{"repo_name": "CellChat", "file_name": "/CellChat/R/CellChat_class.R", "inference_info": {"prefix_code": "\n#' The CellChat Class\n#'\n#' The CellChat object is created from a single-cell transcriptomic data matrix, Seurat V3 or SingleCellExperiment object.\n#' When inputting an data matrix, it takes a digital data matrices as input. Genes should be in rows and cells in columns. rownames and colnames should be included.\n#' The class provides functions for data preprocessing, intercellular communication network inference, communication network analysis, and visualization.\n#'\n#'\n#'# Class definitions\n#' @importFrom methods setClassUnion\n#' @importClassesFrom Matrix dgCMatrix\nsetClassUnion(name = 'AnyMatrix', members = c(\"matrix\", \"dgCMatrix\"))\nsetClassUnion(name = 'AnyFactor', members = c(\"factor\", \"list\"))\n\n#' The key slots used in the CellChat object are described below.\n#'\n#' @slot data.raw raw count data matrix\n#' @slot data normalized data matrix for CellChat analysis (Genes should be in rows and cells in columns)\n#' @slot data.signaling a subset of normalized matrix only containing signaling genes\n#' @slot data.scale scaled data matrix\n#' @slot data.smooth smoothed data\n#' @slot images a list of information of spatial transcriptomics data\n#' @slot net a three-dimensional array P (K×K×N), where K is the number of cell groups and N is the number of ligand-receptor pairs. Each row of P indicates the communication probability originating from the sender cell group to other cell groups.\n#' @slot netP a three-dimensional array representing cel-cell communication networks on a signaling pathway level\n#' @slot DB ligand-receptor interaction database used in the analysis (a subset of CellChatDB)\n#' @slot LR a list of information related with ligand-receptor pairs\n#' @slot meta data frame storing the information associated with each cell\n#' @slot idents a factor defining the cell identity used for all analysis. It becomes a list for a merged CellChat object\n#' @slot var.features A list: one element is a vector consisting of the identified over-expressed signaling genes; one element is a data frame returned from the differential expression analysis\n#' @slot dr List of the reduced 2D coordinates, one per method, e.g., umap/tsne/dm\n#' @slot options List of miscellaneous data, such as parameters used throughout analysis, and a indicator whether the CellChat object is a single or merged\n#'\n#' @exportClass CellChat\n#' @importFrom Rcpp evalCpp\n#' @importFrom methods setClass\n# #' @useDynLib CellChat\nCellChat <- methods::setClass(\"CellChat\",\n slots = c(data.raw = 'AnyMatrix',\n data = 'AnyMatrix',\n data.signaling = \"AnyMatrix\",\n data.scale = \"matrix\",\n data.smooth = \"AnyMatrix\",\n images = \"list\",\n net = \"list\",\n netP = \"list\",\n meta = \"data.frame\",\n idents = \"AnyFactor\",\n DB = \"list\",\n LR = \"list\",\n var.features = \"list\",\n dr = \"list\",\n options = \"list\")\n)\n#' show method for CellChat\n#'\n#' @param CellChat object\n#' @param show show the object\n#' @param object object\n#' @docType methods\n#'\nsetMethod(f = \"show\", signature = \"CellChat\", definition = function(object) {\n if (object@options$mode == \"single\") {\n cat(\"An object of class\", class(object), \"created from a single dataset\", \"\\n\", nrow(object@data), \"genes.\\n\", ncol(object@data), \"cells. \\n\")\n } else if (object@options$mode == \"merged\") {\n cat(\"An object of class\", class(object), \"created from a merged object with multiple datasets\", \"\\n\", nrow(object@data.signaling), \"signaling genes.\\n\", ncol(object@data.signaling), \"cells. \\n\")\n }\n if (object@options$datatype == \"RNA\") {\n cat(\"CellChat analysis of single cell RNA-seq data! \\n\")\n } else {\n cat(\"CellChat analysis of\", object@options$datatype, \"data! The input spatial locations are \\n\")\n print(head(object@images$coordinates))\n }\n\n\n invisible(x = NULL)\n})\n\n\n\n#' Create a new CellChat object from a data matrix, Seurat or SingleCellExperiment object\n#'\n#' @param object a normalized (NOT count) data matrix (genes by cells), Seurat or SingleCellExperiment object\n#' @param meta a data frame (rows are cells with rownames) consisting of cell information, which will be used for defining cell groups.\n#' If input is a Seurat or SingleCellExperiment object, the meta data in the object will be used\n#' @param group.by a char name of the variable in meta data, defining cell groups.\n#' If input is a data matrix and group.by is NULL, the input `meta` should contain a column named 'labels',\n#' If input is a Seurat or SingleCellExperiment object, USER must provide `group.by` to define the cell groups. e.g, group.by = \"ident\" for Seurat object\n#' @param datatype By default datatype = \"RNA\"; when running CellChat on spatial imaging data, set datatype = \"spatial\" and input `spatial.factors`\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param spatial.factors a data frame containing two distance factors `ratio` and `tol`, which is dependent on spatial transcriptomics technologies (and specific datasets).\n#'\n#' USER must input this data frame when datatype = \"spatial\". spatial.factors must contain an element named `ratio`, which is the conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns). For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates,\n#'\n#' and another element named `tol`, which is the tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um. If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the cell center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance. Of note, CellChat does not need an accurate tolerance factor, which is used for determining whether considering the cell-pair as spatially proximal if their distance is greater than `interaction.range` but smaller than \"`interaction.range` + `tol`\".\n#'\n#'\n#' @param assay Assay to use when the input is a Seurat or SingleCellExperiment object. NB: The data in the `integrated` assay in Seurat is not suitable for CellChat analysis because it contains negative values.\n#' @param do.sparse whether use sparse format\n#'\n#' @return\n#' @export\n#' @importFrom methods as new\n#' @examples\n#' \\dontrun{\n#' Create a CellChat object from single-cell transcriptomics data\n#' # Input is a data matrix\n#' ## create a dataframe consisting of the cell labels\n#' meta = data.frame(labels = cell.labels, row.names = names(cell.labels))\n#' cellChat <- createCellChat(object = data.input, meta = meta, group.by = \"labels\")\n#'\n#' # input is a Seurat object\n#' ## use the default cell identities of Seurat object\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"ident\", assay = \"RNA\")\n#' ## use other meta information as cell groups\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"seurat.clusters\")\n#'\n#' # input is a SingleCellExperiment object\n#' cellChat <- createCellChat(object = sce.obj, group.by = \"sce.clusters\")\n#'\n#' # input is a AnnData object\n#' sce <- zellkonverter::readH5AD(file = \"adata.h5ad\")\n#' assayNames(sce) # retrieve all the available assays within sce object\n#' counts <- assay(sce, \"X\") # add a new assay entry \"logcounts\" if not available and make sure this is the original count data matrix\n#' library.size <- Matrix::colSums(counts)\n#' logcounts(sce) <- log1p(Matrix::t(Matrix::t(counts)/library.size) * 10000)\n#' meta <- as.data.frame(SingleCellExperiment::colData(sce))\n#' cellChat <- createCellChat(object = sce, group.by = \"sce.clusters\")\n#'\n#'\n#' Create a CellChat object from spatial transcriptomics data\n#' # Input is a data matrix\n#' cellChat <- createCellChat(object = data.input, meta = meta, group.by = \"labels\",\n#' datatype = \"spatial\", coordinates = coordinates, spatial.factors = spatial.factors)\n#'\n#' # input is a Seurat object\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"ident\", assay = \"SCT\",\n#' datatype = \"spatial\", spatial.factors = spatial.factors)\n#'\n#' }\ncreateCellChat <- ", "suffix_code": "\n\n\n#' Merge CellChat objects\n#'\n#' @param object.list A list of multiple CellChat objects\n#' @param add.names A vector containing the name of each dataset\n#' @param merge.data whether merging the data for ALL genes. Default only merges the data of signaling genes\n#' @param cell.prefix whether prefix cell names\n#' @importFrom methods slot new\n#'\n#' @return\n#' @export\n#'\n#' @examples\nmergeCellChat <- function(object.list, add.names = NULL, merge.data = FALSE, cell.prefix = FALSE) {\n if (is.null(add.names)) {\n add.names <- paste(\"Dataset\",1:length(object.list),sep = \"_\")\n }\n slot.name <- c(\"net\", \"netP\", \"idents\" ,\"LR\", \"var.features\", \"images\")\n slot.combined <- vector(\"list\", length(slot.name))\n names(slot.combined) <- slot.name\n for (i in 1:length(slot.name)) {\n object.slot <- vector(\"list\", length(object.list))\n for (j in 1:length(object.list)) {\n object.slot[[j]] <- slot(object.list[[j]], slot.name[i])\n }\n slot.combined[[i]] <- object.slot\n names(slot.combined[[i]]) <- add.names\n }\n\n if (cell.prefix) {\n warning(\"Prefix cell names!\")\n for (i in 1:length(object.list)) {colnames(object.list[[i]]@data) <- paste(colnames(object.list[[i]]@data), add.names[i], sep = \"_\")}\n } else {\n cell.names <- c()\n for (i in 1:length(object.list)) {\n cell.names <- c(cell.names, colnames(object.list[[i]]@data))\n }\n if (sum(duplicated(cell.names))) {\n stop(\"Duplicated cell names were detected across datasets!! Please set cell.prefix = TRUE\")\n }\n }\n\n meta.use <- colnames(object.list[[1]]@meta)\n for (i in 2:length(object.list)) {\n meta.use <- meta.use[meta.use %in% colnames(object.list[[i]]@meta)]\n }\n\n dataset.name <- c()\n cell.names <- c()\n meta.joint <- data.frame()\n for (i in 1:length(object.list)) {\n dataset.name <- c(dataset.name, rep(add.names[i], length(colnames(object.list[[i]]@data))))\n cell.names <- c(cell.names, colnames(object.list[[i]]@data))\n meta.joint <- rbind(meta.joint, object.list[[i]]@meta[ , meta.use, drop = FALSE])\n }\n if (!identical(rownames(meta.joint), cell.names)) {\n cat(\"The cell barcodes in merged 'meta' is \", head(rownames(meta.joint)),'\\n')\n warning(\"The cell barcodes in merged 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of merged 'mata'!\")\n rownames(meta.joint) <- cell.names\n }\n\n #dataset.name <- data.frame(dataset.name = dataset.name, row.names = cell.names)\n meta.joint$datasets <- factor(dataset.name, levels = add.names)\n\n genes.use <- rownames(object.list[[1]]@data)\n for (i in 2:length(object.list)) {\n genes.use <- genes.use[genes.use %in% rownames(object.list[[i]]@data)]\n }\n data.joint <- c()\n for (i in 1:length(object.list)) {\n data.joint <- cbind(data.joint, object.list[[i]]@data[genes.use, ])\n }\n gene.signaling.joint = unique(unlist(lapply(object.list, function(x) rownames(x@data.signaling))))\n data.signaling.joint <- data.joint[rownames(data.joint) %in% gene.signaling.joint, ]\n\n idents.joint <- c()\n idents.levels <- c()\n for (i in 1:length(object.list)) {\n idents.joint <- c(idents.joint, as.character(object.list[[i]]@idents))\n idents.levels <- union(idents.levels, levels(object.list[[i]]@idents))\n }\n names(idents.joint) <- cell.names\n idents.joint <- factor(idents.joint, levels = idents.levels)\n slot.combined$idents$joint <- idents.joint\n\n if (merge.data) {\n message(\"Merge the following slots: 'data','data.signaling','images','net', 'netP','meta', 'idents', 'var.features', 'DB', and 'LR'.\")\n merged.object <- methods::new(\n Class = \"CellChat\",\n data = data.joint,\n data.signaling = data.signaling.joint,\n images = slot.combined$images,\n net = slot.combined$net,\n netP = slot.combined$netP,\n meta = meta.joint,\n idents = slot.combined$idents,\n var.features = slot.combined$var.features,\n LR = slot.combined$LR,\n DB = object.list[[1]]@DB)\n } else {\n message(\"Merge the following slots: 'data.signaling','images','net', 'netP','meta', 'idents', 'var.features' , 'DB', and 'LR'.\")\n merged.object <- methods::new(\n Class = \"CellChat\",\n data.signaling = data.signaling.joint,\n images = slot.combined$images,\n net = slot.combined$net,\n netP = slot.combined$netP,\n meta = meta.joint,\n idents = slot.combined$idents,\n var.features = slot.combined$var.features,\n LR = slot.combined$LR,\n DB = object.list[[1]]@DB)\n }\n merged.object@options$mode <- \"merged\"\n\n datatype.joint <- c()\n for (j in 1:length(object.list)) {\n datatype.joint <- union(datatype.joint, slot(object.list[[j]], \"options\")$datatype)\n }\n if (length(datatype.joint) == 1){\n merged.object@options$datatype <- datatype.joint\n } else {\n message(\"The data types in these objects are \", datatype.joint,'\\n')\n stop(\"Comparison analysis is not suggested for different types of data.\")\n }\n return(merged.object)\n}\n\n\n\n#' Update a single CellChat object\n#'\n#' Update a single previously calculated CellChat object for spatial transcriptomics data analysis (version < 2.1.0)\n#'\n#' Update a single previously calculated CellChat object (version < 1.6.0)\n#'\n#' version < 0.5.0: `object@var.features` is now `object@var.features$features`; `object@net$sum` is now `object@net$weight` if `aggregateNet` has been run.\n#'\n#' version 1.6.0: a `object@images` slot is added and `datatype` is added in `object@options$datatype`\n#'\n#' version 2.1.0: a column named `slices` is added in `meta` data for spatial transcriptomics data analysis.\n#'\n#' version 2.1.1: `images$scale.factors` is changed to `images$spatial.factors` for spatial transcriptomics data analysis.\n#'\n#' version 2.1.2: the column `slices` in `object@meta` is renamed as `samples` in order to identify consistent signaling across samples for cell-cell communication analysis.\n#'\n#' version 2.1.3: the slot `object@data.project` is renamed as `object@data.smooth`.\n#'\n#' @param object CellChat object\n#'\n#' @return a updated CellChat object\n#' @export\n#'\nupdateCellChat <- function(object) {\n DB <- object@DB\n # interaction_input <- DB$interaction\n # if ((\"category\" %in% colnames(interaction_input) == FALSE) & (\"annotation\" %in% colnames(interaction_input) == TRUE)) {\n # message(\"Change the column name `annotation` in object@DB$interaction to `category` since CellChat v2\")\n # colnames(interaction_input) <- plyr::mapvalues(colnames(interaction_input),from = c(\"annotation\"), to = c(\"category\"), warn_missing = TRUE)\n # DB$interaction <- interaction_input\n # }\n if (is.character(object@var.features)) {\n message(\"Update slot 'var.features' from a vector to a list\")\n var.features.new <- list(features = object@var.features)\n } else {\n var.features.new <- object@var.features\n }\n if (\"sum\" %in% names(object@net)) {\n net <- object@net\n net$weight <- net$sum\n } else {\n net <- object@net\n }\n if (!(\"mode\" %in% names(object@options))) {\n object@options$mode <- \"single\"\n }\n if (!(\"datatype\" %in% names(object@options))) {\n object@options$datatype <- \"RNA\"\n images = list()\n } else {\n images = object@images\n }\n meta = object@meta\n if (\"slices\" %in% colnames(meta)) {\n meta$samples <- meta$slices\n meta$slices = NULL\n }\n if (!(\"samples\" %in% colnames(meta))) {\n warning(\"The 'meta' data does not have a column named `samples`. We now add this column and all cells are assumed to belong to `sample1`!\")\n meta$samples <- \"sample1\"\n meta$samples <- factor(meta$samples)\n } else if (is.factor(meta$samples) == FALSE) {\n warning(\"The 'meta$samples' is not a factor. We now force it as a factor!\")\n meta$samples <- factor(meta$samples)\n }\n if (object@options$datatype %in% c(\"spatial\")) {\n if (\"scale.factors\" %in% names(object@images)) {\n images$spatial.factors <- as.data.frame(images$scale.factors)\n images$scale.factors <- NULL\n }\n }\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n data.smooth <- object@data.project\n } else {\n data.smooth <- object@data.smooth\n }\n object.new <- methods::new(\n Class = \"CellChat\",\n data.raw = object@data.raw,\n data = object@data,\n data.signaling = object@data.signaling,\n data.scale = object@data.scale,\n data.smooth = data.smooth,\n images = images,\n net = net,\n netP = object@netP,\n meta = meta,\n idents = object@idents,\n DB = DB,\n LR = object@LR,\n var.features = var.features.new,\n dr = object@dr,\n options = object@options\n )\n return(object.new)\n}\n\n#' Update a CellChat object by lifting up the cell groups to the same cell labels across all datasets\n#'\n#' This function is useful when comparing inferred communications across different datasets with different cellular compositions\n#'\n#' @param object A single or merged CellChat object\n#' @param group.new A char vector giving the cell labels to lift up. The order of cell labels in the vector will be used for setting the new cell identity.\n#'\n#' If the input is a merged CellChat object and group.new = NULL, it will use the cell labels from one dataset with the maximum number of cell groups\n#'\n#' If the input is a single CellChat object, `group.new` must be defined.\n#'\n#' @return a updated CellChat object\n#'\n#' @export\n#'\nliftCellChat <- function(object, group.new = NULL) {\n if (object@options$mode == \"merged\") {\n idents <- object@idents[1:(length(object@idents)-1)]\n if (is.null(group.new)) {\n group.max.all <- unique(unlist(sapply(idents, levels)))\n group.num <- sapply(idents, nlevels)\n group.num.max <- max(group.num)\n group.max <- levels(idents[[which(group.num == group.num.max)]])\n if (length(group.max) != length(group.max.all)) {\n stop(\"CellChat object cannot lift up due to the missing cell groups in any dataset. Please define the parameter `group.new`!\")\n }\n } else {\n group.max <- group.new\n group.num.max <- length(group.new)\n }\n message(paste0(\"The CellChat object will be lifted up using the cell labels \", paste(group.max, collapse=\", \")))\n for (i in 1:length(idents)) {\n cat(\"Update slots object@net, object@netP, object@idents in dataset \", names(object@idents)[i],'\\n')\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net[[i]]\n group.i <- levels(idents[[i]])\n # group.existing <- group.max[group.max %in% group.i]\n group.existing <- group.i[group.i %in% group.max]\n group.existing.index <- which(group.max %in% group.existing)\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max),\n dimnames = list(group.max, group.max))\n values.new[group.existing.index, group.existing.index] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"pairwiseRank\")) {\n for (k in 1:length(values)) {\n values.new1 <- vector(\"list\", group.num.max)\n values.new1[group.existing.index] <- values[[k]]\n temp <- values[[k]][[1]]\n temp$prob <- 0; temp$pval <- 1\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new1[[kk]] <- temp\n }\n names(values.new1) <- group.max\n values[[k]] <- values.new1\n }\n values.new <- vector(\"list\", group.num.max)\n values.new[group.existing.index] <- values\n temp <- lapply(values.new1, function(x) {\n x$prob <- 0; x$pval <- 1\n return(x)\n })\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new[[kk]] <- temp\n }\n names(values.new) <- group.max\n }\n net[[net.j]] <- values.new\n }\n object@net[[i]] <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n netP <- object@netP[[i]]\n for (netP.j in names(netP)) {\n values <- netP[[netP.j]]\n if (netP.j %in% c(\"pathways\")) {\n values.new <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"prob\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"centr\")) {\n for (k in 1:length(values)) {\n values.new <- lapply(values, function(x) {\n values.new2 <- lapply(x, function(x) {\n values.new1 = as.vector(matrix(0, nrow = 1, ncol = group.num.max))\n values.new1[group.existing.index] <- x\n names(values.new1) <- group.max\n return(values.new1)\n })\n names(values.new2) <- names(x)\n return(values.new2)\n })\n names(values.new) <- names(values)\n }\n netP[[netP.j]] <- values.new\n }\n\n }\n object@netP[[i]] <- netP\n # cat(\"Update slot object@idents...\", '\\n')\n # idents[[i]] <- factor(group.max, levels = group.max)\n idents[[i]] <- factor(idents[[i]], levels = group.max)\n }\n object@idents[1:(length(object@idents)-1)] <- idents\n } else {\n if (is.null(group.new)) {\n stop(\"Please define the parameter `group.new`!\")\n } else {\n group.max <- as.character(group.new)\n group.num.max <- length(group.new)\n message(paste0(\"The CellChat object will be lifted up using the cell labels \", paste(group.max, collapse=\", \")))\n }\n cat(\"Update slots object@net, object@netP, object@idents in a single dataset...\", '\\n')\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net\n idents <- object@idents\n group.i <- levels(idents)\n # group.existing <- group.max[group.max %in% group.i]\n group.existing <- group.i[group.i %in% group.max]\n group.existing.index <- which(group.max %in% group.existing)\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max),\n dimnames = list(group.max, group.max))\n values.new[group.existing.index, group.existing.index] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"pairwiseRank\")) {\n for (k in 1:length(values)) {\n values.new1 <- vector(\"list\", group.num.max)\n values.new1[group.existing.index] <- values[[k]]\n temp <- values[[k]][[1]]\n temp$prob <- 0; temp$pval <- 1\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new1[[kk]] <- temp\n }\n names(values.new1) <- group.max\n values[[k]] <- values.new1\n }\n values.new <- vector(\"list\", group.num.max)\n values.new[group.existing.index] <- values\n temp <- lapply(values.new1, function(x) {\n x$prob <- 0; x$pval <- 1\n return(x)\n })\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new[[kk]] <- temp\n }\n names(values.new) <- group.max\n }\n net[[net.j]] <- values.new\n }\n object@net <- net\n\n\n # cat(\"Update slot object@netP...\", '\\n')\n netP <- object@netP\n for (netP.j in names(netP)) {\n values <- netP[[netP.j]]\n if (netP.j %in% c(\"pathways\")) {\n values.new <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"prob\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"centr\")) {\n for (k in 1:length(values)) {\n values.new <- lapply(values, function(x) {\n values.new2 <- lapply(x, function(x) {\n values.new1 = as.vector(matrix(0, nrow = 1, ncol = group.num.max))\n values.new1[group.existing.index] <- x\n names(values.new1) <- group.max\n return(values.new1)\n })\n names(values.new2) <- names(x)\n return(values.new2)\n })\n names(values.new) <- names(values)\n }\n }\n netP[[netP.j]] <- values.new\n }\n object@netP <- netP\n\n # cat(\"Update slot object@idents...\", '\\n')\n idents <- factor(idents, levels = group.max)\n object@idents <- idents\n }\n\n return(object)\n}\n\n\n#' Subset CellChat object using a portion of cells\n#'\n#' @param object A CellChat object (either an object from a single dataset or a merged objects from multiple datasets)\n#' @param cells.use a char vector giving the cell barcodes to subset. If cells.use = NULL, USER must define `idents.use`\n#' @param idents.use a subset of cell groups used for analysis\n#' @param group.by cell group information; default is `object@idents`; otherwise it should be one of the column names of the meta slot\n#' @param invert whether invert the idents.use\n#' @param thresh threshold of the p-value for determining significant interaction. A parameter as an input of the function `computeCommunProbPathway`\n#' @importFrom methods slot new\n#'\n#' @return\n#' @export\n#'\nsubsetCellChat <- function(object, cells.use = NULL, idents.use = NULL, group.by = NULL, invert = FALSE, thresh = 0.05) {\n if (!is.null(idents.use)) {\n if (is.null(group.by)) {\n labels <- object@idents\n if (object@options$mode == \"merged\") {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n level.use0 <- levels(labels)\n level.use <- levels(labels)[levels(labels) %in% unique(labels)]\n\n if (invert) {\n level.use <- level.use[!(level.use %in% idents.use)]\n } else {\n level.use <- level.use[level.use %in% idents.use]\n }\n cells.use.index <- which(as.character(labels) %in% level.use)\n cells.use <- names(labels)[cells.use.index]\n } else if (!is.null(cells.use)) {\n labels <- object@idents\n if (object@options$mode == \"merged\") {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n level.use0 <- levels(labels)\n level.use <- levels(labels)[levels(labels) %in% unique(as.character(labels[cells.use]))]\n cells.use.index <- which(names(labels) %in% cells.use)\n } else {\n stop(\"USER should define either `cells.use` or `idents.use`!\")\n }\n cat(\"The subset of cell groups used for CellChat analysis are \", level.use, '\\n')\n\n if (nrow(object@data) > 0) {\n data.subset <- object@data[, cells.use.index]\n } else {\n data.subset <- matrix(0, nrow = 0, ncol = 0)\n }\n if (nrow(object@data.smooth) > 0) {\n data.smooth.subset <- object@data.smooth[, cells.use.index]\n } else {\n data.smooth.subset <- matrix(0, nrow = 0, ncol = 0)\n }\n data.signaling.subset <- object@data.signaling[, cells.use.index]\n\n meta.subset <- object@meta[cells.use.index, , drop = FALSE]\n\n\n if (object@options$mode == \"merged\") {\n idents <- object@idents[1:(length(object@idents)-1)]\n group.existing <- level.use0[level.use0 %in% level.use]\n group.existing.index <- which(level.use0 %in% level.use)\n net.subset <- vector(\"list\", length = length(object@net))\n netP.subset <- vector(\"list\", length = length(object@netP))\n idents.subset <- vector(\"list\", length = length(idents))\n names(net.subset) <- names(object@net)\n names(netP.subset) <- names(object@netP)\n names(idents.subset) <- names(object@idents[1:(length(object@idents)-1)])\n images.subset <- vector(\"list\", length = length(idents))\n names(images.subset) <- names(object@idents[1:(length(object@idents)-1)])\n\n for (i in 1:length(idents)) {\n cat(\"Update slots object@images, object@net, object@netP, object@idents in dataset \", names(object@idents)[i],'\\n')\n images <- object@images[[i]]\n for (images.j in names(images)) {\n values <- images[[images.j]]\n if (images.j %in% c(\"coordinates\")) {\n values.new <- values[cells.use.index, ]\n images[[images.j]] <- values.new\n }\n if (images.j %in% c(\"distance\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n images[[images.j]] <- values.new\n }\n }\n images.subset[[i]] <- images\n\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net[[i]]\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- values[group.existing.index, group.existing.index, , drop = FALSE]\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n net[[net.j]] <- values.new\n }\n # net[[net.j]] <- values.new\n }\n net.subset[[i]] <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n # netP <- object@netP[[i]]\n # for (netP.j in names(netP)) {\n # values <- netP[[netP.j]]\n # if (netP.j %in% c(\"pathways\")) {\n # values.new <- values\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"prob\")) {\n # values.new <- values[group.existing.index, group.existing.index, ]\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"centr\")) {\n # for (k in 1:length(values)) {\n # values.new <- lapply(values, function(x) {\n # values.new2 <- lapply(x, function(x) {\n # values.new1 <- x[group.existing.index]\n # names(values.new1) <- group.existing\n # return(values.new1)\n # })\n # names(values.new2) <- names(x)\n # return(values.new2)\n # })\n # names(values.new) <- names(values)\n # }\n # }\n # netP[[netP.j]] <- values.new\n # }\n netP = computeCommunProbPathway(net = net.subset[[i]], pairLR.use = object@LR[[i]]$LRsig, thresh = thresh)\n netP$centr = netAnalysis_computeCentrality(net = net.subset[[i]]$prob)\n netP.subset[[i]] <- netP\n idents.subset[[i]] <- idents[[i]][names(idents[[i]]) %in% cells.use]\n idents.subset[[i]] <- factor(idents.subset[[i]], levels = levels(idents[[i]])[levels(idents[[i]]) %in% level.use])\n }\n idents.subset$joint <- factor(object@idents$joint[cells.use.index], levels = level.use)\n\n } else {\n cat(\"Update slots object@images, object@net, object@netP in a single dataset...\", '\\n')\n\n group.existing <- level.use0[level.use0 %in% level.use]\n group.existing.index <- which(level.use0 %in% level.use)\n\n images <- object@images\n for (images.j in names(images)) {\n values <- images[[images.j]]\n if (images.j %in% c(\"coordinates\")) {\n values.new <- values[cells.use.index, ]\n images[[images.j]] <- values.new\n }\n if (images.j %in% c(\"distance\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n images[[images.j]] <- values.new\n }\n }\n images.subset <- images\n\n\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- values[group.existing.index, group.existing.index, , drop = FALSE]\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n net[[net.j]] <- values.new\n }\n }\n net.subset <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n # netP <- object@netP\n # for (netP.j in names(netP)) {\n # values <- netP[[netP.j]]\n # if (netP.j %in% c(\"pathways\")) {\n # values.new <- values\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"prob\")) {\n # values.new <- values[group.existing.index, group.existing.index, ]\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"centr\")) {\n # for (k in 1:length(values)) {\n # values.new <- lapply(values, function(x) {\n # values.new2 <- lapply(x, function(x) {\n # values.new1 <- x[group.existing.index]\n # names(values.new1) <- group.existing\n # return(values.new1)\n # })\n # names(values.new2) <- names(x)\n # return(values.new2)\n # })\n # names(values.new) <- names(values)\n # }\n # }\n # netP[[netP.j]] <- values.new\n # }\n netP = computeCommunProbPathway(net = net.subset, pairLR.use = object@LR$LRsig, thresh = thresh)\n netP$centr = netAnalysis_computeCentrality(net = net.subset$prob)\n netP.subset <- netP\n idents.subset <- object@idents[cells.use.index]\n idents.subset <- factor(idents.subset, levels = level.use)\n }\n\n\n object.subset <- methods::new(\n Class = \"CellChat\",\n data = data.subset,\n data.signaling = data.signaling.subset,\n data.smooth = data.smooth.subset,\n images = images.subset,\n net = net.subset,\n netP = netP.subset,\n meta = meta.subset,\n idents = idents.subset,\n var.features = object@var.features,\n LR = object@LR,\n DB = object@DB,\n options = object@options\n )\n return(object.subset)\n}\n\n\n", "middle_code": "function(object, meta = NULL, group.by = NULL,\n datatype = c(\"RNA\", \"spatial\"), coordinates = NULL, spatial.factors = NULL,\n assay = NULL, do.sparse = T) {\n datatype <- match.arg(datatype)\n if (inherits(x = object, what = c(\"matrix\", \"Matrix\", \"dgCMatrix\", \"dgRMatrix\",\"CsparseMatrix\"))) {\n print(\"Create a CellChat object from a data matrix\")\n data <- object\n if (is.null(group.by)) {\n group.by <- \"labels\"\n }\n }\n if (is(object,\"Seurat\")) {\n .error_if_no_Seurat()\n print(\"Create a CellChat object from a Seurat object\")\n if (is.null(assay)) {\n assay = Seurat::DefaultAssay(object)\n if (assay == \"integrated\") {\n warning(\"The data in the `integrated` assay is not suitable for CellChat analysis! Please use the `RNA`, `SCT` or `Spatial` assay! \")\n }\n cat(paste0(\"The `data` slot in the default assay is used. The default assay is \", assay),'\\n')\n }\n if (packageVersion(\"Seurat\") < \"5.0.0\") {\n data <- object[[assay]]@data\n } else {\n data <- object[[assay]]$data\n }\n if (min(data) < 0) {\n stop(\"The data matrix contains negative values. Please ensure the normalized data matrix is used.\")\n }\n if (is.null(meta)) {\n cat(\"The `meta.data` slot in the Seurat object is used as cell meta information\",'\\n')\n meta <- object@meta.data\n meta$ident <- Seurat::Idents(object)\n }\n if (is.null(group.by)) {\n group.by <- \"ident\"\n }\n if (datatype %in% c(\"spatial\")) {\n if (is.null(coordinates)) {\n coordinates <- Seurat::GetTissueCoordinates(object, scale = NULL, cols = c(\"imagerow\", \"imagecol\"))\n }\n }\n }\n if (is(object,\"SingleCellExperiment\")) {\n print(\"Create a CellChat object from a SingleCellExperiment object\")\n if (is.null(assay)) {\n assay = \"logcounts\"\n }\n if (assay %in% SummarizedExperiment::assayNames(object)) {\n cat(paste0(\"The data in the \", assay, \" assay is used! \"),'\\n')\n data <- SummarizedExperiment::assay(object, assay)\n } else {\n stop(\"SingleCellExperiment object must contain an assay named `logcounts` or the input assay name! Please check the available assaynames via `assayNames(object)`. \\n\")\n }\n if (is.null(meta)) {\n cat(\"The `colData` assay in the SingleCellExperiment object is used as cell meta information\",'\\n')\n meta <- as.data.frame(SingleCellExperiment::colData(object))\n }\n if (is.null(group.by)) {\n stop(\"`group.by` should be defined!\")\n }\n }\n if (!inherits(x = data, what = c(\"dgCMatrix\")) & do.sparse) {\n if (inherits(x = data, what = c(\"dgRMatrix\"))) {\n data <- as(data, \"CsparseMatrix\")\n }\n data <- as(data, \"dgCMatrix\")\n }\n if (!is.null(meta)) {\n if (inherits(x = meta, what = c(\"matrix\", \"Matrix\",\"DataFrame\"))) {\n meta <- as.data.frame(x = meta)\n }\n if (!is.data.frame(meta)) {\n stop(\"The input `meta` should be a data frame\")\n }\n if (!identical(rownames(meta), colnames(data))) {\n cat(\"The cell barcodes in 'meta' is \", head(rownames(meta)),'\\n')\n warning(\"The cell barcodes in 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of 'mata'!\")\n rownames(meta) <- colnames(data)\n }\n } else {\n meta <- data.frame()\n }\n if (datatype %in% c(\"spatial\")) {\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n if (is.null(spatial.factors) | !(\"ratio\" %in% names(spatial.factors)) | !(\"tol\" %in% names(spatial.factors))) {\n stop(\"spatial.factors with colnames `ratio` and `tol` should be provided!\")\n } else {\n images = list(\"coordinates\" = coordinates,\n \"spatial.factors\" = spatial.factors)\n }\n cat(\"Create a CellChat object from spatial transcriptomics data...\",'\\n')\n } else {\n images <- list()\n }\n object <- methods::new(Class = \"CellChat\",\n data = data,\n images = images,\n meta = meta)\n if (!is.null(meta) & nrow(meta) > 0) {\n if (!(\"samples\" %in% colnames(meta))) {\n warning(\"The 'meta' data does not have a column named `samples`. We now add this column and all cells are assumed to belong to `sample1`! \\n\")\n meta$samples <- \"sample1\"\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n } else if (is.factor(meta$samples) == FALSE) {\n warning(\"The 'meta$samples' is not a factor. We now force it as a factor! \\n\")\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n }\n cat(\"Set cell identities for the new CellChat object\", '\\n')\n if (!(group.by %in% colnames(meta))) {\n stop(\"The 'group.by' is not a column name in the `meta`, which will be used for cell grouping.\")\n }\n object <- setIdent(object, ident.use = group.by) \n cat(\"The cell groups used for CellChat analysis are \", toString(levels(object@idents)), '\\n')\n }\n object@options$mode <- \"single\"\n object@options$datatype <- datatype\n return(object)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/CellChat/R/utilities.R", "#' Normalize data using a scaling factor\n#'\n#' @param data.raw input raw data\n#' @param scale.factor the scaling factor used for each cell\n#' @param do.log whether to do log transformation with pseudocount 1\n#' @param do.sparse whether to use sparse format\n#' @export\n#'\nnormalizeData <- function(data.raw, scale.factor = 10000, do.log = TRUE, do.sparse = TRUE) {\n # Scale counts within a sample\n library.size <- Matrix::colSums(data.raw)\n #scale.factor <- median(library.size)\n expr <- Matrix::t(Matrix::t(data.raw) / library.size) * scale.factor\n if (do.log) {\n data.norm <-log1p(expr)\n }\n if (do.sparse) {\n data.input <- as(data.norm, \"dgCMatrix\")\n }\n return(data.norm)\n}\n\n\n#' Scale the data\n#'\n#' @param data.use input data\n#' @param do.center whether center the values\n#' @export\n#'\nscaleData <- function(data.use, do.center = T) {\n data.use <- Matrix::t(scale(Matrix::t(data.use), center = do.center, scale = TRUE))\n return(data.use)\n}\n\n\n#' Scale a data matrix\n#'\n#' @param x data matrix\n#' @param scale the method to scale the data\n#' @param na.rm whether remove na\n#' @importFrom Matrix rowMeans colMeans rowSums colSums\n#' @return\n#' @export\n#'\n#' @examples\nscaleMat <- function(x, scale, na.rm=TRUE){\n\n av <- c(\"none\", \"row\", \"column\", 'r1', 'c1')\n i <- pmatch(scale, av)\n if(is.na(i) )\n stop(\"scale argument shoud take values: 'none', 'row' or 'column'\")\n scale <- av[i]\n\n switch(scale, none = x\n , row = {\n x <- sweep(x, 1L, rowMeans(x, na.rm = na.rm), '-',check.margin = FALSE)\n sx <- apply(x, 1L, sd, na.rm = na.rm)\n sweep(x, 1L, sx, \"/\", check.margin = FALSE)\n }\n , column = {\n x <- sweep(x, 2L, colMeans(x, na.rm = na.rm), '-',check.margin = FALSE)\n sx <- apply(x, 2L, sd, na.rm = na.rm)\n sweep(x, 2L, sx, \"/\", check.margin = FALSE)\n }\n , r1 = sweep(x, 1L, rowSums(x, na.rm = na.rm), '/', check.margin = FALSE)\n , c1 = sweep(x, 2L, colSums(x, na.rm = na.rm), '/', check.margin = FALSE)\n )\n}\n\n#' Downsampling single cell data using geometric sketching algorithm\n#'\n#' USERs need to install the python package `pip install geosketch` (https://github.com/brianhie/geosketch)\n#'\n#' @param object A data matrix (should have row names; samples in rows, features in columns) or a Seurat object.\n#'\n#' When object is a PCA or UMAP space, please set `do.PCA = FALSE`\n#'\n#' When object is a data matrix (cells in rows and genes in columns), it is better to use the highly variable genes. PCA will be done on this input data matrix.\n#' @param percent the percent of data to sketch\n#' @param idents A vector of identity classes to keep for sketching\n#' @param do.PCA whether doing PCA on the input data\n#' @param dimPC the number of components to use\n#' @importFrom reticulate import\n#' @return A vector of cell names to use for downsampling\n#' @export\n#'\nsketchData <- function(object, percent, idents = NULL, do.PCA = TRUE, dimPC = 30) {\n # pip install geosketch\n geosketch <- reticulate::import('geosketch')\n if (is(object,\"Seurat\")) {\n sketch.size <- as.integer(percent*ncol(object))\n if (!is.null(idents)) {\n object <- subset(object, idents = idents)\n }\n object <- object %>% #Seurat::NormalizeData(verbose = FALSE) %>%\n FindVariableFeatures(selection.method = \"vst\", nfeatures = 2000) %>%\n RunPCA(pc.genes = object@var.genes, npcs = dimPC, verbose = FALSE)\n\n X.pcs <- object@reductions$pca@cell.embeddings\n cells.all <- Cells(object)\n\n } else {\n # Get top PCs\n if (do.PCA) {\n X.pcs <- runPCA(object, dimPC = dimPC)\n } else {\n X.pcs <- object\n }\n\n # Sketch percent of data.\n sketch.size <- as.integer(percent*nrow(X))\n cells.all <- rownames(object)\n }\n sketch.index <- geosketch$gs(X.pcs, sketch.size)\n sketch.index <- unlist(sketch.index) + 1\n sketch.cells <- cells.all[sketch.index]\n return(sketch.cells)\n}\n\n\n#' Add the cell information into meta slot\n#'\n#' @param object CellChat object\n#' @param meta cell information to be added\n#' @param meta.name the name of column to be assigned\n#'\n#' @return\n#' @export\n#'\n#' @examples\naddMeta <- function(object, meta, meta.name = NULL) {\n if (is.null(x = meta.name) && is.atomic(x = meta)) {\n stop(\"'meta.name' must be provided for atomic meta types (eg. vectors)\")\n }\n if (inherits(x = meta, what = c(\"matrix\", \"Matrix\"))) {\n meta <- as.data.frame(x = meta)\n }\n\n if (is.null(x = meta.name)) {\n meta.name <- names(meta)\n } else {\n names(meta) <- meta.name\n }\n object@meta <- meta\n return(object)\n}\n\n\n#' Set the default identity of cells\n#' @param object CellChat object\n#' @param ident.use the name of the variable in object.meta;\n#' @param levels set the levels of factor\n#' @param display.warning whether display the warning message\n#' @return\n#' @export\n#'\n#' @examples\nsetIdent <- function(object, ident.use = NULL, levels = NULL, display.warning = TRUE){\n if (!is.null(ident.use)) {\n object@idents <- as.factor(object@meta[[ident.use]])\n }\n\n if (!is.null(levels)) {\n object@idents <- factor(object@idents, levels = levels)\n }\n if (\"0\" %in% as.character(object@idents)) {\n stop(\"Cell labels cannot contain `0`! \")\n }\n if (length(object@net) > 0) {\n if (all(dimnames(object@net$prob)[[1]] %in% levels(object@idents) )) {\n message(\"Reorder cell groups! \")\n cat(\"The cell group order before reordering is \", dimnames(object@net$prob)[[1]],'\\n')\n # idx <- match(dimnames(object@net$prob)[[1]], levels(object@idents))\n idx <- match(levels(object@idents), dimnames(object@net$prob)[[1]])\n object@net$prob <- object@net$prob[idx, , ]\n object@net$prob <- object@net$prob[, idx, ]\n object@net$pval <- object@net$pval[idx, , ]\n object@net$pval <- object@net$pval[, idx, ]\n cat(\"The cell group order after reordering is \", dimnames(object@net$prob)[[1]],'\\n')\n } else {\n message(\"Rename cell groups but do not change the order! \")\n cat(\"The cell group order before renaming is \", dimnames(object@net$prob)[[1]],'\\n')\n dimnames(object@net$prob) <- list(levels(object@idents), levels(object@idents), dimnames(object@net$prob)[[3]])\n dimnames(object@net$pval) <- dimnames(object@net$prob)\n cat(\"The cell group order after renaming is \", dimnames(object@net$prob)[[1]],'\\n')\n }\n if (display.warning) {\n warning(\"All the calculations after `computeCommunProb` should be re-run!!\n These include but not limited to `computeCommunProbPathway`,`aggregateNet`, and `netAnalysis_computeCentrality`.\")\n }\n\n\n }\n return(object)\n}\n\n\n#' Add a reduced space of the data into CellChat object\n#'\n#' @param object CellChat object from a single dataset\n#' @param dr A data frame (rows are cells with rownames) consisting of a low-dimensional space for visualization\n#' @param dr.name A char name of the reduction method for the input `dr`\n#' @param seu.obj A Seurat object with the reduced space of the data\n#' @param dr.use A char name of the reduction method to use when taking `seu.obj` as input. By default, all reduced space in `seu.obj` will be added in `object@dr`\n#' @param force.add Whether to force to add a new reduced space when a reduced space exists in `object@dr`\n#' @return\n#' @export\n#' @examples\n#' \\dontrun{\n#' cellChat <- addReduction(object = cellchat, dr = cell.embeddings, dr.name = \"umap\")\n#'\n#' cellChat <- addReduction(object = cellchat, seu.obj = seu.obj)\n#' }\naddReduction <- function(object, dr = NULL, dr.name = NULL, seu.obj = NULL, dr.use = NULL, force.add = FALSE) {\n if (length(names(object@dr)) > 0) {\n if (!force.add) {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please set `force.add = TRUE` if intending to add a new reduced space. \\n\"))\n }\n }\n if (!is.null(dr)) {\n if (is.null(dr.name)) {\n stop(\"When inputing `dr`, please also provide the `dr.name`! \\n\")\n }\n dr <- as.data.frame(dr)\n if (all(colnames(object@data.signaling) %in% rownames(dr))) {\n object@dr[[dr.name]] <- dr[colnames(object@data.signaling), ]\n } else {\n stop(\"Some cell barcodes in the CellChat object are not the rownames of the input `dr`. Please check the input `dr` and make sure it contains all cells in the CellChat analysis. \\n\")\n }\n } else if(!is.null(seu.obj)) {\n if (!is(seu.obj,\"Seurat\")) {\n stop(\"The input `seu.obj` can be only the Seurat object. \\n\")\n }\n reductions <- names(seu.obj@reductions)\n if (length(reductions) == 0) {\n stop(\"The input `seu.obj` does not contain any low-dimensional space. Please generate a low-dimensional space for visualization. \\n\")\n }\n if (!is.null(dr.use)) {\n reductions <- intersect(reductions, dr.use)\n }\n if (length(reductions) == 0) {\n stop(\"The input `dr.use` is not in the reduced space in `seu.obj`. \\n\")\n }\n for (i in 1:length(reductions)) {\n dr.name <- reductions[i]\n dr = seu.obj@reductions[[dr.name]]@cell.embeddings\n if (all(colnames(object@data.signaling) %in% rownames(dr))) {\n cat(paste0(dr.name, \" is now added in `object@dr` as a low-dimensional space. \\n\"))\n object@dr[[dr.name]] <- dr[colnames(object@data.signaling), ]\n } else {\n stop(\"Some cell barcodes in the CellChat object are not in the input `seu.obj`. Please check the input `seu.obj` and make sure it contains all cells in the CellChat analysis. \\n\")\n }\n }\n } else {\n stop(\"Please input either `dr` or `seu.obj`! \\n\")\n }\n return(object)\n}\n\n\n#' Update and re-order the cell group names after running `computeCommunProb`\n#'\n#' @param object CellChat object\n#' @param old.cluster.name A vector defining old cell group labels in `object@idents`; Default = NULL, which will use `levels(object@idents)`\n#' @param new.cluster.name A vector defining new cell group labels to rename\n#' @param new.order reset order of cell group labels\n#' @param new.cluster.metaname assign a name of the new labels, which will be the column name of new labels in `object@meta`\n#' @return An updated CellChat object\n#' @export\n#'\nupdateClusterLabels <- function(object, old.cluster.name = NULL, new.cluster.name = NULL, new.order = NULL, new.cluster.metaname = \"new.labels\") {\n if (is.null(old.cluster.name)) {\n old.cluster.name <- levels(object@idents)\n }\n if (new.cluster.metaname %in% colnames(object@meta)) {\n stop(\"Please define another `new.cluster.metaname` as it exists in `colnames(object@meta)`!\")\n }\n if (!is.null(new.cluster.name)) {\n labels.new <- plyr::mapvalues(object@idents, from = old.cluster.name, to = new.cluster.name)\n object@meta[[new.cluster.metaname]] <- labels.new\n object <- setIdent(object, ident.use = new.cluster.metaname, display.warning = FALSE)\n } else {\n new.cluster.metaname <- NULL\n cat(\"Only reorder cell groups but do not rename cell groups!\")\n }\n\n if (!is.null(new.order)) {\n object <- setIdent(object, ident.use = new.cluster.metaname, levels = new.order, display.warning = FALSE)\n }\n message(\"We now re-run computeCommunProbPathway`,`aggregateNet`, and `netAnalysis_computeCentrality`...\")\n object <- computeCommunProbPathway(object)\n ## calculate the aggregated network by counting the number of links or summarizing the communication probability\n object <- aggregateNet(object)\n # network importance analysis\n object <-netAnalysis_computeCentrality(object, slot.name = \"netP\")\n return(object)\n}\n\n\n\n\n\n#' Subset the expression data of signaling genes for saving computation cost\n#'\n#' @param object CellChat object\n#' @param features default = NULL: subset the expression data of signaling genes in CellChatDB.use\n#'\n#' @return An updated CellChat object by assigning a subset of the data into the slot `data.signaling`\n#' @export\n#'\nsubsetData <- function(object, features = NULL) {\n interaction_input <- object@DB$interaction\n if (object@options$datatype != \"RNA\") {\n if (\"annotation\" %in% colnames(interaction_input) == FALSE) {\n warning(\"A column named `annotation` is required in `object@DB$interaction` when running CellChat on spatial transcriptomics! The `annotation` column is now automatically added and all L-R pairs are assigned as `Secreted Signaling`, which means that these L-R pairs are assumed to mediate diffusion-based cellular communication.\")\n interaction_input$annotation <- \"Secreted Signaling\"\n }\n }\n if (\"annotation\" %in% colnames(interaction_input) == TRUE) {\n if (length(unique(interaction_input$annotation)) > 1) {\n interaction_input$annotation <- factor(interaction_input$annotation, levels = c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\", \"Cell-Cell Contact\"))\n interaction_input <- interaction_input[order(interaction_input$annotation), , drop = FALSE]\n interaction_input$annotation <- as.character(interaction_input$annotation)\n }\n object@DB$interaction <- interaction_input\n }\n\n if (is.null(features)) {\n DB <- object@DB\n gene.use_input <- extractGene(DB)\n gene.use <- intersect(gene.use_input, rownames(object@data))\n } else {\n gene.use <- intersect(features, rownames(object@data))\n }\n object@data.signaling <- object@data[rownames(object@data) %in% gene.use, ]\n return(object)\n}\n\n\n\n#' Identify over-expressed signaling genes associated with each cell group\n#'\n#' USERS can use customized gene set as over-expressed signaling genes by setting `object@var.features[[features.name]] <- features.sig`\n#' The Bonferroni corrected/adjusted p value can be obtained via `object@var.features[[paste0(features.name, \".info\")]]`. Note that by default `features.name = \"features\"`\n#'\n#' @param object CellChat object\n#' @param data.use a customed data matrix. Default: data.use = NULL and the expression matrix in the slot 'data.signaling' is used\n#' @param group.by cell group information; default is `object@idents`; otherwise it should be one of the column names of the meta slot\n#' @param idents.use a subset of cell groups used for analysis\n#' @param invert whether to invert the idents.use\n#' @param group.dataset dataset origin information in a merged CellChat object; set it as one of the column names of meta slot when identifying the highly enriched genes in one dataset for each cell group\n#' @param pos.dataset the dataset name used for identifying highly enriched genes in this dataset for each cell group\n#' @param group.DE.combined Whether to perform differential expression between conditions by ignoring cell group information. By default, group.DE.combined = FALSE, which will perform differential expression analysis between two biological conditions for each cell group;\n#' When group.DE.combined = TRUE, it will perform DE analysis by combining all cell groups together.\n#'\n#' @param features.name a char name used for storing the over-expressed signaling genes in `object@var.features[[features.name]]`\n#' @param only.pos Only return positive markers\n#' @param features features used for identifying Over Expressed genes. default use all features\n#' @param return.object whether to return the object; otherwise return a data frame consisting of over-expressed signaling genes associated with each cell group\n#' @param thresh.pc Threshold of the fraction of cells expressed in one cluster, i.e., thresh.pc = 0.1\n#' @param thresh.fc Threshold of Log Fold Change, i.e., thresh.pc = 0.1\n#' @param thresh.p Threshold of p-values, i.e., thresh.pc = 0.05\n#' @param do.DE Whether to perform differential expression analysis. By default do.DE = TRUE; When do.DE = FALSE, selecting over-expressed genes that are expressed in more than `min.cells` cells.\n#' @param do.fast If do.fast = TRUE, then perform a ultra-fast Wilcoxon test using presto package; otherwise using stats package. These two methods produce different logFC values, and the presto::wilcoxauc method gives smaller values.\n#' @param min.cells the minmum number of expressed cells required for the genes that are considered for cell-cell communication analysis\n#' @importFrom future nbrOfWorkers\n#' @importFrom pbapply pbsapply\n#' @importFrom future.apply future_sapply\n#' @importFrom stats sd wilcox.test p.adjust\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, two new elements named 'features.name' and paste0(features.name, \".info\") will be added into the list `object@var.features`\n#' `object@var.features[[features.name]]` is a vector consisting of the identified over-expressed signaling genes;\n#' `object@var.features[[paste0(features.name, \".info\")]]` is a data frame returned from the differential expression analysis\n#' @export\n#'\nidentifyOverExpressedGenes <- function(object, data.use = NULL, group.by = NULL, idents.use = NULL, invert = FALSE,\n group.dataset = NULL, pos.dataset = NULL, group.DE.combined = FALSE,\n features.name = \"features\", only.pos = TRUE, features = NULL, return.object = TRUE,\n thresh.pc = 0, thresh.fc = 0, thresh.p = 0.05, do.DE = TRUE, do.fast = TRUE, min.cells = 10) {\n if (!is.list(object@var.features)) {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n if (is.null(data.use)) {\n X <- object@data.signaling\n if (nrow(X) < 3) {stop(\"Please check `object@data.signaling` and ensure that you have run `subsetData` and that the data matrix `object@data.signaling` looks OK.\")}\n } else {\n X <- data.use\n }\n\n if (is.null(features)) {\n features.use <- row.names(X)\n } else {\n features.use <- intersect(features, row.names(X))\n }\n data.use <- X[features.use,]\n\n if (do.DE) {\n # select genes based on differential expression\n data.use <- as.matrix(data.use)\n\n if (is.null(group.by)) {\n labels <- object@idents\n if (!is.factor(labels)) {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n level.use <- levels(labels)[levels(labels) %in% unique(labels)]\n if (!is.null(idents.use)) {\n if (invert) {\n level.use <- level.use[!(level.use %in% idents.use)]\n } else {\n level.use <- level.use[level.use %in% idents.use]\n }\n }\n numCluster <- length(level.use)\n\n if (!is.null(group.dataset)) {\n labels.dataset <- as.character(object@meta[[group.dataset]])\n if (!(pos.dataset %in% unique(labels.dataset))) {\n cat(\"Please set pos.dataset to be one of the following dataset names: \", unique(as.character(labels.dataset)))\n stop()\n }\n labels.dataset[labels.dataset != pos.dataset] <- toString(setdiff(unique(labels.dataset), pos.dataset))\n labels.dataset <- factor(labels.dataset, levels = c(pos.dataset, setdiff(unique(labels.dataset), pos.dataset)))\n }\n\n if (do.fast) {\n presto.check <- rlang::is_installed(c(\"presto\"))\n if (!presto.check) {\n stop(\n \"For a faster implementation of the Wilcoxon Test, please install the presto package\",\n \"\\n--------------------------------------------\",\n \"\\n devtools::install_github('immunogenomics/presto')\",\n \"\\n--------------------------------------------\",\n \"\\n Otherwise, plase set `do.fast = FALSE` for running the standard Wilcoxon Test!\\n\"\n )\n }\n if (is.null(group.dataset)) {\n genes.de <- presto::wilcoxauc(data.use, labels, groups_use = level.use)\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"clusters\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100) %>% arrange(pvalues)\n\n } else if ((!is.null(group.dataset)) & (group.DE.combined == FALSE)) {\n genes.de <- data.frame()\n for (i in 1:numCluster) {\n idx <- which(labels == level.use[i])\n data.use.i <- data.use[ ,idx]\n labels.i <- labels.dataset[idx]\n genes.de.i <- presto::wilcoxauc(data.use.i, labels.i)\n # genes.de.i <- genes.de.i[1:(nrow(genes.de.i)/2),]\n genes.de.i$clusters <- level.use[i]\n genes.de <- rbind(genes.de, genes.de.i)\n }\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"datasets\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100)\n markers.all$datasets <- factor(markers.all$datasets, levels = levels(labels.dataset))\n markers.all <- markers.all[order(markers.all$datasets, markers.all$pvalues, -markers.all$logFC), ]\n } else if ((!is.null(group.dataset)) & (group.DE.combined == TRUE)) {\n genes.de.c <- presto::wilcoxauc(data.use, labels.dataset)\n genes.de.c <- genes.de.c[1:(nrow(genes.de.c)/2),]\n genes.de <- data.frame()\n for (i in 1:numCluster) {\n genes.de.c$clusters <- level.use[i]\n genes.de <- rbind(genes.de, genes.de.c)\n }\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"datasets\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100) %>% arrange(pvalues)\n\n }\n markers.all <- dplyr::select(markers.all, -c(\"logFC_abs\",\"statistic\",\"pct.max\"))\n\n if (only.pos & nrow(markers.all) > 0) {\n markers.all <- subset(markers.all, subset = logFC > 0)\n }\n markers.all$features <- as.character(markers.all$features)\n\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- unique(features.sig)\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n\n } else {\n\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n\n mean.fxn <- function(x) {\n return(log(x = mean(x = expm1(x = x)) + 1))\n }\n labels <- as.character(labels)\n genes.de <- vector(\"list\", length = numCluster)\n for (i in 1:numCluster) {\n features <- features.use\n if (is.null(group.dataset)) {\n cell.use1 <- which(labels == level.use[i])\n cell.use2 <- base::setdiff(1:length(labels), cell.use1)\n } else if ((!is.null(group.dataset)) & (group.DE.combined == FALSE)) {\n cell.use1 <- which((labels == level.use[i]) & (labels.dataset == pos.dataset))\n cell.use2 <- which((labels == level.use[i]) & (labels.dataset != pos.dataset))\n } else if ((!is.null(group.dataset)) & (group.DE.combined == TRUE)) {\n cell.use1 <- which(labels.dataset == pos.dataset)\n cell.use2 <- which(labels.dataset != pos.dataset)\n }\n\n # feature selection (based on percentages)\n thresh.min <- 0\n pct.1 <- round(\n x = rowSums(data.use[features, cell.use1, drop = FALSE] > thresh.min) /\n length(x = cell.use1),\n digits = 3\n )\n pct.2 <- round(\n x = rowSums(data.use[features, cell.use2, drop = FALSE] > thresh.min) /\n length(x = cell.use2),\n digits = 3\n )\n data.alpha <- cbind(pct.1, pct.2)\n colnames(x = data.alpha) <- c(\"pct.1\", \"pct.2\")\n alpha.min <- apply(X = data.alpha, MARGIN = 1, FUN = max)\n names(x = alpha.min) <- rownames(x = data.alpha)\n features <- names(x = which(x = alpha.min > thresh.pc))\n if (length(x = features) == 0) {\n #stop(\"No features pass thresh.pc threshold\")\n next\n }\n\n # feature selection (based on average difference)\n data.1 <- apply(X = data.use[features, cell.use1, drop = FALSE],MARGIN = 1,FUN = mean.fxn)\n data.2 <- apply(X = data.use[features, cell.use2, drop = FALSE],MARGIN = 1,FUN = mean.fxn)\n FC <- (data.1 - data.2)\n if (only.pos) {\n features.diff <- names(which(FC > thresh.fc))\n } else {\n features.diff <- names(which(abs(FC) > thresh.fc))\n }\n\n features <- intersect(x = features, y = features.diff)\n if (length(x = features) == 0) {\n # stop(\"No features pass thresh.fc threshold\")\n next\n }\n\n data1 <- data.use[features, cell.use1, drop = FALSE]\n data2 <- data.use[features, cell.use2, drop = FALSE]\n\n pvalues <- unlist(\n x = my.sapply(\n X = 1:nrow(x = data1),\n FUN = function(x) {\n # return(wilcox.test(data1[x, ], data2[x, ], alternative = \"greater\")$p.value)\n return(wilcox.test(data1[x, ], data2[x, ])$p.value)\n }\n )\n )\n\n pval.adj = stats::p.adjust(\n p = pvalues,\n method = \"bonferroni\",\n n = nrow(X)\n )\n genes.de[[i]] <- data.frame(clusters = level.use[i], features = as.character(rownames(data1)), pvalues = pvalues, logFC = FC[features], data.alpha[features,, drop = F],pvalues.adj = pval.adj, stringsAsFactors = FALSE)\n }\n\n markers.all <- data.frame()\n for (i in 1:numCluster) {\n gde <- genes.de[[i]]\n if (!is.null(gde)) {\n gde <- gde[order(gde$pvalues, -gde$logFC), ]\n gde <- subset(gde, subset = pvalues < thresh.p)\n if (nrow(gde) > 0) {\n markers.all <- rbind(markers.all, gde)\n }\n }\n }\n if (only.pos & nrow(markers.all) > 0) {\n markers.all <- subset(markers.all, subset = logFC > 0)\n }\n if (!is.null(group.dataset)) {\n markers.all$datasets[markers.all$logFC > 0] <- pos.dataset\n markers.all$datasets[markers.all$logFC < 0] <- setdiff(unique(labels.dataset), pos.dataset)\n markers.all$datasets <- factor(markers.all$datasets, levels = levels(labels.dataset))\n markers.all <- markers.all[order(markers.all$datasets, markers.all$pvalues, -markers.all$logFC), ]\n }\n markers.all$features <- as.character(markers.all$features)\n\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- features.sig\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n }\n\n } else {\n # select genes if they are exprssed in at least `min.cells` cells\n markers.all <- data.frame(features = as.character(rownames(data.use)), nCells = rowSums(data.use > 0))\n markers.all <- dplyr::filter(markers.all, nCells >= min.cells)\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- unique(features.sig)\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n }\n\n\n if (return.object) {\n return(object)\n } else {\n return(markers.all)\n }\n}\n\n\n#' Identify over-expressed ligands and (complex) receptors associated with each cell group\n#'\n#' This function identifies the over-expressed ligands and (complex) receptors based on the identified signaling genes from 'identifyOverExpressedGenes'.\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for storing the over-expressed ligands and receptors in `object@var.features[[paste0(features.name, \".LR\")]]`\n#' @param features a vector of features to use. default use all over-expressed genes in `object@var.features[[features.name]]`\n#' @param return.object whether returning a CellChat object. If FALSE, it will return a data frame containing over-expressed ligands and (complex) receptors associated with each cell group\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom dplyr select\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, a new element named paste0(features.name, \".LR\") will be added into the list `object@var.features`\n#' @export\n#'\nidentifyOverExpressedLigandReceptor <- function(object, features.name = \"features\", features = NULL, return.object = TRUE) {\n\n features.name.LR <- paste0(features.name, \".LR\")\n features.name <- paste0(features.name, \".info\")\n DB <- object@DB\n interaction_input <- DB$interaction\n complex_input <- DB$complex\n pairLR <- select(interaction_input, ligand, receptor)\n LR.use <- unique(c(pairLR$ligand, pairLR$receptor))\n if (is.null(features)) {\n if (is.list(object@var.features)) {\n markers.all <- object@var.features[[features.name]] # use the updated CellChat object 12/2020\n } else {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n\n } else {\n features.use <- features\n rm(features)\n markers.all <- subset(markers.all, subset = features %in% features.use)\n }\n\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n complexSubunits <- complex_input[, grepl(\"subunit\" , colnames(complex_input))]\n\n markers.all.new <- data.frame()\n for (i in 1:nrow(markers.all)) {\n if (markers.all$features[i] %in% LR.use) {\n markers.all.new <- rbind(markers.all.new, markers.all[i, , drop = FALSE])\n } else {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (markers.all$features[i] %in% complexsubunitsV) {\n return(x)\n }\n }\n )\n )\n complexSubunits.sig <- rownames(complexSubunits[index.sig,])\n markers.all.complex <- data.frame()\n for (j in 1:length(complexSubunits.sig)) {\n markers.all.complex <- rbind(markers.all.complex, markers.all[i, , drop = FALSE])\n }\n markers.all.complex$features <- complexSubunits.sig\n markers.all.new <- rbind(markers.all.new, markers.all.complex)\n }\n }\n\n object@var.features[[features.name.LR]] <- markers.all.new\n\n if (return.object) {\n return(object)\n } else {\n return(markers.all.new)\n }\n}\n\n\n\n#' Identify over-expressed ligand-receptor interactions (pairs) within the used CellChatDB\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for assess the results in `object@var.features[[features.name]]`\n#' @param features a vector of features to use. default use all over-expressed genes in `object@var.features[[features.name]]`\n#' @param variable.both variable.both = TRUE will require that both ligand and receptor from one pair are over-expressed;\n#'\n#' variable.both = FALSE will only require that either ligand or receptor from one pair is over-expressed, leading to more over-expressed ligand-receptor interactions (pairs) for further analysis.\n#' @param return.object whether returning a CellChat object. If FALSE, it will return a data frame containing the over-expressed ligand-receptor pairs\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom dplyr select\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, a new element named 'LRsig' will be added into the list `object@LR`\n#' @export\n#'\nidentifyOverExpressedInteractions <- function(object, features.name = \"features\", variable.both = TRUE, features = NULL, return.object = TRUE) {\n gene.use <- row.names(object@data.signaling)\n DB <- object@DB\n if (is.null(features)) {\n if (is.list(object@var.features)) {\n features.sig <- object@var.features[[features.name]] # use the updated CellChat object 12/2020\n } else {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n\n } else {\n features.sig <- features\n }\n\n interaction_input <- DB$interaction\n complex_input <- DB$complex\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n complexSubunits <- complex_input[, grepl(\"subunit\" , colnames(complex_input))]\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (length(intersect(complexsubunitsV, features.sig)) > 0 & all(complexsubunitsV %in% gene.use)) {\n return(x)\n }\n }\n )\n )\n complexSubunits.sig <- complexSubunits[index.sig,]\n\n index.use <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (all(complexsubunitsV %in% gene.use)) {\n return(x)\n }\n }\n )\n )\n complexSubunits.use <- complexSubunits[index.use,]\n\n pairLR <- select(interaction_input, ligand, receptor)\n\n if (variable.both) {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(pairLR),\n FUN = function(x) {\n if (all(unlist(pairLR[x,], use.names = F) %in% c(features.sig, rownames(complexSubunits.sig)))) {\n return(x)\n }\n }\n )\n )\n } else {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(pairLR),\n FUN = function(x) {\n # if (all(unlist(pairLR[x,], use.names = F) %in% c(features.sig, rownames(complexSubunits.sig)))) {\n if (all(unlist(pairLR[x,], use.names = F) %in% c(gene.use, rownames(complexSubunits.use))) & (length(intersect(unlist(pairLR[x,], use.names = F), c(features.sig, rownames(complexSubunits.sig)))) > 0)) {\n return(x)\n }\n }\n )\n )\n }\n\n pairLRsig <- interaction_input[index.sig, ]\n object@LR$LRsig <- pairLRsig\n cat(\"The number of highly variable ligand-receptor pairs used for signaling inference is\", nrow(pairLRsig), '\\n')\n if (return.object) {\n return(object)\n } else {\n return(pairLRsig)\n }\n}\n\n\n#' Smooth the gene expression data\n#'\n#' A diffusion process is used to smooth genes’ expression values based on their neighbors’ defined in a high-confidence experimentally validated protein-protein network.\n#'\n#' This function is useful when analyzing single-cell data with shallow sequencing depth because the projection reduces the dropout effects of signaling genes, in particular for possible zero expression of subunits of ligands/receptors\n#'\n#' @param object CellChat object\n#' @param method When method = \"netSmooth\", smoothing a gene’s expression values based on its neighbors defined in a high-confidence experimentally validated protein-protein network.\n#' @param adj adjacency matrix of protein-protein interaction network to use\n#' @param alpha numeric in [0,1] alpha = 0: no smoothing; a larger value alpha results in increasing levels of smoothing.\n#' @param normalizeAdjMatrix how to normalize the adjacency matrix\n#' possible values are 'rows' (in-degree)\n#' and 'columns' (out-degree)\n#' @return a smoothed gene expression matrix\n#' @export\n#'\n# This function is adapted from https://github.com/BIMSBbioinfo/netSmooth\nsmoothData <- function(object, method = c(\"netSmooth\"), adj = NULL, alpha=0.5, normalizeAdjMatrix=c('rows','columns')){\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n stop(\"`object@data.smooth` is missing. Please update the CellChat object via `updateCellChat`! \\n\")\n }\n data <- as.matrix(object@data.signaling)\n normalizeAdjMatrix <- match.arg(normalizeAdjMatrix)\n if (method == \"netSmooth\") {\n if (is.null(adj)) stop(\"Please provide the `adj`. \\n\")\n stopifnot(is(adj, 'matrix') | is(adj, 'sparseMatrix'))\n stopifnot((is.numeric(alpha) & (alpha > 0 & alpha < 1)))\n if(sum(Matrix::rowSums(adj)==0)>0) stop(\"PPI cannot have zero rows/columns\")\n if(sum(Matrix::colSums(adj)==0)>0) stop(\"PPI cannot have zero rows/columns\")\n }\n if(is.numeric(alpha)) {\n if(alpha<0 | alpha > 1) {\n stop('alpha must be between 0 and 1')\n }\n data.projected <- projectAndRecombine(data, adj, alpha,normalizeAdjMatrix=normalizeAdjMatrix)\n } else stop(\"unsupported alpha value: \", class(alpha))\n object@data.smooth <- data.projected\n return(object)\n}\n\n#' Perform network projecting on network when the network genes and the\n#' experiment genes aren't exactly the same.\n#'\n#' The gene network might be defined only on a subset of genes that are\n#' measured in any experiment. Further, an experiment might not measure all\n#' genes that are present in the network. This function projects the experiment\n#' data onto the gene space defined by the network prior to projecting. Then,\n#' it projects the projected data back into the original dimansions.\n#'\n#' @param gene_expression gene expession data to be projected\n#' [N_genes x M_samples]\n#' @param adj_matrix adjacenty matrix of network to perform projecting over.\n#' Will be column-normalized.\n#' Rownames and colnames should be genes.\n#' @param alpha network projecting parameter (1 - restart probability in random\n#' walk model.\n#' @param projecting.function must be a function that takes in data, adjacency\n#' matrix, and alpha. Will be used to perform the\n#' actual projecting.\n#' @param normalizeAdjMatrix which dimension (rows or columns) should the\n#' adjacency matrix be normalized by. rows\n#' corresponds to in-degree, columns to\n#' out-degree.\n#' @return matrix with network-projected gene expression data. Genes that are\n#' not present in projecting network will retain original values.\n#' @keywords internal\n#'\nprojectAndRecombine <- function(gene_expression, adj_matrix, alpha,\n projecting.function=randomWalkBySolve,\n normalizeAdjMatrix=c('rows','columns')) {\n normalizeAdjMatrix <- match.arg(normalizeAdjMatrix)\n gene_expression_in_A_space <- projectOnNetwork(gene_expression,rownames(adj_matrix))\n gene_expression_in_A_space_project <- projecting.function(gene_expression_in_A_space, adj_matrix, alpha, normalizeAdjMatrix)\n gene_expression_project <- projectFromNetworkRecombine(gene_expression, gene_expression_in_A_space_project)\n return(gene_expression_project)\n}\n\n\n#' Project the gene expression matrix onto a lower space\n#' of the genes defined in the projecting network\n#' @param gene_expression gene expression matrix\n#' @param new_features the genes in the network, on which to project\n#' the gene expression matrix\n#' @param missing.value value to assign to genes that are in network,\n#' but missing from gene expression matrix\n#' @return the gene expression matrix projected onto the gene space defined by new_features\n#' @keywords internal\nprojectOnNetwork <- function(gene_expression, new_features, missing.value=0) {\n # data_in_new_space = matrix(rep(0, length(new_features)*dim(gene_expression)[2]),nrow=length(new_features))\n data_in_new_space = matrix(0, ncol=dim(gene_expression)[2], nrow=length(new_features))\n rownames(data_in_new_space) <- new_features\n colnames(data_in_new_space) <- colnames(gene_expression)\n genes_in_both <- intersect(rownames(data_in_new_space),rownames(gene_expression))\n data_in_new_space[genes_in_both,] <- gene_expression[genes_in_both,]\n genes_only_in_network <- setdiff(new_features, rownames(gene_expression))\n data_in_new_space[genes_only_in_network,] <- missing.value\n return(data_in_new_space)\n}\n\n#' project data on graph by solving the linear equation (I - alpha*A) * E_sm = E * (1-alpha)\n\n#' @param E initial data matrix [NxM]\n#' @param A adjacency matrix of graph to network project on will be column-normalized.\n#' @param alpha projecting coefficient (1 - restart probability of random walk)\n#' @return network-projected gene expression\n#' @keywords internal\nrandomWalkBySolve <- function(E, A, alpha, normalizeAjdMatrix=c('rows','columns')) {\n normalizeAjdMatrix <- match.arg(normalizeAjdMatrix)\n if (normalizeAjdMatrix=='rows') {\n Anorm <- l1NormalizeRows(A)\n } else if (normalizeAjdMatrix=='columns') {\n Anorm <- l1NormalizeColumns(A)\n }\n eye <- diag(dim(A)[1])\n AA <- eye - alpha*Anorm\n BB <- (1-alpha) * E\n return(solve(AA, BB))\n}\n\n#' Column-normalize a sparse, symmetric matrix (using the l1 norm) so that each\n#' column sums to 1.\n#'\n#' @param A matrix\n#' @usage l1NormalizeColumns(A)\n#' @return column-normalized sparse matrix object\n#' @keywords internal\nl1NormalizeColumns <- function(A) {\n return(Matrix::t(Matrix::t(A)/Matrix::colSums(A)))\n}\n\n#' Row-normalize a sparse, symmetric matrix (using the l1 norm) so that each\n#' row sums to 1.\n#'\n#' @param A matrix\n#' @usage l1NormalizeRows(A)\n#' @return row-normalized sparse matrix object\n#' @keywords internal\nl1NormalizeRows <- function(A) {\n return(A/Matrix::rowSums(A))\n}\n\n#' Combine gene expression from projected space (that of the network) with the\n#' expression of genes that were not projected (not present in network)\n#' @keywords internal\n#' @param original_expression the non-projected expression\n#' @param projected_expression the projected gene expression, in the space\n#' of the genes defined by the network\n#' @return a matrix in the dimensions of original_expression, where values that\n#' are present in projected_expression are copied from there.\nprojectFromNetworkRecombine <- function(original_expression, projected_expression) {\n data_in_original_space <- original_expression\n genes_in_both <- intersect(rownames(original_expression),rownames(projected_expression))\n data_in_original_space[genes_in_both,] <- as.matrix(projected_expression[genes_in_both,])\n return(data_in_original_space)\n}\n\n\n#' Dimension reduction using PCA\n#'\n#' @param data.use input data (samples in rows, features in columns)\n#' @param do.fast whether do fast PCA\n#' @param dimPC the number of components to keep\n#' @param seed.use set a seed\n#' @param weight.by.var whether use weighted pc.scores\n#' @importFrom stats prcomp\n#' @importFrom irlba irlba\n#' @return\n#' @export\n#'\n#' @examples\nrunPCA <- function(data.use, do.fast = T, dimPC = 50, seed.use = 42, weight.by.var = T) {\n set.seed(seed = seed.use)\n if (do.fast) {\n dimPC <- min(dimPC, ncol(data.use) - 1)\n pca.res <- irlba::irlba(data.use, nv = dimPC)\n sdev <- pca.res$d/sqrt(max(1, nrow(data.use) - 1))\n if (weight.by.var){\n pc.scores <- pca.res$u %*% diag(pca.res$d)\n } else {\n pc.scores <- pca.res$u\n }\n } else {\n dimPC <- min(dimPC, ncol(data.use) - 1)\n pca.res <- stats::prcomp(x = data.use, rank. = dimPC)\n sdev <- pca.res$sdev\n if (weight.by.var) {\n pc.scores <- pca.res$x %*% diag(pca.res$sdev[1:dimPC]^2)\n } else {\n pc.scores <- pca.res$x\n }\n }\n rownames(pc.scores) <- rownames(data.use)\n colnames(pc.scores) <- paste0('PC', 1:ncol(pc.scores))\n return(pc.scores)\n}\n\n\n#' Run UMAP\n#' @param data.use input data matrix\n#' @param n_neighbors This determines the number of neighboring points used in\n#' local approximations of manifold structure. Larger values will result in more\n#' global structure being preserved at the loss of detailed local structure. In general this parameter should often be in the range 5 to 50.\n#' @param n_components The dimension of the space to embed into.\n#' @param metric This determines the choice of metric used to measure distance in the input space.\n#' @param n_epochs the number of training epochs to be used in optimizing the low dimensional embedding. Larger values result in more accurate embeddings. If NULL is specified, a value will be selected based on the size of the input dataset (200 for large datasets, 500 for small).\n#' @param learning_rate The initial learning rate for the embedding optimization.\n#' @param min_dist This controls how tightly the embedding is allowed compress points together.\n#' Larger values ensure embedded points are moreevenly distributed, while smaller values allow the\n#' algorithm to optimise more accurately with regard to local structure. Sensible values are in the range 0.001 to 0.5.\n#' @param spread he effective scale of embedded points. In combination with min.dist this determines how clustered/clumped the embedded points are.\n#' @param set_op_mix_ratio Interpolate between (fuzzy) union and intersection as the set operation used to combine local fuzzy simplicial sets to obtain a global fuzzy simplicial sets.\n#' @param local_connectivity The local connectivity required - i.e. the number of nearest neighbors\n#' that should be assumed to be connected at a local level. The higher this value the more connected\n#' the manifold becomes locally. In practice this should be not more than the local intrinsic dimension of the manifold.\n#' @param repulsion_strength Weighting applied to negative samples in low dimensional embedding\n#' optimization. Values higher than one will result in greater weight being given to negative samples.\n#' @param negative_sample_rate The number of negative samples to select per positive sample in the\n#' optimization process. Increasing this value will result in greater repulsive force being applied, greater optimization cost, but slightly more accuracy.\n#' @param a More specific parameters controlling the embedding. If NULL, these values are set automatically as determined by min. dist and spread.\n#' @param b More specific parameters controlling the embedding. If NULL, these values are set automatically as determined by min. dist and spread.\n#' @param seed.use Set a random seed. By default, sets the seed to 42.\n#' @param metric_kwds,angular_rp_forest,verbose other parameters used in UMAP\n#' @import reticulate\n#' @export\n#'\nrunUMAP <- function(\n data.use,\n n_neighbors = 30L,\n n_components = 2L,\n metric = \"correlation\",\n n_epochs = NULL,\n learning_rate = 1.0,\n min_dist = 0.3,\n spread = 1.0,\n set_op_mix_ratio = 1.0,\n local_connectivity = 1L,\n repulsion_strength = 1,\n negative_sample_rate = 5,\n a = NULL,\n b = NULL,\n seed.use = 42L,\n metric_kwds = NULL,\n angular_rp_forest = FALSE,\n verbose = FALSE){\n if (!reticulate::py_module_available(module = 'umap')) {\n stop(\"Cannot find UMAP, please install through pip (e.g. pip install umap-learn or reticulate::py_install(packages = 'umap-learn')).\")\n }\n set.seed(seed.use)\n reticulate::py_set_seed(seed.use)\n umap_import <- reticulate::import(module = \"umap\", delay_load = TRUE)\n umap <- umap_import$UMAP(\n n_neighbors = as.integer(n_neighbors),\n n_components = as.integer(n_components),\n metric = metric,\n n_epochs = n_epochs,\n learning_rate = learning_rate,\n min_dist = min_dist,\n spread = spread,\n set_op_mix_ratio = set_op_mix_ratio,\n local_connectivity = local_connectivity,\n repulsion_strength = repulsion_strength,\n negative_sample_rate = negative_sample_rate,\n a = a,\n b = b,\n metric_kwds = metric_kwds,\n angular_rp_forest = angular_rp_forest,\n verbose = verbose\n )\n Rumap <- umap$fit_transform\n umap_output <- Rumap(t(data.use))\n colnames(umap_output) <- paste0('UMAP', 1:ncol(umap_output))\n rownames(umap_output) <- colnames(data.use)\n return(umap_output)\n}\n\n.error_if_no_Seurat <- function() {\n if (!requireNamespace(\"Seurat\", quietly = TRUE)) {\n stop(\"Seurat installation required for working with Seurat objects\")\n }\n}\n\n\n#' Color interpolation\n#'\n#' This function is modified from https://rdrr.io/cran/circlize/src/R/utils.R\n#' Colors are linearly interpolated according to break values and corresponding colors through CIE Lab color space (`colorspace::LAB`) by default.\n#' Values exceeding breaks will be assigned with corresponding maximum or minimum colors.\n#'\n#' @param breaks A vector indicating numeric breaks\n#' @param colors A vector of colors which correspond to values in ``breaks``\n#' @param transparency A single value in ``[0, 1]``. 0 refers to no transparency and 1 refers to full transparency\n#' @param space color space in which colors are interpolated. Value should be one of \"RGB\", \"HSV\", \"HLS\", \"LAB\", \"XYZ\", \"sRGB\", \"LUV\", see `colorspace::color-class` for detail.\n#' @importFrom colorspace coords RGB HSV HLS LAB XYZ sRGB LUV hex\n#' @importFrom grDevices col2rgb\n#' @return It returns a function which accepts a vector of numeric values and returns interpolated colors.\n#' @export\n#' @examples\n#' \\dontrun{\n#' col_fun = colorRamp3(c(-1, 0, 1), c(\"green\", \"white\", \"red\"))\n#' col_fun(c(-2, -1, -0.5, 0, 0.5, 1, 2))\n#' }\ncolorRamp3 = function(breaks, colors, transparency = 0, space = \"LAB\") {\n\n if(length(breaks) != length(colors)) {\n stop(\"Length of `breaks` should be equal to `colors`.\\n\")\n }\n\n colors = colors[order(breaks)]\n breaks = sort(breaks)\n\n l = duplicated(breaks)\n breaks = breaks[!l]\n colors = colors[!l]\n\n if(length(breaks) == 1) {\n stop(\"You should have at least two distinct break values.\")\n }\n\n\n if(! space %in% c(\"RGB\", \"HSV\", \"HLS\", \"LAB\", \"XYZ\", \"sRGB\", \"LUV\")) {\n stop(\"`space` should be in 'RGB', 'HSV', 'HLS', 'LAB', 'XYZ', 'sRGB', 'LUV'\")\n }\n\n colors = t(grDevices::col2rgb(colors)/255)\n\n attr = list(breaks = breaks, colors = colors, transparency = transparency, space = space)\n\n if(space == \"LUV\") {\n i = which(apply(colors, 1, function(x) all(x == 0)))\n colors[i, ] = 1e-5\n }\n\n transparency = 1-ifelse(transparency > 1, 1, ifelse(transparency < 0, 0, transparency))[1]\n transparency_str = sprintf(\"%X\", round(transparency*255))\n if(nchar(transparency_str) == 1) transparency_str = paste0(\"0\", transparency_str)\n\n fun = function(x = NULL, return_rgb = FALSE, max_value = 1) {\n if(is.null(x)) {\n stop(\"Please specify `x`\\n\")\n }\n\n att = attributes(x)\n if(is.data.frame(x)) x = as.matrix(x)\n\n l_na = is.na(x)\n if(all(l_na)) {\n return(rep(NA, length(l_na)))\n }\n\n x2 = x[!l_na]\n\n x2 = ifelse(x2 < breaks[1], breaks[1],\n ifelse(x2 > breaks[length(breaks)], breaks[length(breaks)],\n x2\n ))\n ibin = .bincode(x2, breaks, right = TRUE, include.lowest = TRUE)\n res_col = character(length(x2))\n for(i in unique(ibin)) {\n l = ibin == i\n res_col[l] = .get_color(x2[l], breaks[i], breaks[i+1], colors[i, ], colors[i+1, ], space = space)\n }\n res_col = paste(res_col, transparency_str[1], sep = \"\")\n\n if(return_rgb) {\n res_col = t(grDevices::col2rgb(as.vector(res_col), alpha = TRUE)/255)\n return(res_col)\n } else {\n res_col2 = character(length(x))\n res_col2[l_na] = NA\n res_col2[!l_na] = res_col\n\n attributes(res_col2) = att\n return(res_col2)\n }\n }\n\n attributes(fun) = attr\n return(fun)\n}\n\n.restrict_in = function(x, lower, upper) {\n x[x > upper] = upper\n x[x < lower] = lower\n x\n}\n\n# x: vector\n# break1 single value\n# break2 single value\n# rgb1 vector with 3 elements\n# rgb2 vector with 3 elements\n.get_color = function(x, break1, break2, col1, col2, space) {\n\n col1 = colorspace::coords(as(colorspace::sRGB(col1[1], col1[2], col1[3]), space))\n col2 = colorspace::coords(as(colorspace::sRGB(col2[1], col2[2], col2[3]), space))\n\n res_col = matrix(ncol = 3, nrow = length(x))\n for(j in 1:3) {\n xx = (x - break2)*(col2[j] - col1[j]) / (break2 - break1) + col2[j]\n res_col[, j] = xx\n }\n\n res_col = get(space)(res_col)\n res_col = colorspace::coords(as(res_col, \"sRGB\"))\n res_col[, 1] = .restrict_in(res_col[,1], 0, 1)\n res_col[, 2] = .restrict_in(res_col[,2], 0, 1)\n res_col[, 3] = .restrict_in(res_col[,3], 0, 1)\n colorspace::hex(colorspace::sRGB(res_col))\n}\n\n#' Update the cell-cell communication array from a customized cell-cell-communication scores between different cell groups\n#'\n#' Users may also check the `updateCellChatDB` function for integrating other resources or utilizing a custom database\n#'\n#' @param object CellChat object\n#' @param net a data frame with at least five columns named as `source`,`target`,`ligand`,`receptor` and `score`, which defines the customized cell-cell-communication scores between different cell groups.\n#' a p-value column named `pval`, and additional columns named `interaction_name` and `interaction_name_2` can be also provided.\n#' @return a CellChat object with updated slot `net` and slot `DB` if db is not NULL.\n#' @export\n\nupdateCCC_score <- function(object, net) {\n df.net <- net\n if (all(c(\"source\",\"target\",\"ligand\",\"receptor\",\"score\") %in% colnames(df.net)) == FALSE) {\n stop(\"The input `net` must contain at least five columns named as source,target,ligand,receptor,score\")\n }\n if (all(c(\"interaction_name\") %in% colnames(df.net)) == FALSE) {\n df.net$interaction_name <- paste0(toupper(df.net$ligand), \"_\", toupper(df.net$receptor))\n }\n if (all(c(\"interaction_name_2\") %in% colnames(df.net)) == FALSE) {\n df.net$interaction_name_2 <- paste0(df.net$ligand, \" - \", df.net$receptor)\n }\n if (all(c(\"pval\") %in% colnames(df.net)) == FALSE) {\n df.net$pval <- rep(0, nrow(df.net))\n }\n df.net$prob <- df.net$score\n\n LR <- unique(df.net$interaction_name)\n cell.levels <- levels(object@idents)\n numCluster <- length(cell.levels)\n mat.prob.all <- array(0, dim = c(numCluster,numCluster,length(LR)))\n mat.pval.all <- mat.prob.all\n for (i in 1:length(LR)) {\n df.i <- df.net[df.net$interaction_name == LR[i], , drop = FALSE]\n mat.prob <- matrix(0, nrow = numCluster, ncol = numCluster)\n mat.pval <- mat.prob\n for (j in 1:nrow(df.i)) {\n idx.s <- which(df.i$source[j] == cell.levels)\n idx.t <- which(df.i$target[j] == cell.levels)\n mat.prob[idx.s, idx.t] <- df.i$prob[j]\n mat.pval[idx.s, idx.t] <- df.i$pval[j]\n }\n mat.prob.all[,,i] <- mat.prob\n mat.pval.all[,,i] <- mat.pval\n }\n\n dimnames(mat.prob.all) <- list(cell.levels, cell.levels, LR)\n dimnames(mat.pval.all) <- dimnames(mat.prob.all)\n net <- list(\"prob\" = mat.prob.all, \"pval\" = mat.pval.all)\n object@net <- net\n\n return(object)\n}\n\n#' Preprocessing multi-omics data and preparing the L-R database\n#'\n#' @param data.list a list consisting of multi-omics data (e.g., RNA & ADT)\n#' @param db one of the CellChatDB databases: CellChatDB.human, CellChatDB.mouse, CellChatDB.zebrafish\n#' @param do.sparse whether to use sparse format\n#' @export\n#'\npreProcMultiomics <- function(data.list, db, do.sparse = TRUE) {\n # normalize the data\n data.input.rna <- data.list[[1]]\n data.input.adt <- data.list[[2]]\n data.input.rna = data.input.rna/max(data.input.rna)\n data.input.adt = data.input.adt/max(data.input.adt)\n data.input.adt.temp = data.input.adt\n X = data.input.adt\n for (i in 1:nrow(X)) {\n data.input.adt.temp[i,] = (X[i,]-min(X[i,]))/(max(X[i,])-min(X[i,]))\n }\n data.input.adt[data.input.adt.temp < 0.5] <- 0\n if (do.sparse) {\n data.input = rbind(data.input.rna, as(data.input.adt, \"dgCMatrix\"))\n } else {\n data.input = rbind(as.matrix(data.input.rna), as.matrix(data.input.adt))\n }\n\n # create a new L-R database\n proteins <- rownames(data.input.adt)\n geneInfo.subset <- db$geneInfo[db$geneInfo$AntibodyName %in% proteins, ]\n proteins.nonmapping <- setdiff(proteins, geneInfo.subset$AntibodyName)\n if (length(proteins.nonmapping) > 0) {\n warning(cat(\"The following antibodies are not found in `CellChatDB$geneInfo$AntibodyName`: \", toString(proteins.nonmapping), \"! Please manually add them via the function `updateCellChatDB`. \\n\"))\n }\n out <- extractLRfromGenes(geneSet = geneInfo.subset$Symbol, db)\n LR.use <- out$LR.use\n idx <- match(LR.use$ligand, geneInfo.subset$Symbol)\n LR.use$ligand[!is.na(idx)] <- geneInfo.subset$AntibodyName[idx[!is.na(idx)]]\n idx <- match(LR.use$receptor, geneInfo.subset$Symbol)\n LR.use$receptor[!is.na(idx)] <- geneInfo.subset$AntibodyName[idx[!is.na(idx)]]\n\n db.use <- db\n db.use$interaction <- LR.use\n db.use$geneInfo <- dplyr::add_row(db.use$geneInfo, Symbol = geneInfo.subset$AntibodyName)\n\n return(list(data.input = data.input, db.use = db.use))\n}\n\n\n \n"], ["/CellChat/R/analysis.R", "\n#' Compute and visualize the contribution of each ligand-receptor pair in the overall signaling pathways\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param width the width of individual bar\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param return.data whether return the data.frame consisting of the predicted L-R pairs and their contribution\n#' @param x.rotation rotation of x-label\n#' @param title the title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom dplyr select\n#' @importFrom ggplot2 ggplot geom_bar aes coord_flip scale_x_discrete element_text theme ggtitle\n#' @importFrom cowplot ggdraw draw_label plot_grid\n#'\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_contribution <- function(object, signaling, signaling.name = NULL, sources.use = NULL, targets.use = NULL,\n width = 0.1, vertex.receiver = NULL, thresh = 0.05, return.data = FALSE,\n x.rotation = 0, title = \"Contribution of each L-R pair\",\n font.size = 10, font.size.title = 10) {\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pair.name.use = select(object@DB$interaction[rownames(pairLR),],\"interaction_name_2\")\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n\n prob <- prob[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n dimnames(prob)[3] <- pairLR.name.use\n }\n prob <-(prob-min(prob))/(max(prob)-min(prob))\n\n if (is.null(vertex.receiver)) {\n pSum <- apply(prob, 3, sum)\n pSum.max <- sum(prob)\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n y.lim <- max(pSum)\n\n pair.name <- unlist(dimnames(prob)[3])\n pair.name <- factor(pair.name, levels = unique(pair.name))\n if (!is.null(pairLR.name.use)) {\n pair.name <- pair.name.use[as.character(pair.name),1]\n pair.name <- factor(pair.name, levels = unique(pair.name))\n }\n mat <- pSum\n df1 <- data.frame(name = pair.name, contribution = mat)\n if(nrow(df1) < 10) {\n df2 <- data.frame(name = as.character(1:(10-nrow(df1))), contribution = rep(0, 10-nrow(df1)))\n df <- rbind(df1, df2)\n } else {\n df <- df1\n }\n df <- df[order(df$contribution, decreasing = TRUE), ]\n # df$name <- factor(df$name, levels = unique(df$name))\n df$name <- factor(df$name,levels=df$name[order(df$contribution, decreasing = TRUE)])\n df1$name <- factor(df1$name,levels=df1$name[order(df1$contribution, decreasing = TRUE)])\n gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\", width = 0.7) +\n theme_classic() + theme(axis.text.y = element_text(angle = x.rotation, hjust = 1,size=font.size, colour = 'black'), axis.text=element_text(size=font.size),\n axis.title.y = element_text(size= font.size), axis.text.x = element_blank(), axis.ticks = element_blank()) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim) + coord_flip() + theme(legend.position=\"none\") +\n scale_x_discrete(limits = rev(levels(df$name)), labels = c(rep(\"\", max(0, 10-nlevels(df1$name))),rev(levels(df1$name))))\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5, size = font.size.title))\n }\n gg\n\n } else {\n pair.name <- factor(unlist(dimnames(prob)[3]), levels = unique(unlist(dimnames(prob)[3])))\n # show all the communications\n pSum <- apply(prob, 3, sum)\n pSum.max <- sum(prob)\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n y.lim <- max(pSum)\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\",width = 0.2) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8),\n axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"All\")+ theme(plot.title = element_text(hjust = 0.5))#+\n\n # show the communications in Hierarchy1\n if (dim(prob)[3] > 1) {\n pSum <- apply(prob[,vertex.receiver,], 3, sum)\n } else {\n pSum <- sum(prob[,vertex.receiver,])\n }\n\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg1 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\",width = 0.2) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"Hierarchy1\") + theme(plot.title = element_text(hjust = 0.5))#+\n #scale_x_discrete(limits = c(0,1))\n\n # show the communications in Hierarchy2\n\n if (dim(prob)[3] > 1) {\n pSum <- apply(prob[,setdiff(1:dim(prob)[1],vertex.receiver),], 3, sum)\n } else {\n pSum <- sum(prob[,setdiff(1:dim(prob)[1],vertex.receiver),])\n }\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg2 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\", width=0.9) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"Hierarchy2\")+ theme(plot.title = element_text(hjust = 0.5))#+\n #scale_x_discrete(limits = c(0,1))\n title <- cowplot::ggdraw() + cowplot::draw_label(paste0(\"Contribution of each signaling in \", signaling.name, \" pathway\"), fontface='bold', size = 10)\n gg.combined <- cowplot::plot_grid(gg, gg1, gg2, nrow = 1)\n gg.combined <- cowplot::plot_grid(title, gg.combined, ncol = 1, rel_heights=c(0.1, 1))\n gg <- gg.combined\n gg\n }\n if (return.data) {\n df <- subset(df, contribution > 0)\n return(list(LR.contribution = df, gg.obj = gg))\n } else {\n return(gg)\n }\n}\n\n\n#' Compute the network centrality scores allowing identification of dominant senders, receivers, mediators and influencers in all inferred communication networks\n#'\n#' NB: This function was previously named as `netAnalysis_signalingRole`. The previous function `netVisual_signalingRole` is now named as `netAnalysis_signalingRole_network`.\n#'\n#' @param object CellChat object; If object = NULL, USER must provide `net`\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks. Setting slot.name = \"netP\" to compute the network centrality scores at the level of signaling pathways, and setting slot.name = \"net\" to compute the network centrality scores at the level of ligand-receptor pairs\n#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net\n#' @param net.name a character vector giving the name of signaling networks\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom future nbrOfWorkers\n#' @importFrom methods slot\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#'\n#' @return\n#' @export\n#'\nnetAnalysis_computeCentrality <- function(object = NULL, slot.name = \"netP\", net = NULL, net.name = NULL, thresh = 0.05) {\n if (is.null(net)) {\n prob <- methods::slot(object, slot.name)$prob\n pval <- methods::slot(object, slot.name)$pval\n pval[prob == 0] <- 1\n prob[pval >= thresh] <- 0\n net = prob\n }\n if (is.null(net.name)) {\n net.name <- dimnames(net)[[3]]\n }\n if (length(dim(net)) == 3) {\n nrun <- dim(net)[3]\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n centr.all = my.sapply(\n X = 1:nrun,\n FUN = function(x) {\n net0 <- net[ , , x]\n return(computeCentralityLocal(net0))\n },\n simplify = FALSE\n )\n } else {\n centr.all <- as.list(computeCentralityLocal(net))\n }\n names(centr.all) <- net.name\n if (is.null(object)) {\n return(centr.all)\n } else {\n slot(object, slot.name)$centr <- centr.all\n return(object)\n }\n}\n\n\n\n#' Compute Centrality measures for a signaling network\n#'\n#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net\n#' @importFrom igraph graph_from_adjacency_matrix strength hub_score authority_score eigen_centrality page_rank betweenness E\n#' @importFrom sna flowbet infocent\n#'\n#' @return\ncomputeCentralityLocal <- function(net) {\n centr <- vector(\"list\")\n G <- igraph::graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n centr$outdeg_unweighted <- rowSums(net > 0)\n centr$indeg_unweighted <- colSums(net > 0)\n centr$outdeg <- igraph::strength(G, mode=\"out\")\n centr$indeg <- igraph::strength(G, mode=\"in\")\n centr$hub <- igraph::hub_score(G)$vector\n centr$authority <- igraph::authority_score(G)$vector # A node has high authority when it is linked by many other nodes that are linking many other nodes.\n centr$eigen <- igraph::eigen_centrality(G)$vector # A measure of influence in the network that takes into account second-order connections\n centr$page_rank <- igraph::page_rank(G)$vector\n igraph::E(G)$weight <- 1/igraph::E(G)$weight\n centr$betweenness <- igraph::betweenness(G)\n #centr$flowbet <- try(sna::flowbet(net)) # a measure of its role as a gatekeeper for the flow of communication between any two cells; the total maximum flow (aggregated across all pairs of third parties) mediated by v.\n #centr$info <- try(sna::infocent(net)) # actors with higher information centrality are predicted to have greater control over the flow of information within a network; highly information-central individuals tend to have a large number of short paths to many others within the social structure.\n centr$flowbet <- tryCatch({\n sna::flowbet(net)\n }, error = function(e) {\n as.vector(matrix(0, nrow = nrow(net), ncol = 1))\n })\n centr$info <- tryCatch({\n sna::infocent(net, diag = T, rescale = T, cmode = \"lower\")\n # sna::infocent(net, diag = T, rescale = T, cmode = \"weak\")\n }, error = function(e) {\n as.vector(matrix(0, nrow = nrow(net), ncol = 1))\n })\n return(centr)\n}\n\n\n#' Select the number of the patterns for running `identifyCommunicationPatterns`\n#'\n#' We infer the number of patterns based on two metrics that have been implemented in the NMF R package, including Cophenetic and Silhouette. Both metrics measure the stability for a particular number of patterns based on a hierarchical clustering of the consensus matrix. For a range of the number of patterns, a suitable number of patterns is the one at which Cophenetic and Silhouette values begin to drop suddenly.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param k.range a range of the number of patterns\n#' @param title.name title of plot\n#' @param do.facet whether use facet plot showing the two measures\n#' @param nrun number of runs when performing NMF\n#' @param seed.use seed when performing NMF\n#' @importFrom methods slot\n# #' @importFrom NMF nmfEstimateRank\n#' @import NMF\n# #' @importFrom ggplot2 scale_color_brewer\n#' @import ggplot2\n#' @return a ggplot object\n#' @export\n#'\n#' @examples\nselectK <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), title.name = NULL, do.facet = TRUE, k.range = seq(2,10), nrun = 30, seed.use = 10) {\n pattern <- match.arg(pattern)\n prob <- methods::slot(object, slot.name)$prob\n if (pattern == \"outgoing\") {\n data_sender <- apply(prob, c(1,3), sum)\n data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_sender)\n } else if (pattern == \"incoming\") {\n data_receiver <- apply(prob, c(2,3), sum)\n data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_receiver)\n }\n options(warn = -1)\n data <- data0\n data <- data[rowSums(data)!=0,]\n\n if (is.null(title.name)) {\n title.name <- paste0(pattern, \" signaling \\n\")\n # title.name <- paste0(pattern, \" signaling \\n (nrun = \", nrun, \", seed = \", seed.use, \")\")\n }\n\n res <- NMF::nmfEstimateRank(data, range = k.range, method = 'lee', nrun=nrun, seed = seed.use)\n df1 <- data.frame(k = res$measures$rank, score = res$measures$cophenetic, Measure = \"Cophenetic\")\n df2 <- data.frame(k = res$measures$rank, score = res$measures$silhouette.consensus, Measure = \"Silhouette\")\n # df3 <- data.frame(k = res$measures$rank, score = res$measures$dispersion, Measure = \"Dispersion\")\n df <- rbind(df1, df2)\n #df <- rbind(df1, df2, df3)\n gg <- ggplot(df, aes(x = k, y = score, group = Measure, color = Measure)) + geom_line(size=1) +\n geom_point() +\n theme_classic() + labs(x = 'Number of patterns', y='Measure score') +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(legend.position = \"right\") + theme(text = element_text(size = 10)) + scale_x_discrete(limits = (unique(df$k))) +\n scale_color_brewer(palette=\"Set2\") + guides(color=guide_legend(\"Measure type\"))\n if (do.facet) {\n gg <- gg + facet_wrap(~ Measure, scales='free')\n }\n gg\n return(gg)\n}\n\n\n\n#' Identification of major signals for specific cell groups and general communication patterns\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param k the number of patterns\n#' @param k.range a range of the number of patterns\n#' @param heatmap.show whether showing heatmap\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param title.legend the title of legend in heatmap\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @importFrom methods slot\n#' @importFrom NMF nmfEstimateRank nmf\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation draw\n#' @importFrom stats setNames\n#' @importFrom grid grid.grabExpr grid.newpage pushViewport grid.draw unit gpar viewport popViewport\n#'\n#' @return\n#' @export\n#'\n#' @examples\n\nidentifyCommunicationPatterns <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), k = NULL, k.range = seq(2,10), heatmap.show = TRUE,\n color.use = NULL, color.heatmap = \"Spectral\", title.legend = \"Contributions\",\n width = 4, height = 6, font.size = 8) {\n pattern <- match.arg(pattern)\n prob <- methods::slot(object, slot.name)$prob\n if (pattern == \"outgoing\") {\n data_sender <- apply(prob, c(1,3), sum)\n data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_sender)\n } else if (pattern == \"incoming\") {\n data_receiver <- apply(prob, c(2,3), sum)\n data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_receiver)\n }\n options(warn = -1)\n data <- data0\n data <- data[rowSums(data)!=0,]\n if (is.null(k)) {\n stop(\"Please run the function `selectK` for selecting a suitable k!\")\n }\n\n outs_NMF <- NMF::nmf(data, rank = k, method = 'lee', seed = 'nndsvd')\n W <- scaleMat(outs_NMF@fit@W, 'r1')\n H <- scaleMat(outs_NMF@fit@H, 'c1')\n colnames(W) <- paste0(\"Pattern \", seq(1,ncol(W))); rownames(H) <- paste0(\"Pattern \", seq(1,nrow(H)));\n if (heatmap.show) {\n net <- W\n if (is.null(color.use)) {\n color.use <- scPalette(length(rownames(net)))\n }\n color.heatmap = grDevices::colorRampPalette(rev(RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(255)\n\n df<- data.frame(group = rownames(net)); rownames(df) <- rownames(net)\n cell.cols.assigned <- setNames(color.use, unique(as.character(df$group)))\n row_annotation <- HeatmapAnnotation(df = df, col = list(group = cell.cols.assigned),which = \"row\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ht1 = Heatmap(net, col = color.heatmap, na_col = \"white\", name = \"Contribution\",\n left_annotation = row_annotation,\n cluster_rows = T,cluster_columns = F,clustering_method_rows = \"average\",\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n show_heatmap_legend = F,\n column_title = \"Cell patterns\",column_title_gp = gpar(fontsize = 10)\n )\n\n\n net <- t(H)\n\n ht2 = Heatmap(net, col = color.heatmap, na_col = \"white\", name = \"Contribution\",\n cluster_rows = T,cluster_columns = F,clustering_method_rows = \"average\",\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = \"Communication patterns\",column_title_gp = gpar(fontsize = 10),\n heatmap_legend_param = list(title = title.legend, title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = c(round(min(net, na.rm = T), digits = 1), round(max(net, na.rm = T), digits = 1)),\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 6),grid_width = unit(2, \"mm\"))\n )\n\n gb_ht1 = grid.grabExpr(draw(ht1))\n gb_ht2 = grid.grabExpr(draw(ht2))\n #grid.newpage()\n pushViewport(viewport(x = 0.1, y = 0.1, width = 0.2, height = 0.5, just = c(\"left\", \"bottom\")))\n grid.draw(gb_ht1)\n popViewport()\n\n pushViewport(viewport(x = 0.6, y = 0.1, width = 0.2, height = 0.5, just = c(\"left\", \"bottom\")))\n grid.draw(gb_ht2)\n popViewport()\n\n }\n\n data_W <- as.data.frame(as.table(W)); colnames(data_W) <- c(\"CellGroup\",\"Pattern\",\"Contribution\")\n data_H <- as.data.frame(as.table(H)); colnames(data_H) <- c(\"Pattern\",\"Signaling\",\"Contribution\")\n\n res.pattern = list(\"cell\" = data_W, \"signaling\" = data_H)\n methods::slot(object, slot.name)$pattern[[pattern]] <- list(data = data0, pattern = res.pattern)\n return(object)\n}\n\n\n#' Compute signaling network similarity for any pair of signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param k the number of nearest neighbors\n#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity\n#' @importFrom methods slot\n\n#'\n#' @return\n#' @export\n#'\n#' @examples\ncomputeNetSimilarity <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), k = NULL, thresh = NULL) {\n type <- match.arg(type)\n prob = methods::slot(object, slot.name)$prob\n if (is.null(k)) {\n if (dim(prob)[3] <= 25) {\n k <- ceiling(sqrt(dim(prob)[3]))\n } else {\n k <- ceiling(sqrt(dim(prob)[3])) + 1\n }\n\n }\n if (!is.null(thresh)) {\n prob[prob < quantile(c(prob[prob != 0]), thresh)] <- 0\n }\n if (type == \"functional\") {\n # compute the functional similarity\n D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])\n S2 <- D_signalings; S3 <- D_signalings;\n for (i in 1:(dim(prob)[3]-1)) {\n for (j in (i+1):dim(prob)[3]) {\n Gi <- (prob[ , ,i] > 0)*1\n Gj <- (prob[ , ,j] > 0)*1\n S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)\n }\n }\n # define the similarity matrix\n S3[is.na(S3)] <- 0; S3 <- S3 + t(S3); diag(S3) <- 1\n # S_signalings <- S1 *S2\n S_signalings <- S3\n } else if (type == \"structural\") {\n # compute the structure distance\n D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])\n for (i in 1:(dim(prob)[3]-1)) {\n for (j in (i+1):dim(prob)[3]) {\n Gi <- (prob[ , ,i] > 0)*1\n Gj <- (prob[ , ,j] > 0)*1\n D_signalings[i,j] <- computeNetD_structure(Gi,Gj)\n }\n }\n # define the structure similarity matrix\n D_signalings[is.infinite(D_signalings)] <- 0\n D_signalings[is.na(D_signalings)] <- 0\n D_signalings <- D_signalings + t(D_signalings)\n S_signalings <- 1-D_signalings\n }\n\n # smooth the similarity matrix using SNN\n SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)\n Similarity <- as.matrix(S_signalings*SNN)\n rownames(Similarity) <- dimnames(prob)[[3]]\n colnames(Similarity) <- dimnames(prob)[[3]]\n\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {\n methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity\n return(object)\n}\n\n\n\n#' Compute signaling network similarity for any pair of datasets\n#'\n#' @param object A merged CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison\n#' @param k the number of nearest neighbors\n#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity\n#' @importFrom methods slot\n#'\n#' @return\n#' @export\n#'\ncomputeNetSimilarityPairwise <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, k = NULL, thresh = NULL) {\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Compute signaling network similarity for datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n net <- list()\n signalingAll <- c()\n object.net.nameAll <- c()\n # 1:length(setdiff(names(methods::slot(object, slot.name)), \"similarity\"))\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n object.net.name <- names(methods::slot(object, slot.name))[comparison[i]]\n object.net.nameAll <- c(object.net.nameAll, object.net.name)\n net[[i]] = object.net$prob\n signalingAll <- c(signalingAll, paste0(dimnames(net[[i]])[[3]], \"--\", object.net.name))\n # signalingAll <- c(signalingAll, dimnames(net[[i]])[[3]])\n }\n names(net) <- object.net.nameAll\n net.dim <- sapply(net, dim)[3,]\n nnet <- sum(net.dim)\n position <- cumsum(net.dim); position <- c(0,position)\n\n if (is.null(k)) {\n if (nnet <= 25) {\n k <- ceiling(sqrt(nnet))\n } else {\n k <- ceiling(sqrt(nnet)) + 1\n }\n\n }\n if (!is.null(thresh)) {\n for (i in 1:length(net)) {\n neti <- net[[i]]\n neti[neti < quantile(c(neti[neti != 0]), thresh)] <- 0\n net[[i]] <- neti\n }\n }\n if (type == \"functional\") {\n # compute the functional similarity\n S3 <- matrix(0, nrow = nnet, ncol = nnet)\n for (i in 1:nnet) {\n for (j in 1:nnet) {\n idx.i <- which(position - i >= 0)[1]\n idx.j <- which(position - j >= 0)[1]\n net.i <- net[[idx.i-1]]\n net.j <- net[[idx.j-1]]\n Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1\n Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1\n S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)\n }\n }\n\n # define the similarity matrix\n S3[is.na(S3)] <- 0; diag(S3) <- 1\n S_signalings <- S3\n } else if (type == \"structural\") {\n # compute the structure distance\n D_signalings <- matrix(0, nrow = nnet, ncol = nnet)\n for (i in 1:nnet) {\n for (j in 1:nnet) {\n idx.i <- which(position - i >= 0)[1]\n idx.j <- which(position - j >= 0)[1]\n net.i <- net[[idx.i-1]]\n net.j <- net[[idx.j-1]]\n Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1\n Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1\n D_signalings[i,j] <- computeNetD_structure(Gi,Gj)\n }\n }\n # define the structure similarity matrix\n D_signalings[is.infinite(D_signalings)] <- 0\n D_signalings[is.na(D_signalings)] <- 0\n S_signalings <- 1-D_signalings\n }\n # smooth the similarity matrix using SNN\n SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)\n Similarity <- as.matrix(S_signalings*SNN)\n rownames(Similarity) <- signalingAll\n colnames(Similarity) <- rownames(Similarity)\n\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {\n methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL\n }\n # methods::slot(object, slot.name)$similarity[[type]]$matrix <- Similarity\n methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity\n return(object)\n}\n\n\n#' Manifold learning of the signaling networks based on their similarity\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object\n#' @param pathway.remove a range of the number of patterns\n#' @param umap.method UMAP implementation to run.\n#'\n#' Can be umap-learn: Run the python umap-learn package; uwot: Runs umap via the uwot R package; If umap.method = \"uwot\", please make sure you have installed the 'uwot' (https://github.com/jlmelville/uwot)\n#'\n#' @param n_neighbors the number of nearest neighbors in running umap\n#' @param min_dist This controls how tightly the embedding is allowed compress points together.\n#' Larger values ensure embedded points are moreevenly distributed, while smaller values allow the\n#' algorithm to optimise more accurately with regard to local structure. Sensible values are in the range 0.001 to 0.5.\n#' @param ... Parameters passing to umap\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetEmbedding <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, pathway.remove = NULL,\n umap.method = c(\"umap-learn\", \"uwot\"), n_neighbors = NULL,min_dist = 0.3,...) {\n umap.method <- match.arg(umap.method)\n if (object@options$mode == \"single\") {\n comparison <- \"single\"\n cat(\"Manifold learning of the signaling networks for a single dataset\", '\\n')\n } else if (object@options$mode == \"merged\") {\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Manifold learning of the signaling networks for datasets\", as.character(comparison), '\\n')\n }\n comparison.name <- paste(comparison, collapse = \"-\")\n Similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n if (is.null(pathway.remove)) {\n pathway.remove <- rownames(Similarity)[which(colSums(Similarity) == 1)]\n }\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(rownames(Similarity) %in% pathway.remove)\n Similarity <- Similarity[-pathway.remove.idx, -pathway.remove.idx]\n }\n if (is.null(n_neighbors)) {\n n_neighbors <- ceiling(sqrt(dim(Similarity)[1])) + 1\n }\n options(warn = -1)\n # dimension reduction\n if (umap.method == \"umap-learn\") {\n Y <- runUMAP(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)\n } else if (umap.method == \"uwot\") {\n Y <- uwot::umap(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)\n colnames(Y) <- paste0('UMAP', 1:ncol(Y))\n rownames(Y) <- colnames(Similarity)\n }\n\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$dr)) {\n methods::slot(object, slot.name)$similarity[[type]]$dr <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]] <- Y\n return(object)\n}\n\n\n#' Classification learning of the signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object\n#' @param k the number of signaling groups when running kmeans\n#' @param methods the methods for clustering: \"kmeans\" or \"spectral\"\n#' @param do.plot whether showing the eigenspectrum for inferring number of clusters; Default will save the plot\n#' @param fig.id add a unique figure id when saving the plot\n#' @param do.parallel whether doing parallel when inferring the number of signaling groups when running kmeans\n#' @param nCores number of workers when doing parallel\n#' @param k.eigen the number of eigenvalues used when doing spectral clustering\n#' @importFrom methods slot\n#' @importFrom future nbrOfWorkers plan\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @return\n#' @export\n#'\n#' @examples\nnetClustering <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, k = NULL, methods = \"kmeans\", do.plot = TRUE, fig.id = NULL, do.parallel = TRUE, nCores = 4, k.eigen = NULL) {\n type <- match.arg(type)\n if (object@options$mode == \"single\") {\n comparison <- \"single\"\n cat(\"Classification learning of the signaling networks for a single dataset\", '\\n')\n } else if (object@options$mode == \"merged\") {\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Classification learning of the signaling networks for datasets\", as.character(comparison), '\\n')\n }\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n data.use <- Y\n if (methods == \"kmeans\") {\n if (!is.null(k)) {\n clusters = kmeans(data.use,k,nstart=10)$cluster\n } else {\n N <- nrow(data.use)\n kRange <- seq(2,min(N-1, 10),by = 1)\n if (do.parallel) {\n future::plan(\"multisession\", workers = nCores)\n options(future.globals.maxSize = 1000 * 1024^2)\n }\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n results = my.sapply(\n X = 1:length(kRange),\n FUN = function(x) {\n idents <- kmeans(data.use,kRange[x],nstart=10)$cluster\n clusIndex <- idents\n #adjMat0 <- as.numeric(outer(clusIndex, clusIndex, FUN = \"==\")) - outer(1:N, 1:N, \"==\")\n adjMat0 <- Matrix::Matrix(as.numeric(outer(clusIndex, clusIndex, FUN = \"==\")), nrow = N, ncol = N)\n return(list(adjMat = adjMat0, ncluster = length(unique(idents))))\n },\n simplify = FALSE\n )\n adjMat <- lapply(results, \"[[\", 1)\n CM <- Reduce('+', adjMat)/length(kRange)\n res <- computeEigengap(as.matrix(CM))\n numCluster <- res$upper_bound\n clusters = kmeans(data.use,numCluster,nstart=10)$cluster\n if (do.plot) {\n gg <- res$gg.obj\n ggsave(filename= paste0(\"estimationNumCluster_\",fig.id,\"_\",type,\"_dataset_\",comparison.name,\".pdf\"), plot=gg, width = 3.5, height = 3, units = 'in', dpi = 300)\n }\n }\n\n } else if (methods == \"spectral\") {\n A <- as.matrix(data.use)\n D <- apply(A, 1, sum)\n L <- diag(D)-A # unnormalized version\n L <- diag(D^-0.5)%*%L%*% diag(D^-0.5) # normalized version\n evL <- eigen(L,symmetric=TRUE) # evL$values is decreasing sorted when symmetric=TRUE\n # pick the first k first k eigenvectors (corresponding k smallest) as data points in spectral space\n plot(rev(evL$values)[1:30])\n Z <- evL$vectors[,(ncol(evL$vectors)-k.eigen+1):ncol(evL$vectors)]\n clusters = kmeans(Z,k,nstart=20)$cluster\n }\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$group)) {\n methods::slot(object, slot.name)$similarity[[type]]$group <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]] <- clusters\n return(object)\n}\n\n\n#' Build SNN matrix\n# #' Adapted from swne (https://github.com/yanwu2014/swne)\n#' @param data.use Features x samples matrix to use to build the SNN\n#' @param k Defines k for the k-nearest neighbor algorithm\n#' @param k.scale Granularity option for k.param\n#' @param prune.SNN Sets the cutoff for acceptable Jaccard distances when\n#' computing the neighborhood overlap for the SNN construction.\n#'\n#' @return Returns similarity matrix in sparse matrix format\n#'\n#' @importFrom FNN get.knn\n#' @importFrom Matrix sparseMatrix\n#' @export\n#'\nbuildSNN <- function(data.use, k = 10, k.scale = 10, prune.SNN = 1/15) {\n n.cells <- ncol(data.use)\n if (n.cells < k) {\n stop(\"k cannot be greater than the number of samples\")\n }\n\n ## find the k-nearest neighbors for each single cell\n my.knn <- FNN::get.knn(t(as.matrix(data.use)), k = min(k.scale * k, n.cells - 1))\n nn.ranked <- cbind(1:n.cells, my.knn$nn.index[, 1:(k - 1)])\n nn.large <- my.knn$nn.index\n\n w <- ComputeSNN(nn.ranked, prune.SNN)\n colnames(w) <- rownames(w) <- colnames(data.use)\n\n Matrix::diag(w) <- 1\n return(w)\n}\n\n\n\n#' Compute the eigengap of a given matrix for inferring the number of clusters\n#'\n#' @param CM consensus matrix\n#' @param tau truncated consensus matrix\n#' @param tol tolerance\n#' @return\n#' @import ggplot2\n#' @export\ncomputeEigengap <- function(CM, tau = NULL, tol = 0.01){\n # compute the drop tolerance, enforcing parsimony of components\n K.init <- computeLaplacian(CM, tol = tol)$n_zeros\n if (is.null(tau)) {\n if (K.init <= 5) {\n tau = 0.3\n } else if (K.init <= 10){\n tau = 0.4\n } else {\n tau = 0.5\n }\n }\n\n # truncate the ensemble consensus matrix\n CM[CM <= tau] <- 0;\n # normalize and make symmetric\n CM <- (CM + t(CM))/2\n eigs <- computeLaplacian(CM, tol = tol)\n\n # compute the largest eigengap\n gaps <- diff(eigs$val)\n upper_bound <- which(gaps == max(gaps))\n\n # compute the number of zero eigenvalues\n lower_bound <- eigs$n_zeros\n\n df <- data.frame(nCluster = 1:min(c(30,length(eigs$val))), eigenVal = eigs$val[1:min(c(30,length(eigs$val)))])\n g <- ggplot(df, aes(x = nCluster, y = eigenVal)) + geom_point(size = 1) +\n geom_point(aes(x= upper_bound, y= eigs$val[upper_bound]), colour=\"red\", size = 3, pch = 1) + theme(legend.position=\"none\")\n title.name <- paste0('Inferred number of clusters: ', upper_bound,'; Min number: ', lower_bound)\n g <- g + labs(title = title.name) + theme_bw() + scale_x_continuous(breaks=seq(0,30,5)) +\n theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = 10)) + labs(x = 'Number of clusters', y = 'Eigenvalue of graph Laplacian')+\n theme(axis.text.x = element_text(size = 8), axis.text.y = element_text(size = 8))\n # ggsave(filename= paste0(\"estimationNumCluster_eigenspectrum\",sample.int(100,1),\".pdf\"), plot=g, width = 3.5, height = 3, units = 'in', dpi = 300)\n return(list(upper_bound = upper_bound,\n lower_bound = lower_bound,\n eigs = eigs,\n gg.obj = g))\n\n}\n\n\n#' Compute eigenvalues of associated Laplacian matrix of a given matrix\n#'\n#' @param CM consensus matrix\n#' @param tol tolerance\n#' @return\n#' @importFrom RSpectra eigs_sym\n#' @importFrom Matrix colSums\n#' @export\ncomputeLaplacian <- function(CM, tol = 0.01) {\n # Normalized Laplacian:\n Dsq <- sqrt(Matrix::colSums(CM))\n L <- -Matrix::t(CM / Dsq) / Dsq\n Matrix::diag(L) <- 1 + Matrix::diag(L)\n\n numEigs <- min(100,nrow(CM))\n res <- RSpectra::eigs_sym(L, k = numEigs, which = \"SM\", opt = list(tol = 1e-4))\n eigs <- abs(Re(res$values))\n n_zeros <- sum(eigs <= tol)\n return(list(val = sort(eigs), n_zeros = n_zeros))\n}\n\n\n#' Rank the similarity of the shared signaling pathways based on their joint manifold learning\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison1 a numerical vector giving the datasets for comparison. This should be the same as `comparison` in `computeNetSimilarityPairwise`\n#' @param comparison2 a numerical vector with two elements giving the datasets for comparison.\n#'\n#' If there are more than 2 datasets defined in `comparison1`, `comparison2` can be defined to indicate which two datasets used for computing the distance.\n#' e.g., comparison2 = c(1,3) indicates the first and third datasets defined in `comparison1` will be used for comparison.\n#' @param x.rotation rotation of x-labels\n#' @param title main title of the plot\n#' @param bar.w the width of bar plot\n#' @param color.use defining the color\n#' @param font.size font size\n#' @import ggplot2\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nrankSimilarity <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison1 = NULL, comparison2 = c(1,2),\n x.rotation = 90, title = NULL, color.use = NULL, bar.w = NULL, font.size = 8) {\n type <- match.arg(type)\n\n if (is.null(comparison1)) {\n comparison1 <- 1:length(unique(object@meta$datasets))\n }\n comparison.name <- paste(comparison1, collapse = \"-\")\n cat(\"Compute the distance of signaling networks between datasets\", as.character(comparison1[comparison2]), '\\n')\n comparison2.name <- names(methods::slot(object, slot.name))[comparison1[comparison2]]\n # net <- list()\n # for (i in 1:length(comparison2)) {\n # net[[i]] = methods::slot(object, slot.name)[[comparison1[comparison2[i]]]]$prob\n # }\n\n #net.dim <- sapply(net, dim)[3,]\n #position <- cumsum(net.dim); position <- c(0,position)\n # if (is.null(pathway.remove)) {\n # similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n # pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove.idx <- which(rownames(similarity) %in% pathway.remove)\n # }\n\n # if (length(pathway.remove.idx) > 0) {\n # for (i in 1:length(pathway.remove.idx)) {\n # idx <- which(position - pathway.remove.idx[i] > 0)\n # if (!is.null(idx)) {\n # position[idx[1]] <- position[idx[1]] - 1\n # if (idx[1] == 2) {\n # position[3] <- position[3] - 1\n # }\n # }\n # }\n # }\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n group <- sub(\".*--\", \"\", rownames(Y))\n data1 <- Y[group %in% comparison2.name[1], ]\n data2 <- Y[group %in% comparison2.name[2], ]\n rownames(data1) <- sub(\"--.*\", \"\", rownames(data1))\n rownames(data2) <- sub(\"--.*\", \"\", rownames(data2))\n\n pathway.show = as.character(intersect(rownames(data1), rownames(data2)))\n data1 <- data1[pathway.show, ]\n data2 <- data2[pathway.show, ]\n euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))\n dist <- NULL\n for(i in 1:nrow(data1)) dist[i] <- euc.dist(data1[i,],data2[i,])\n df <- data.frame(name = pathway.show, dist = dist, row.names = pathway.show)\n df <- df[order(df$dist), , drop = F]\n df$name <- factor(df$name, levels = as.character(df$name))\n\n gg <- ggplot(df, aes(x=name, y=dist)) + geom_bar(stat=\"identity\",width = bar.w) +\n theme_classic() + theme(text=element_text(size=font.size),axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_text(size=font.size)) +\n xlab(\"\") + ylab(\"Pathway distance\") + coord_flip()#+\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n if (!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = 1), drop = FALSE, na.value = \"white\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, na.value = \"white\")\n }\n return(gg)\n}\n\n\n\n\n\n\n\n#' Rank signaling networks based on the information flow or the number of interactions\n#'\n#' This function can also be used to rank signaling from certain cell groups to other cell groups\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param measure \"weight\" or \"count\". \"weight\": comparing the total interaction weights (strength); \"count\": comparing the number of interactions;\n#' @param mode \"single\",\"comparison\"\n#' @param comparison a numerical vector giving the datasets for comparison; a single value means ranking for only one dataset and two values means ranking comparison for two datasets\n#' @param color.use defining the color for each cell group\n#' @param stacked whether plot the stacked bar plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a vector giving the signaling pathway to show\n#' @param pairLR a vector giving the names of L-R pairs to show (e.g, pairLR = c(\"IL1A_IL1R1_IL1RAP\",\"IL1B_IL1R1_IL1RAP\"))\n#' @param signaling.type a char giving the types of signaling from the three categories c(\"Secreted Signaling\", \"ECM-Receptor\", \"Cell-Cell Contact\")\n#' @param do.stat whether do a Wilcoxon test to determine whether there is significant difference between two datasets. Default = FALSE\n#' @param paired.test a logical indicating whether you want a paired test. Paired test is applicable to compare two datasets with the same cellular compositions.\n#' @param cutoff.pvalue the cutoff of pvalue when doing Wilcoxon test; Default = 0.05\n#' @param tol a tolerance when considering the relative contribution being equal between two datasets. contribution.relative between 1-tol and 1+tol will be considered as equal contribution\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @param do.flip whether flip the x-y axis\n#' @param x.angle,y.angle,x.hjust,y.hjust parameters for rotating and spacing axis labels\n#' @param axis.gap whetehr making gaps in y-axes\n#' @param ylim,segments,tick_width,rel_heights parameters in the function gg.gap when making gaps in y-axes\n#' e.g., ylim = c(0, 35), segments = list(c(11, 14),c(16, 28)), tick_width = c(5,2,5), rel_heights = c(0.8,0,0.1,0,0.1)\n#' https://tobiasbusch.xyz/an-r-package-for-everything-ep2-gaps\n#' @param show.raw whether show the raw information flow. Default = FALSE, showing the scaled information flow to provide compariable data scale; When stacked = TRUE, use raw information flow by default.\n#' @param return.data whether return the data.frame consisting of the calculated information flow of each signaling pathway or L-R pair\n#' @param x.rotation rotation of x-labels\n#' @param title main title of the plot\n#' @param bar.w the width of bar plot\n#' @param font.size font size\n\n#' @import ggplot2\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nrankNet <- function(object, slot.name = \"netP\", measure = c(\"weight\",\"count\"), mode = c(\"comparison\", \"single\"), comparison = c(1,2), color.use = NULL, stacked = FALSE, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR = NULL, signaling.type = NULL, do.stat = FALSE, paired.test = TRUE, cutoff.pvalue = 0.05, tol = 0.05, thresh = 0.05, show.raw = FALSE, return.data = FALSE, x.rotation = 90, title = NULL, bar.w = 0.75, font.size = 8,\n do.flip = TRUE, x.angle = NULL, y.angle = 0, x.hjust = 1,y.hjust = 1,\n axis.gap = FALSE, ylim = NULL, segments = NULL, tick_width = NULL, rel_heights = c(0.9,0,0.1)) {\n measure <- match.arg(measure)\n mode <- match.arg(mode)\n options(warn = -1)\n object.names <- names(methods::slot(object, slot.name))\n if (measure == \"weight\") {\n ylabel = \"Information flow\"\n } else if (measure == \"count\") {\n ylabel = \"Number of interactions\"\n }\n if (mode == \"single\") {\n object1 <- methods::slot(object, slot.name)\n prob = object1$prob\n prob[object1$pval > thresh] <- 0\n if (measure == \"count\") {\n prob <- 1*(prob > 0)\n }\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n if (sum(prob) == 0) {\n stop(\"No inferred communications for the input!\")\n }\n\n pSum <- apply(prob, 3, sum)\n pSum.original <- pSum\n if (measure == \"weight\") {\n pSum <- -1/log(pSum)\n pSum[is.na(pSum)] <- 0\n idx1 <- which(is.infinite(pSum) | pSum < 0)\n values.assign <- seq(max(pSum)*1.1, max(pSum)*1.5, length.out = length(idx1))\n position <- sort(pSum.original[idx1], index.return = TRUE)$ix\n pSum[idx1] <- values.assign[match(1:length(idx1), position)]\n } else if (measure == \"count\") {\n pSum <- pSum.original\n }\n\n pair.name <- names(pSum)\n\n df<- data.frame(name = pair.name, contribution = pSum.original, contribution.scaled = pSum, group = object.names[comparison[1]])\n idx <- with(df, order(df$contribution))\n df <- df[idx, ]\n df$name <- factor(df$name, levels = as.character(df$name))\n for (i in 1:length(pair.name)) {\n df.t <- df[df$name == pair.name[i], \"contribution\"]\n if (sum(df.t) == 0) {\n df <- df[-which(df$name == pair.name[i]), ]\n }\n }\n\n if (!is.null(signaling.type)) {\n LR <- subset(object@DB$interaction, annotation %in% signaling.type)\n if (slot.name == \"netP\") {\n signaling <- unique(LR$pathway_name)\n } else if (slot.name == \"net\") {\n pairLR <- LR$interaction_name\n }\n }\n\n if ((slot.name == \"netP\") && (!is.null(signaling))) {\n df <- subset(df, name %in% signaling)\n } else if ((slot.name == \"netP\") &&(!is.null(pairLR))) {\n stop(\"You need to set `slot.name == 'net'` if showing specific L-R pairs \")\n }\n if ((slot.name == \"net\") && (!is.null(pairLR))) {\n df <- subset(df, name %in% pairLR)\n } else if ((slot.name == \"net\") && (!is.null(signaling))) {\n stop(\"You need to set `slot.name == 'netP'` if showing specific signaling pathways \")\n }\n\n gg <- ggplot(df, aes(x=name, y=contribution.scaled)) + geom_bar(stat=\"identity\",width = bar.w) +\n theme_classic() + theme(axis.text=element_text(size=font.size),axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(ylabel) + coord_flip()#+\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n\n } else if (mode == \"comparison\") {\n prob.list <- list()\n pSum <- list()\n pSum.original <- list()\n pair.name <- list()\n idx <- list()\n pSum.original.all <- c()\n object.names.comparison <- c()\n for (i in 1:length(comparison)) {\n object.list <- methods::slot(object, slot.name)[[comparison[i]]]\n prob <- object.list$prob\n prob[object.list$pval > thresh] <- 0\n if (measure == \"count\") {\n prob <- 1*(prob > 0)\n }\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n if (sum(prob) == 0) {\n stop(\"No inferred communications for the input!\")\n }\n prob.list[[i]] <- prob\n pSum.original[[i]] <- apply(prob, 3, sum)\n if (measure == \"weight\") {\n pSum[[i]] <- -1/log(pSum.original[[i]])\n pSum[[i]][is.na(pSum[[i]])] <- 0\n idx[[i]] <- which(is.infinite(pSum[[i]]) | pSum[[i]] < 0)\n pSum.original.all <- c(pSum.original.all, pSum.original[[i]][idx[[i]]])\n } else if (measure == \"count\") {\n pSum[[i]] <- pSum.original[[i]] # the prob is already binarized in line 1136\n }\n pair.name[[i]] <- names(pSum.original[[i]])\n object.names.comparison <- c(object.names.comparison, object.names[comparison[i]])\n }\n if (measure == \"weight\") {\n values.assign <- seq(max(unlist(pSum))*1.1, max(unlist(pSum))*1.5, length.out = length(unlist(idx)))\n position <- sort(pSum.original.all, index.return = TRUE)$ix\n for (i in 1:length(comparison)) {\n if (i == 1) {\n pSum[[i]][idx[[i]]] <- values.assign[match(1:length(idx[[i]]), position)]\n } else {\n pSum[[i]][idx[[i]]] <- values.assign[match(length(unlist(idx[1:i-1]))+1:length(unlist(idx[1:i])), position)]\n }\n }\n }\n\n\n\n pair.name.all <- as.character(unique(unlist(pair.name)))\n df <- list()\n for (i in 1:length(comparison)) {\n df[[i]] <- data.frame(name = pair.name.all, contribution = 0, contribution.scaled = 0, group = object.names[comparison[i]], row.names = pair.name.all)\n df[[i]][pair.name[[i]],3] <- pSum[[i]]\n df[[i]][pair.name[[i]],2] <- pSum.original[[i]]\n }\n\n\n # contribution.relative <- as.numeric(format(df[[length(comparison)]]$contribution/abs(df[[1]]$contribution), digits=1))\n # # contribution.relative <- as.numeric(format(df[[length(comparison)]]$contribution.scaled/abs(df[[1]]$contribution.scaled), digits=1))\n # contribution.relative2 <- as.numeric(format(df[[length(comparison)-1]]$contribution/abs(df[[1]]$contribution), digits=1))\n # contribution.relative[is.na(contribution.relative)] <- 0\n # for (i in 1:length(comparison)) {\n # df[[i]]$contribution.relative <- contribution.relative\n # df[[i]]$contribution.relative2 <- contribution.relative2\n # }\n # df[[1]]$contribution.data2 <- df[[length(comparison)]]$contribution\n # idx <- with(df[[1]], order(-contribution.relative, -contribution.relative2, contribution, -contribution.data2))\n #\n contribution.relative <- list()\n for (i in 1:(length(comparison)-1)) {\n contribution.relative[[i]] <- as.numeric(format(df[[length(comparison)-i+1]]$contribution/df[[1]]$contribution, digits=1))\n contribution.relative[[i]][is.na(contribution.relative[[i]])] <- 0\n }\n names(contribution.relative) <- paste0(\"contribution.relative.\", 1:length(contribution.relative))\n for (i in 1:length(comparison)) {\n for (j in 1:length(contribution.relative)) {\n df[[i]][[names(contribution.relative)[j]]] <- contribution.relative[[j]]\n }\n }\n df[[1]]$contribution.data2 <- df[[length(comparison)]]$contribution\n if (length(comparison) == 2) {\n idx <- with(df[[1]], order(-contribution.relative.1, contribution, -contribution.data2))\n } else if (length(comparison) == 3) {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2,contribution, -contribution.data2))\n } else if (length(comparison) == 4) {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2, -contribution.relative.3, contribution, -contribution.data2))\n } else {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2, -contribution.relative.3, -contribution.relative.4, contribution, -contribution.data2))\n }\n\n\n\n for (i in 1:length(comparison)) {\n df[[i]] <- df[[i]][idx, ]\n df[[i]]$name <- factor(df[[i]]$name, levels = as.character(df[[i]]$name))\n }\n df[[1]]$contribution.data2 <- NULL\n\n df <- do.call(rbind, df)\n df$group <- factor(df$group, levels = object.names.comparison)\n\n if (is.null(color.use)) {\n color.use = ggPalette(length(comparison))\n }\n\n # https://stackoverflow.com/questions/49448497/coord-flip-changes-ordering-of-bars-within-groups-in-grouped-bar-plot\n df$group <- factor(df$group, levels = rev(levels(df$group)))\n color.use <- rev(color.use)\n\n # perform statistical analysis\n # if (do.stat) {\n # pvalues <- c()\n # for (i in 1:length(pair.name.all)) {\n # df.prob <- data.frame()\n # for (j in 1:length(comparison)) {\n # if (pair.name.all[i] %in% pair.name[[j]]) {\n # df.prob <- rbind(df.prob, data.frame(prob = as.vector(prob.list[[j]][ , , pair.name.all[i]]), group = comparison[j]))\n # } else {\n # df.prob <- rbind(df.prob, data.frame(prob = as.vector(matrix(0, nrow = nrow(prob.list[[j]]), ncol = nrow(prob.list[[j]]))), group = comparison[j]))\n # }\n #\n # }\n # df.prob$group <- factor(df.prob$group, levels = comparison)\n # if (length(comparison) == 2) {\n # pvalues[i] <- wilcox.test(prob ~ group, data = df.prob)$p.value\n # } else {\n # pvalues[i] <- kruskal.test(prob ~ group, data = df.prob)$p.value\n # }\n # }\n # df$pvalues <- pvalues\n # }\n if (do.stat & length(comparison) == 2) {\n for (i in 1:length(pair.name.all)) {\n if (nrow(prob.list[[j]]) != nrow(prob.list[[1]])) {\n if (paired.test) {\n stop(\"Paired test is not applicable to datasets with different cellular compositions! Please set `do.stat = FALSE` or `paired.test = FALSE`! \\n\")\n }\n }\n prob.values <- matrix(0, nrow = nrow(prob.list[[1]]) * nrow(prob.list[[1]]), ncol = length(comparison))\n for (j in 1:length(comparison)) {\n if (pair.name.all[i] %in% pair.name[[j]]) {\n prob.values[, j] <- as.vector(prob.list[[j]][ , , pair.name.all[i]])\n } else {\n prob.values[, j] <- NA\n }\n }\n prob.values <- prob.values[rowSums(prob.values, na.rm = TRUE) != 0, , drop = FALSE]\n if (nrow(prob.values) >3 & sum(is.na(prob.values)) == 0) {\n pvalues <- wilcox.test(prob.values[ ,1], prob.values[ ,2], paired = paired.test)$p.value\n } else {\n pvalues <- 0\n }\n pvalues[is.na(pvalues)] <- 0\n df$pvalues[df$name == pair.name.all[i]] <- pvalues\n }\n }\n\n\n if (length(comparison) == 2) {\n if (do.stat) {\n colors.text <- ifelse((df$contribution.relative < 1-tol) & (df$pvalues < cutoff.pvalue), color.use[2], ifelse((df$contribution.relative > 1+tol) & df$pvalues < cutoff.pvalue, color.use[1], \"black\"))\n } else {\n colors.text <- ifelse(df$contribution.relative < 1-tol, color.use[2], ifelse(df$contribution.relative > 1+tol, color.use[1], \"black\"))\n }\n } else {\n message(\"The text on the y-axis will not be colored for the number of compared datasets larger than 3!\")\n colors.text = NULL\n }\n\n for (i in 1:length(pair.name.all)) {\n df.t <- df[df$name == pair.name.all[i], \"contribution\"]\n if (sum(df.t) == 0) {\n df <- df[-which(df$name == pair.name.all[i]), ]\n }\n }\n\n if ((slot.name == \"netP\") && (!is.null(signaling))) {\n df <- subset(df, name %in% signaling)\n } else if ((slot.name == \"netP\") &&(!is.null(pairLR))) {\n stop(\"You need to set `slot.name == 'net'` if showing specific L-R pairs \")\n }\n if ((slot.name == \"net\") && (!is.null(pairLR))) {\n df <- subset(df, name %in% pairLR)\n } else if ((slot.name == \"net\") && (!is.null(signaling))) {\n stop(\"You need to set `slot.name == 'netP'` if showing specific signaling pathways \")\n }\n\n if (stacked) {\n gg <- ggplot(df, aes(x=name, y=contribution, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position =\"fill\") # +\n # xlab(\"\") + ylab(\"Relative information flow\") #+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n # scale_y_discrete(breaks=c(\"0\",\"0.5\",\"1\")) +\n if (measure == \"weight\") {\n gg <- gg + xlab(\"\") + ylab(\"Relative information flow\")\n } else if (measure == \"count\") {\n gg <- gg + xlab(\"\") + ylab(\"Relative number of interactions\")\n }\n\n gg <- gg + geom_hline(yintercept = 0.5, linetype=\"dashed\", color = \"grey50\", size=0.5)\n } else {\n if (show.raw) {\n gg <- ggplot(df, aes(x=name, y=contribution, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position = position_dodge(0.8)) +\n xlab(\"\") + ylab(ylabel) #+ coord_flip()#+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n } else {\n gg <- ggplot(df, aes(x=name, y=contribution.scaled, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position = position_dodge(0.8)) +\n xlab(\"\") + ylab(ylabel) #+ coord_flip()#+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n }\n\n if (axis.gap) {\n gg <- gg + theme_bw() + theme(panel.grid = element_blank())\n gg.gap::gg.gap(gg,\n ylim = ylim,\n segments = segments,\n tick_width = tick_width,\n rel_heights = rel_heights)\n }\n }\n gg <- gg + CellChat_theme_opts() + theme_classic()\n if (do.flip) {\n gg <- gg + coord_flip() + theme(axis.text.y = element_text(colour = colors.text))\n if (is.null(x.angle)) {\n x.angle = 0\n }\n\n } else {\n if (is.null(x.angle)) {\n x.angle = 45\n }\n gg <- gg + scale_x_discrete(limits = rev) + theme(axis.text.x = element_text(colour = rev(colors.text)))\n\n }\n\n gg <- gg + theme(axis.text=element_text(size=font.size), axis.title.y = element_text(size=font.size))\n gg <- gg + scale_fill_manual(name = \"\", values = color.use)\n gg <- gg + guides(fill = guide_legend(reverse = TRUE))\n gg <- gg + theme(axis.text.x = element_text(angle = x.angle, hjust=x.hjust),\n axis.text.y = element_text(angle = y.angle, hjust=y.hjust))\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n }\n\n if (return.data) {\n df$contribution <- abs(df$contribution)\n df$contribution.scaled <- abs(df$contribution.scaled)\n return(list(signaling.contribution = df, gg.obj = gg))\n } else {\n return(gg)\n }\n}\n\n\n#' Comparing the number of inferred communication links between different datasets\n#'\n#' @param object A merged CellChat object\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param color.use defining the color for each group of datasets\n#' @param group a vector giving the groups of different datasets to define colors of the bar plot. Default: only one group and a single color\n#' @param group.levels the factor level in the defined group\n#' @param group.facet Name of one metadata column defining faceting groups\n#' @param group.facet.levels the factor level in the defined group.facet\n#' @param n.row Number of rows in facet_grid()\n#' @param color.alpha transparency\n#' @param legend.title legend title\n#' @param width bar width\n#' @param title.name main title of the plot\n#' @param digits integer indicating the number of decimal places (round) to be used when `measure` is `weight`.\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param remove.xtick whether remove xtick\n#' @param size.text font size of the text\n#' @param show.legend whether show the legend\n#' @param x.lab.rot,angle.x,vjust.x,hjust.x adjusting parameters if rotating xtick.labels when x.lab.rot = TRUE\n#' @import ggplot2\n#' @return A ggplot object\n#' @export\n#'\ncompareInteractions <- function(object, measure = c(\"count\", \"weight\"), color.use = NULL, group = NULL, group.levels = NULL, group.facet = NULL, group.facet.levels = NULL, n.row = 1, color.alpha = 1, legend.title = NULL, width=0.6, title.name = NULL, digits = 3,\n xlabel = NULL, ylabel = NULL, remove.xtick = FALSE,\n show.legend = TRUE, x.lab.rot = FALSE, angle.x = 45, vjust.x = NULL, hjust.x = 1, size.text = 10) {\n measure <- match.arg(measure)\n if (measure == \"count\") {\n df <- as.data.frame(sapply(object@net, function(x) sum(x$count)))\n if (is.null(ylabel)) {\n ylabel = \"Number of inferred interactions\"\n }\n } else if (measure == \"weight\") {\n df <- as.data.frame(sapply(object@net, function(x) sum(x$weight)))\n df[,1] <- round(df[,1],digits)\n if (is.null(ylabel)) {\n ylabel = \"Interaction strength\"\n }\n }\n colnames(df) <- \"count\"\n\n df$dataset <- names(object@net)\n if (is.null(group)) {\n group <- 1\n }\n df$group <- group\n df$dataset <- factor(df$dataset, levels = names(object@net))\n if (is.null(group.levels)) {\n df$group <- factor(df$group)\n } else {\n df$group <- factor(df$group, levels = group.levels)\n }\n\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(group)))\n }\n # theme_classic() #+ scale_x_discrete(limits = (levels(df$x)))\n if (!is.null(group.facet)) {\n if (all(group.facet %in% colnames(df))) {\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n gg <- gg + facet_wrap(group.facet, nrow = n.row)\n } else {\n df$group.facet <- group.facet\n if (is.null(group.facet.levels)) {\n df$group.facet <- factor(df$group.facet)\n } else {\n df$group.facet <- factor(df$group.facet, levels = group.facet.levels)\n }\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n gg <- gg + facet_wrap(~group.facet, nrow = n.row)\n }\n } else {\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n }\n gg <- gg + geom_text(aes(label=count), vjust=-0.3, size=3, position = position_dodge(0.9))\n gg <- gg + ylab(ylabel) + xlab(xlabel) + theme_classic() +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = size.text), axis.text = element_text(colour=\"black\"))\n gg <- gg + scale_fill_manual(values = alpha(color.use, alpha = color.alpha), drop = FALSE)\n # gg <- gg + scale_color_manual(values = alpha(color.use, alpha = 1), drop = FALSE) + guides(colour = FALSE)\n if (remove.xtick) {\n gg <- gg + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank())\n }\n if (is.null(legend.title)) {\n gg <- gg + theme(legend.title = element_blank())\n } else {\n gg <- gg + guides(fill=guide_legend(legend.title))\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n if (x.lab.rot) {\n gg <- gg + theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x, vjust = vjust.x, size=size.text))\n }\n gg\n return(gg)\n}\n\n\n#' Rank ligand-receptor interactions for any pair of two cell groups\n#'\n#' @param object CellChat object\n#' @param LR.use ligand-receptor interactions used in inferring communication network\n#' @return\n#' @export\n#'\nrankNetPairwise <- function(object, LR.use = NULL) {\n if (is.null(LR.use)) {\n pairLR.use <- object@LR$LRsig\n } else {\n pairLR.use <- LR.use\n }\n net <- object@net\n prob <- net$prob\n pval <- net$pval\n numCluster <- dim(prob)[1]\n pairwiseLR <- list()\n for (i in 1:numCluster) {\n temp <- list()\n for (j in 1:numCluster) {\n pvalij <- pval[i,j,]; pvalij <- as.vector(pvalij)\n probij <- prob[i,j,]; probij <- as.vector(probij)\n index <- 1:length(pvalij)\n data <- data.frame(pathway_index = index, interaction_name = pairLR.use$interaction_name, interaction_name_2 = pairLR.use$interaction_name_2, pathway_name = pairLR.use$pathway_name, ligand = pairLR.use$ligand, receptor = pairLR.use$receptor,\n prob = probij, pval = pvalij, row.names = rownames(pairLR.use))\n temp[[j]] <- data[with(data, order(pval, -prob)), ]\n }\n names(temp) <- colnames(prob)\n pairwiseLR[[i]] <- temp\n }\n names(pairwiseLR) <- rownames(prob)\n object@net$pairwiseRank <- pairwiseLR\n return(object)\n}\n\n\n#' compute the Shannon entropy\n#'\n#' @param a a numeric vector\n#' @return\nentropia<-function(a){\n a<-a[which(a>0)]\n return(-sum(a*log(a)))\n}\n\n\n#' compute the node distance matrix\n#'\n#' @param g a graph objecct\n#' @return\nnode_distance<-function(g){\n n<-length(V(g))\n if(n==1){\n retorno=1\n }\n\n if(n>1){\n a<-Matrix::Matrix(0,nrow=n,ncol=n,sparse=TRUE)\n m<-igraph::shortest.paths(g,algorithm=c(\"unweighted\"))\n m[which(m==\"Inf\")]<-n\n quem<-setdiff(intersect(m,m),0)\n for(j in (1:length(quem))){\n\n l<-which(m==quem[j])/n\n\n linhas<-floor(l)+1\n\n posicoesm1<-which(l==floor(l))\n\n if(length(posicoesm1)>0){\n linhas[posicoesm1]<-linhas[posicoesm1]-1\n }\n a[1:n,quem[j]]<-hist(linhas,plot=FALSE,breaks=(0:n))$counts\n\n }\n retorno=(a/(n-1))\n }\n return(retorno)\n}\n\n\n#' compute nnd\n#'\n#' @param g a graph objecct\n#' @return\nnnd<-function(g){\n\n N<-length(V(g))\n\n nd<-node_distance(g)\n\n pdfm<-Matrix::colMeans(nd)\n\n norm<-log(max(c(2,length(which(pdfm[1:(N-1)]>0))+1)))\n\n return(c(pdfm,max(c(0,entropia(pdfm)-entropia(as.matrix(nd))/N))/norm))\n}\n\n#' compute alpha centrality\n#'\n#' @param g a graph objecct\n#' @importFrom igraph degree alpha.centrality\n#' @return\nalpha_centrality<-function(g){\n\n N<-length(igraph::V(g))\n\n r<-sort(igraph::alpha.centrality(g,exo=igraph::degree(g)/(N-1),alpha=1/N))/((N^2))\n\n return(c(r,max(c(0,1-sum(r)))))\n\n}\n\n#' Compute the structural distance between two signaling networks\n#'\n#' @param g a graph object of one signaling network\n#' @param h a graph object of another signaling network\n#' @param w1 parameter\n#' @param w2 parameter\n#' @param w3 parameter\n#' @importFrom igraph graph_from_adjacency_matrix V graph.complementer\n#' @return\n#' @export\n#'\n#' @examples\ncomputeNetD_structure <- function(g, h, w1 = 0.45, w2 = 0.45, w3 = 0.1){\n\n first<-0\n\n second<-0\n\n third<-0\n\n # g<-read.graph(g,format=c(\"edgelist\"),directed=FALSE)\n #\n # h<-read.graph(h,format=c(\"edgelist\"),directed=FALSE)\n\n g <- graph_from_adjacency_matrix(g,mode=\"directed\")\n h <- graph_from_adjacency_matrix(h,mode=\"directed\")\n\n N<-length(V(g))\n\n M<-length(V(h))\n\n PM<-matrix(0,ncol=max(c(M,N)))\n\n if(w1+w2>0){\n\n pg = nnd(g)\n\n PM[1:(N-1)]=pg[1:(N-1)]\n\n PM[length(PM)]<-pg[N]\n\n ph=nnd(h)\n\n PM[1:(M-1)]=PM[1:(M-1)]+ph[1:(M-1)]\n\n PM[length(PM)]<-PM[length(PM)]+ph[M]\n\n PM<-PM/2\n\n first<-sqrt(max(c((entropia(PM)-(entropia(pg[1:N])+entropia(ph[1:M]))/2)/log(2),0)))\n\n second<-abs(sqrt(pg[N+1])-sqrt(ph[M+1]))\n\n\n }\n\n if(w3>0){\n\n pg<-alpha_centrality(g)\n\n ph<-alpha_centrality(h)\n\n m<-max(c(length(pg),length(ph)))\n\n Pg<-matrix(0,ncol=m)\n\n Ph<-matrix(0,ncol=m)\n\n Pg[(m-length(pg)+1):m]<-pg\n\n Ph[(m-length(ph)+1):m]<-ph\n\n third<-third+sqrt((entropia((Pg+Ph)/2)-(entropia(pg)+entropia(ph))/2)/log(2))/2\n\n g<-graph.complementer(g)\n\n h<-graph.complementer(h)\n\n\n pg<-alpha_centrality(g)\n\n ph<-alpha_centrality(h)\n\n m<-max(c(length(pg),length(ph)))\n\n Pg<-matrix(0,ncol=m)\n\n Ph<-matrix(0,ncol=m)\n\n Pg[(m-length(pg)+1):m]<-pg\n\n Ph[(m-length(ph)+1):m]<-ph\n\n third<-third+sqrt((entropia((Pg+Ph)/2)-(entropia(pg)+entropia(ph))/2)/log(2))/2\n }\n return(w1*first+w2*second+w3*third)\n}\n\n\n#' Identify all the significant interactions (L-R pairs) and related signaling genes for a given signaling pathway\n#'\n#' @param object CellChat object\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param geneLR.return whether return the related signaling genes of enriched L-R pairs\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param geneInfo a dataframe with gene official symbol (there should be one column named `Symbol`)\n#' @param complex_input signaling complex information from CellChatDB\n#' @importFrom dplyr select\n#'\n#' @return The returned value depends on the input argument:\n#'\n#' When `geneLR.return = FALSE`, it returns a data frame containing the significant interactions (L-R pairs)\n#'\n#' When `geneLR.return = TRUE`, it returns a list, the first element is a data frame containing the significant interactions (L-R pairs), and the second is a vector containing the related signaling genes of enriched L-R pairs, which can be used for examining the gene expression pattern using the function \\code{\\link{plotGeneExpression}}\n#'\n#' @export\n#'\nextractEnrichedLR <- function(object, signaling, geneLR.return = FALSE, enriched.only = TRUE, thresh = 0.05, geneInfo = NULL, complex_input = NULL) {\n DB <- object@DB\n if (is.null(geneInfo)) {\n geneInfo = DB$geneInfo\n } else {\n DB$geneInfo = geneInfo\n }\n if (is.null(complex_input)) {\n complex_input = DB$complex\n } else {\n DB$complex = complex_input\n }\n pairLR.all <- c()\n geneLR.all <- c()\n net0 <- slot(object, \"net\")\n for (ii in 1:length(signaling)) {\n signaling.i <- signaling[ii]\n if (object@options$mode == \"single\") {\n net <- net0\n LR <- object@LR\n res <- extractEnrichedLR_internal(net, LR, DB, signaling = signaling.i, enriched.only = enriched.only, thresh = thresh)\n } else {\n geneLR.t <- c()\n pairLR.t <- c()\n for (i in 1:length(net0)) {\n net <- net0[[i]]\n LR <- object@LR[[i]]\n res.t <- extractEnrichedLR_internal(net, LR, DB, signaling = signaling.i, enriched.only = enriched.only, thresh = thresh)\n geneLR.t <- BiocGenerics::union(geneLR.t, as.character(res.t[[1]]))\n pairLR.t <- BiocGenerics::union(pairLR.t, as.character(res.t[[2]]))\n }\n res <- list(geneLR.t, pairLR.t)\n }\n geneLR.all <- c(geneLR.all, as.character(res[[1]]))\n pairLR.all <- c(pairLR.all, as.character(res[[2]]))\n }\n pairLR.all <- data.frame(interaction_name = pairLR.all, stringsAsFactors = FALSE)\n\n if (geneLR.return) {\n return(list(pairLR = pairLR.all, geneLR = geneLR.all))\n } else {\n return(pairLR.all)\n }\n}\n\n#' Identify all the significant interactions (L-R pairs) and related signaling genes for a given signaling pathway\n#'\n#' @param net,LR,DB object@net object@LR object@DB\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom dplyr select\n#'\n#' @return a list: list(geneLR, pairLR.name.use)\nextractEnrichedLR_internal <- function(net, LR, DB, signaling, enriched.only = TRUE, thresh = 0.05){\n pairLR <- searchPair(signaling = signaling, pairLR.use = LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.name.use = dplyr::select(DB$interaction[rownames(pairLR),],\"interaction_name\")\n if (enriched.only) {\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n if (length(pairLR.name.use) == 0) {\n message(paste0('There is no significant communication of ', signaling))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n }\n geneL <- unique(pairLR$ligand)\n geneR <- unique(pairLR$receptor)\n geneL <- extractGeneSubset(geneL, DB$complex, DB$geneInfo)\n geneR <- extractGeneSubset(geneR, DB$complex, DB$geneInfo)\n geneLR <- c(geneL, geneR)\n return(list(geneLR, pairLR.name.use))\n}\n\n\n#' Compute the maximum value of certain measures in the inferred cell-cell communication networks\n#'\n#' To better control the node size and edge weights of the inferred networks across different datasets,\n#' we compute the maximum number of cells per cell group and the maximum number of interactions (or interaction weights) across all datasets\n#'\n#' @param object.list List of CellChat objects\n#' @param slot.name the slot name of object that is used to compute the maximum value.\n#'\n#' When slot.name = \"idents\", 'attribute' should be \"idents\", which will compute the maximum number of cells per cell group across all datasets\n#'\n#' When slot.name = \"net\", 'attribute' can be either \"count\" or \"weight\", which will compute he maximum number of interactions (or interaction weights) across all datasets\n#'\n#' When slot.name = \"net\" or \"netP\", 'attribute' can be a single pathway name or a ligand-receptor pair name\n#'\n#' @param attribute the attribute to compute the maximum values. `attribute` should have the same length as `slot.name`.\n#'\n#' `attribute` can only be \"count\", \"weight\",\"count.merged\",\"weight.merged\" or a single pathway name or a ligand-receptor pair name\n#'\n#' @return A numeric vector\n#' @export\n#'\ngetMaxWeight <- function(object.list, slot.name = c(\"idents\", \"net\"), attribute = c(\"idents\", \"count\")) {\n weight <- c()\n for (i in 1:length(slot.name)) {\n if (slot.name[i] == \"idents\") {\n weight.all <- sapply(object.list, function (x) {max(as.numeric(table(slot(x, slot.name[i]))))})\n } else if ((slot.name[i] == \"net\") & (attribute[i] %in% c(\"count\", \"weight\",\"count.merged\",\"weight.merged\"))) {\n weight.all <- sapply(object.list, function (x) {max(slot(x, slot.name[i])[[attribute[i]]])})\n } else if (attribute[i] %in% c(object.list[[1]]@DB$interaction$pathway_name, object.list[[1]]@DB$interaction$interaction_name)) {\n weight.all <- sapply(object.list, function (x) {max(slot(x, slot.name[i])$prob[,,attribute[i]])})\n }\n weight[i] <- max(weight.all)\n }\n names(weight) <- attribute\n weight.max <- weight\n return(weight.max)\n}\n\n\n#' Compute the number of interactions/interaction strength between cell types based on their associated cell subpopulations\n#'\n#' @param object CellChat object\n#' @param group.merged a factor defining the group for merging different clusters/subpopulations\n#'\n#' @return An updated slot `net` by adding three elements:\n#'\n#' `count.merged`: the number of interactions between cell types (i.e., merged cell groups)\n#'\n#' `weight.merged`: interaction strength between cell types (i.e., merged cell groups)\n#'\n#' `group.merged` the defined group for merging different clusters/subpopulations\n#'\n#' @export\n#'\nmergeInteractions <- function(object, group.merged) {\n if (!is.factor(group.merged)) {\n group.merged <- factor(group.merged)\n }\n count <- object@net$count\n count.merged <- matrix(0, nrow = nlevels(group.merged), ncol = nlevels(group.merged))\n rownames(count.merged) <- levels(group.merged); colnames(count.merged) <- levels(group.merged);\n weight <- object@net$weight\n weight.merged <- count.merged\n dimnames(weight.merged) <- dimnames(count.merged)\n for (i in levels(group.merged)) {\n for (j in levels(group.merged)) {\n count.merged[i, j] <- sum(count[group.merged == i, group.merged == j])\n weight.merged[i, j] <- sum(weight[group.merged == i, group.merged == j])\n }\n }\n object@net$count.merged <- count.merged\n object@net$weight.merged <- weight.merged\n object@net$group.merged <- group.merged\n return(object)\n}\n\n\n#' Subset the inferred cell-cell communications of interest\n#'\n#' NB: If all arguments are NULL, it returns a data frame consisting of all the inferred cell-cell communications\n#'\n#' @param object CellChat object\n#' @param net Alternative input is a data frame with at least with three columns defining the cell-cell communication network (\"source\",\"target\",\"interaction_name\")\n#' @param slot.name the slot name of object: slot.name = \"net\" when extracting the inferred communications at the level of ligands/receptors; slot.name = \"netP\" when extracting the inferred communications at the level of signaling pathways\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param datasets select the inferred cell-cell communications from a particular `datasets` when inputing a data frame `net`\n#' @param ligand.pvalues,ligand.logFC,ligand.pct.1,ligand.pct.2 set threshold for ligand genes\n#'\n#' ligand.pvalues: threshold for pvalues in the differential expression gene analysis (DEG)\n#'\n#' ligand.logFC: threshold for logFoldChange in the DEG analysis; When ligand.logFC > 0, keep upgulated genes; otherwise, kepp downregulated genes\n#'\n#' ligand.pct.1: threshold for the percent of expressed genes in the defined 'positive' cell group. keep genes with percent greater than ligand.pct.1\n#'\n#' ligand.pct.2: threshold for the percent of expressed genes in the cells except for the defined 'positive' cell group\n#'\n#' @param receptor.pvalues,receptor.logFC,receptor.pct.1,receptor.pct.2 set threshold for receptor genes\n#' @importFrom dplyr select group_by summarize groups\n#' @importFrom stringr str_split\n#' @importFrom BiocGenerics as.data.frame\n#' @importFrom reshape2 melt\n#' @importFrom magrittr %>%\n#'\n#' @return If input object is created from a single dataset, a data frame of the inferred cell-cell communications of interest, consisting of source, target, interaction_name, pathway_name, prob and other information\n#'\n#' If input object is a merged object from multiple datasets, it will return a list and each element is a data frame for one dataset\n#'\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # access all the inferred cell-cell communications\n#' df.net <- subsetCommunication(cellchat)\n#'\n#' # access all the inferred cell-cell communications at the level of signaling pathways\n#' df.net <- subsetCommunication(cellchat, slot.name = \"netP\")\n#'\n#' # Subset to certain cells with sources.use and targets.use\n#' df.net <- subsetCommunication(cellchat, sources.use = c(1,2), targets.use = c(4,5))\n#'\n#' # Subset to certain signaling, e.g., WNT and TGFb\n#' df.net <- subsetCommunication(cellchat, signaling = c(\"WNT\", \"TGFb\"))\n#'}\n#'\nsubsetCommunication <- function(object = NULL, net = NULL, slot.name = \"net\",\n sources.use = NULL, targets.use = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n thresh = 0.05,\n datasets = NULL, ligand.pvalues = NULL, ligand.logFC = NULL, ligand.pct.1 = NULL, ligand.pct.2 = NULL,\n receptor.pvalues = NULL, receptor.logFC = NULL, receptor.pct.1 = NULL, receptor.pct.2 = NULL) {\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n message(\"slot.name is set to be 'netP' when pairLR.use contains signaling pathways\")\n slot.name = \"netP\"\n }\n }\n\n if (!is.null(pairLR.use) & !is.null(signaling)) {\n stop(\"Please do not assign values to 'signaling' when using 'pairLR.use'\")\n }\n\n if (object@options$mode == \"single\") {\n if (is.null(net)) {\n net <- slot(object, \"net\")\n }\n LR <- object@LR$LRsig\n cells.level <- levels(object@idents)\n df.net <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n } else if (object@options$mode == \"merged\") {\n if (is.null(net)) {\n net0 <- slot(object, \"net\")\n df.net <- vector(\"list\", length(net0))\n names(df.net) <- names(net0)\n for (i in 1:length(net0)) {\n net <- net0[[i]]\n LR <- object@LR[[i]]$LRsig\n cells.level <- levels(object@idents[[i]])\n\n df.net[[i]] <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n }\n } else {\n LR <- data.frame()\n for (i in 1:length(object@LR)) {\n LR <- rbind(LR, object@LR[[i]]$LRsig)\n }\n LR <- unique(LR)\n cells.level <- levels(object@idents$joint)\n df.net <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n }\n\n }\n\n return(df.net)\n\n}\n\n#' Subset the inferred cell-cell communications of interest\n#'\n#' NB: If all arguments are NULL, it returns a data frame consisting of all the inferred cell-cell communications\n#'\n#' @param net,LR,cells.level net is object@net or a data frame; LR: object@LR$LRsig; cells.level: levels(object@idents)\n#' @param slot.name the slot name of object: slot.name = \"net\" when extracting the inferred communications at the level of ligands/receptors; slot.name = \"netP\" when extracting the inferred communications at the level of signaling pathways\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param datasets select the inferred cell-cell communications from a particular `datasets` when inputing a data frame `net`\n#' @param ligand.pvalues,ligand.logFC,ligand.pct.1,ligand.pct.2 set threshold for ligand genes\n#'\n#' ligand.pvalues: threshold for pvalues in the differential expression gene analysis (DEG)\n#'\n#' ligand.logFC: threshold for logFoldChange in the DEG analysis; When ligand.logFC > 0, keep upgulated genes; otherwise, kepp downregulated genes\n#'\n#' ligand.pct.1: threshold for the percent of expressed genes in the defined 'positive' cell group. keep genes with percent greater than ligand.pct.1\n#'\n#' ligand.pct.2: threshold for the percent of expressed genes in the cells except for the defined 'positive' cell group\n#'\n#' @param receptor.pvalues,receptor.logFC,receptor.pct.1,receptor.pct.2 set threshold for receptor genes\n#' @importFrom dplyr select group_by summarize groups\n#' @importFrom stringr str_split\n#' @importFrom BiocGenerics as.data.frame\n#' @importFrom reshape2 melt\n#' @importFrom magrittr %>%\n#'\n#' @return A data frame of the inferred cell-cell communications of interest, consisting of source, target, interaction_name, pathway_name, prob and other information\n\nsubsetCommunication_internal <- function(net, LR, cells.level, slot.name = \"net\",\n sources.use = NULL, targets.use = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n thresh = 0.05,\n datasets = NULL, ligand.pvalues = NULL, ligand.logFC = NULL, ligand.pct.1 = NULL, ligand.pct.2 = NULL,\n receptor.pvalues = NULL, receptor.logFC = NULL, receptor.pct.1 = NULL, receptor.pct.2 = NULL) {\n if (!is.data.frame(net)) {\n prob <- net$prob\n pval <- net$pval\n prob[pval >= thresh] <- 0\n net <- reshape2::melt(prob, value.name = \"prob\")\n colnames(net)[1:3] <- c(\"source\",\"target\",\"interaction_name\")\n net.pval <- reshape2::melt(pval, value.name = \"pval\")\n net$pval <- net.pval$pval\n # remove the interactions with zero values\n net <- subset(net, prob > 0)\n }\n if (!(\"ligand\" %in% colnames(net))) {\n col.use <- intersect(c(\"interaction_name_2\", \"pathway_name\", \"ligand\", \"receptor\" ,\"annotation\",\"evidence\"), colnames(LR))\n pairLR <- dplyr::select(LR, col.use)\n idx <- match(net$interaction_name, rownames(pairLR))\n net <- cbind(net, pairLR[idx,])\n }\n\n if (!is.null(signaling)) {\n pairLR.use <- data.frame()\n for (i in 1:length(signaling)) {\n pairLR.use.i <- searchPair(signaling = signaling[i], pairLR.use = LR, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.use <- rbind(pairLR.use, pairLR.use.i)\n }\n }\n\n if (!is.null(pairLR.use)){\n net <- tryCatch({\n subset(net,interaction_name %in% pairLR.use$interaction_name)\n }, error = function(e) {\n subset(net, pathway_name %in% pairLR.use$pathway_name)\n })\n }\n\n if (!is.null(datasets)) {\n if (!(\"datasets\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before selecting 'datasets'\")\n }\n net <- net[net$datasets %in% datasets, , drop = FALSE]\n }\n if (!is.null(ligand.pvalues)){\n if (!(\"ligand.pvalues\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pvalues'\")\n }\n net <- net[net$ligand.pvalues <= ligand.pvalues, , drop = FALSE]\n }\n if (!is.null(ligand.logFC)){\n if (!(\"ligand.logFC\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.logFC'\")\n }\n if (ligand.logFC >= 0) {\n net <- net[net$ligand.logFC >= ligand.logFC, , drop = FALSE]\n } else {\n net <- net[net$ligand.logFC <= ligand.logFC, , drop = FALSE]\n }\n }\n if (!is.null(ligand.pct.1)){\n if (!(\"ligand.pct.1\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pct.1'\")\n }\n net <- net[net$ligand.pct.1 >= ligand.pct.1, , drop = FALSE]\n }\n if (!is.null(ligand.pct.2)){\n if (!(\"ligand.pct.2\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pct.2'\")\n }\n net <- net[net$ligand.pct.2 >= ligand.pct.2, , drop = FALSE]\n }\n\n if (!is.null(receptor.pvalues)){\n if (!(\"receptor.pvalues\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pvalues'\")\n }\n net <- net[net$receptor.pvalues <= receptor.pvalues, , drop = FALSE]\n }\n if (!is.null(receptor.logFC)){\n if (!(\"receptor.logFC\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.logFC'\")\n }\n if (receptor.logFC >= 0) {\n net <- net[net$receptor.logFC >= receptor.logFC, , drop = FALSE]\n } else {\n net <- net[net$receptor.logFC <= receptor.logFC, , drop = FALSE]\n }\n }\n if (!is.null(receptor.pct.1)){\n if (!(\"receptor.pct.1\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pct.1'\")\n }\n net <- net[net$receptor.pct.1 >= receptor.pct.1, , drop = FALSE]\n }\n if (!is.null(receptor.pct.2)){\n if (!(\"receptor.pct.2\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pct.2'\")\n }\n net <- net[net$receptor.pct.2 >= receptor.pct.2, , drop = FALSE]\n }\n\n net <- net[rowSums(is.na(net)) != ncol(net), , drop = FALSE]\n\n if (nrow(net) == 0) {\n stop(\"No significant signaling interactions are inferred based on the input!\")\n }\n\n\n if (slot.name == \"netP\") {\n col.use <- intersect(c(\"source\",\"target\",\"pathway_name\",\"prob\", \"pval\",\"annotation\"), colnames(net))\n net <- dplyr::select(net, col.use)\n net$source_target <- paste(net$source, net$target, sep = \"sourceTotarget\")\n # net$source_target_pathway <- paste(paste(net$source, net$target, sep = \"_\"), net$pathway_name, sep = \"_\")\n net.pval <- net %>% group_by(source_target, pathway_name) %>% summarize(pval = mean(pval), .groups = 'drop')\n net <- net %>% group_by(source_target, pathway_name) %>% summarize(prob = sum(prob), .groups = 'drop')\n a <- stringr::str_split(net$source_target, \"sourceTotarget\", simplify = T)\n net$source <- as.character(a[, 1])\n net$target <- as.character(a[, 2])\n net <- dplyr::select(net, -source_target)\n net$pval <- net.pval$pval\n }\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n }\n\n net <- BiocGenerics::as.data.frame(net, stringsAsFactors=FALSE)\n\n if (nrow(net) == 0) {\n warning(\"No significant signaling interactions are inferred!\")\n } else {\n rownames(net) <- 1:nrow(net)\n }\n\n if (slot.name == \"net\") {\n if ((\"ligand.logFC\" %in% colnames(net)) & (\"datasets\" %in% colnames(net))) {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\",\n \"datasets\",\"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\", \"ligand.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\", \"receptor.pvalues\"), colnames(net))\n net <- net[,col.use]\n } else if (\"ligand.logFC\" %in% colnames(net)) {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\",\n \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\", \"ligand.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\", \"receptor.pvalues\"), colnames(net))\n net <- net[,col.use]\n } else {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\"), colnames(net))\n net <- net[,col.use]\n }\n } else if (slot.name == \"netP\") {\n col.use <- intersect(c(\"source\", \"target\", \"pathway_name\", \"prob\", \"pval\"), colnames(net))\n net <- net[,col.use]\n }\n\n return(net)\n\n}\n\n\n\n\n\n\n\n\n\n\n#' Heatmap showing the centrality scores/importance of cell groups as senders, receivers, mediators and influencers in a single intercellular communication network\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the name of signaling networks\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param measure centrality measures to show\n#' @param measure.name the names of centrality measures to show\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation draw\n#' @importFrom stats setNames\n#'\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_signalingRole_network <- function(object, signaling, slot.name = \"netP\", measure = c(\"outdeg\",\"indeg\",\"flowbet\",\"info\"), measure.name = c(\"Sender\",\"Receiver\",\"Mediator\",\"Influencer\"),\n color.use = NULL, color.heatmap = \"BuGn\",\n width = 6.5, height = 1.4, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE) {\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n centr <- slot(object, slot.name)$centr[signaling]\n for(i in 1:length(centr)) {\n centr0 <- centr[[i]]\n mat <- matrix(unlist(centr0), ncol = length(centr0), byrow = FALSE)\n mat <- t(mat)\n rownames(mat) <- names(centr0); colnames(mat) <- names(centr0$outdeg)\n if (!is.null(measure)) {\n mat <- mat[measure,,drop = FALSE]\n if (!is.null(measure.name)) {\n if (length(measure.name) != length(measure)) {\n stop(\"The length of `measure.name` is not the same as that of `measure`! Please modify it! \\n\")\n }\n rownames(mat) <- measure.name\n }\n }\n mat <- sweep(mat, 1L, apply(mat, 1, max), '/', check.margin = FALSE)\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(colnames(mat)))\n }\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n\n df<- data.frame(group = colnames(mat)); rownames(df) <- colnames(mat)\n cell.cols.assigned <- setNames(color.use, unique(as.character(df$group)))\n col_annotation <- HeatmapAnnotation(df = df, col = list(group = cell.cols.assigned),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = \"Importance\",\n bottom_annotation = col_annotation,\n cluster_rows = cluster.rows,cluster_columns = cluster.cols,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = paste0(names(centr[i]), \" signaling pathway network\"),column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 45,\n heatmap_legend_param = list(title = \"Importance\", title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = c(round(min(mat, na.rm = T), digits = 1), round(max(mat, na.rm = T), digits = 1)),\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n draw(ht1)\n }\n}\n\n\n#' 2D visualization of dominant senders (sources) and receivers (targets)\n#'\n#' @description\n#' This scatter plot shows the dominant senders (sources) and receivers (targets) in a 2D space.\n#' x-axis and y-axis are respectively the total outgoing or incoming communication probability associated with each cell group.\n#' Dot size is proportional to the number of inferred links (both outgoing and incoming) associated with each cell group.\n#' Dot colors indicate different cell groups. Dot shapes indicate different categories of cell groups if `group`` is defined.\n#'\n#' @param object CellChat object\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param color.use defining the color for each cell group\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param group a vector to categorize the cell groups, e.g., categorize the cell groups into two major categories: immune cells and fibroblasts\n#' @param weight.MinMax the Minmum/maximum weight, which is useful to control the dot size when comparing multiple datasets\n#' @param point.shape point shape when group is not NULL\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size a range defining the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_signalingRole_scatter <- function(object, signaling = NULL, color.use = NULL, slot.name = \"netP\", group = NULL, weight.MinMax = NULL, dot.size = c(2, 6), point.shape = c(21, 22, 24, 23, 25, 8, 3), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\",xlabel = \"Outgoing interaction strength\", ylabel = \"Incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n centr <- slot(object, slot.name)$centr\n outgoing <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n incoming <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n dimnames(outgoing) <- list(levels(object@idents), names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n if (is.null(signaling)) {\n message(\"Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\")\n } else {\n message(\"Signaling role analysis on the cell-cell communication network from user's input\")\n signaling <- signaling[signaling %in% object@netP$pathways]\n if (length(signaling) == 0) {\n stop('There is no significant communication for the input signaling. All the significant signaling are shown in `object@netP$pathways`')\n }\n outgoing <- outgoing[ , signaling, drop = FALSE]\n incoming <- incoming[ , signaling, drop = FALSE]\n }\n outgoing.cells <- rowSums(outgoing)\n incoming.cells <- rowSums(incoming)\n\n num.link <- aggregateNet(object, signaling = signaling, return.object = FALSE, remove.isolate = FALSE)$count\n num.link <- rowSums(num.link) + colSums(num.link)-diag(num.link)\n df <- data.frame(x = outgoing.cells, y = incoming.cells, labels = names(incoming.cells),\n Count = num.link)\n df$labels <- factor(df$labels, levels = names(incoming.cells))\n if (!is.null(group)) {\n df$Group <- group\n }\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(object@idents))\n }\n if (!is.null(group)) {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Count, colour = labels, fill = labels, shape = Group))\n } else {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Count, colour = labels, fill = labels))\n }\n\n gg <- gg + CellChat_theme_opts() +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\"))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE) + guides(colour=\"none\")\n # gg <- gg + scale_colour_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(colour=\"none\")\n # gg <- gg + scale_shape_manual(values = point.shape[1:length(prob)])\n if (!is.null(group)) {\n gg <- gg + scale_shape_manual(values = point.shape[1:length(unique(df$Group))])\n }\n if (is.null(weight.MinMax)) {\n gg <- gg + scale_size_continuous(range = dot.size)\n } else {\n gg <- gg + scale_size_continuous(limits = weight.MinMax, range = dot.size)\n }\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = labels), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n\n#' 2D visualization of differential signaling roles (dominant senders (sources) or receivers (targets) ) of each cell group when comparing mutiple datasets\n#'\n#' @description\n#' This scatter plot shows the differential signaling roles (dominant senders (sources) or receivers (targets) in a 2D space.\n#'\n#' x-axis and y-axis are respectively the differential outgoing or incoming communication probability associated with each cell group.\n#' Dot colors indicate different cell groups. Dot shapes indicate different categories of cell groups if `group`` is defined.\n#'\n#' Positive values indicate the increase in the second dataset while negative values indicate the increase in the first dataset\n#'\n#' @param object A merged CellChat object of a list of CellChat objects\n#' @param color.use defining the color for each cell group\n#' @param comparison an index vector giving the two datasets for comparison\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param signaling.exclude signaling pathways to exclude\n#' @param idents.exclude cell groups to exclude. This is useful when zooming into the small changes\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param group a vector to categorize the cell groups, e.g., categorize the cell groups into two major categories: immune cells and fibroblasts\n#' @param point.shape point shape when group is not NULL\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., Outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., Incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_diff_signalingRole_scatter <- function(object, color.use = NULL, comparison = c(1,2), signaling = NULL, signaling.exclude = NULL, idents.exclude = NULL, slot.name = \"netP\", group = NULL, dot.size = 2.5, point.shape = c(21, 22, 24, 23, 25, 8, 3), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\", xlabel = \"Outgoing interaction strength\", ylabel = \"Incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (is.list(object)) {\n object <- mergeCellChat(object, add.names = names(object))\n }\n if (!is.list(object@net[[1]])) {\n stop(\"This function cannot be applied to a single cellchat object from one dataset!\")\n }\n\n dataset.name <- names(object@net)\n message(paste0(\"Visualizing differential outgoing and incoming signaling changes from \", dataset.name[comparison[1]], \" to \", dataset.name[comparison[2]]))\n title <- paste0(\"Signaling changes \", \" (\", dataset.name[comparison[1]], \" vs. \", dataset.name[comparison[2]], \")\")\n\n cell.levels <- levels(object@idents$joint)\n if (is.null(xlabel) | is.null(ylabel)) {\n xlabel = \"Differential outgoing interaction strength\"\n ylabel = \"Differential incoming interaction strength\"\n }\n if (is.null(signaling)) {\n signaling <- union(object@netP[[comparison[1]]]$pathways, object@netP[[comparison[2]]]$pathways)\n }\n if (!is.null(signaling.exclude)) {\n signaling <- setdiff(signaling, signaling.exclude)\n }\n\n mat.all.merged <- list()\n for (ii in 1:length(comparison)) {\n if (length(slot(object, slot.name)[[comparison[ii]]]$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores for each dataset seperately! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n\n centr <- slot(object, slot.name)[[comparison[ii]]]$centr\n outgoing <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n incoming <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n dimnames(outgoing) <- list(cell.levels, names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n mat.out <- t(outgoing)\n mat.in <- t(incoming)\n\n mat.all <- array(0, dim = c(length(signaling),ncol(mat.out),2))\n mat.t <-list(mat.out, mat.in)\n for (i in 1:length(comparison)) {\n mat = mat.t[[i]]\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n mat.all[,,i] = mat\n }\n dimnames(mat.all) <- list(dimnames(mat)[[1]], dimnames(mat)[[2]], c(\"outgoing\", \"incoming\"))\n mat.all.merged[[ii]] <- mat.all\n\n }\n\n mat.diff <- mat.all.merged[[2]] - mat.all.merged[[1]]\n\n outgoing.diff <- colSums(mat.diff[ , , 1])\n incoming.diff <- colSums(mat.diff[ , , 2])\n\n\n df <- data.frame(x = outgoing.diff, y = incoming.diff, labels = names(incoming.diff))\n df$labels <- factor(df$labels, levels = names(incoming.diff))\n if (!is.null(group)) {\n df$Group <- group\n }\n if (is.null(color.use)) {\n color.use <- scPalette(length(cell.levels))\n }\n if (!is.null(idents.exclude)) {\n df <- df[!(df$labels %in% idents.exclude), ]\n color.use <- color.use[!(cell.levels %in% idents.exclude)]\n df$labels = droplevels(df$labels, exclude = setdiff(levels(df$labels),unique(df$labels)))\n }\n\n if (!is.null(group)) {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = labels, fill = labels, shape = Group), size = dot.size)\n } else {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = labels, fill = labels), size = dot.size)\n }\n\n gg <- gg + CellChat_theme_opts() + theme_linedraw() +theme(panel.grid = element_blank()) +\n geom_hline(yintercept=0,linetype=\"dashed\", color = \"grey50\", size = 0.25) + geom_vline(xintercept=0, linetype=\"dashed\", color = \"grey50\",size = 0.25) +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\", hjust = 0.5))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE) + guides(colour=\"none\")\n if (!is.null(group)) {\n gg <- gg + scale_shape_manual(values = point.shape[1:length(unique(df$Group))])\n }\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = labels), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n\n#' 2D visualization of differential outgoing and incoming signaling associated with one cell group\n#'\n#' @description\n#' Positive values indicate the increase in the second dataset while negative values indicate the increase in the first dataset\n#'\n#'\n#' @param object A merged CellChat object of a list of CellChat objects\n#' @param idents.use the cell group names of interest. Should be one of `levels(object@idents$joint)`\n#' @param color.use a vector with three elements: the first is for coloring shared pathways, the second is for specific pathways in the first dataset, and the third is for specific pathways in the second dataset\n#' @param comparison an index vector giving the two datasets for comparison\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param signaling.label a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param signaling.exclude signaling pathways to exclude when plotting\n#' @param xlims,ylims set x-Axis and y-Axis Limits for zoom into the plot. e.g., xlims = c(-0.05, 0.1), ylims = c(-0.01, 0.035)\n#' @param slot.name the slot name of object\n#' @param point.shape point shape\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., Outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., Incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @importFrom plyr mapvalues\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_signalingChanges_scatter <- function(object, idents.use, color.use = c(\"grey10\", \"#F8766D\", \"#00BFC4\"), comparison = c(1,2), signaling = NULL, signaling.label = NULL, top.label = 1, signaling.exclude = NULL, xlims = NULL, ylims = NULL,slot.name = \"netP\", dot.size = 2.5, point.shape = c(21, 22, 24, 23), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\", xlabel = \"Differential outgoing interaction strength\", ylabel = \"Differential incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (is.list(object)) {\n object <- mergeCellChat(object, add.names = names(object))\n }\n if (is.list(object@net[[1]])) {\n dataset.name <- names(object@net)\n message(paste0(\"Visualizing differential outgoing and incoming signaling changes from \", dataset.name[comparison[1]], \" to \", dataset.name[comparison[2]]))\n title <- paste0(\"Signaling changes of \", idents.use, \" (\", dataset.name[comparison[1]], \" vs. \", dataset.name[comparison[2]], \")\")\n\n cell.levels <- levels(object@idents$joint)\n if (is.null(xlabel) | is.null(ylabel)) {\n xlabel = \"Differential outgoing interaction strength\"\n ylabel = \"Differential incoming interaction strength\"\n }\n\n } else {\n message(\"Visualizing outgoing and incoming signaling on a single object \\n\")\n title <- paste0(\"Signaling patterns of \", idents.use)\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n cell.levels <- levels(object@idents)\n }\n if (!(idents.use %in% cell.levels)) {\n stop(\"Please check the input cell group names!\")\n }\n if (is.null(signaling)) {\n signaling <- union(object@netP[[comparison[1]]]$pathways, object@netP[[comparison[2]]]$pathways)\n }\n if (!is.null(signaling.exclude)) {\n signaling <- setdiff(signaling, signaling.exclude)\n }\n mat.all.merged <- list()\n for (ii in 1:length(comparison)) {\n if (length(slot(object, slot.name)[[comparison[ii]]]$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores for each dataset seperately! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n centr <- slot(object, slot.name)[[comparison[ii]]]$centr\n outgoing <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n incoming <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n dimnames(outgoing) <- list(cell.levels, names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n mat.out <- t(outgoing)\n mat.in <- t(incoming)\n\n mat.all <- array(0, dim = c(length(signaling),ncol(mat.out),2))\n mat.t <-list(mat.out, mat.in)\n for (i in 1:length(comparison)) {\n mat = mat.t[[i]]\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n mat.all[,,i] = mat\n }\n dimnames(mat.all) <- list(dimnames(mat)[[1]], dimnames(mat)[[2]], c(\"outgoing\", \"incoming\"))\n mat.all.merged[[ii]] <- mat.all\n }\n mat.all.merged.use <- list(mat.all.merged[[1]][,idents.use,], mat.all.merged[[2]][,idents.use,])\n idx.specific <- mat.all.merged.use[[1]] * mat.all.merged.use[[2]]\n mat.sum <- mat.all.merged.use[[2]] + mat.all.merged.use[[1]]\n out.specific.signaling <- rownames(idx.specific)[(mat.sum[,1] != 0) & (idx.specific[,1] == 0)]\n in.specific.signaling <- rownames(idx.specific)[(mat.sum[,2] != 0) & (idx.specific[,2] == 0)]\n\n mat.diff <- mat.all.merged.use[[2]] - mat.all.merged.use[[1]]\n idx <- rowSums(mat.diff) != 0\n mat.diff <- mat.diff[idx, ]\n out.specific.signaling <- rownames(mat.diff) %in% out.specific.signaling\n in.specific.signaling <- rownames(mat.diff) %in% in.specific.signaling\n out.in.specific.signaling <- as.logical(out.specific.signaling * in.specific.signaling)\n specificity.out.in <- matrix(0, nrow = nrow(mat.diff), ncol = 1)\n specificity.out.in[out.in.specific.signaling] <- 2 # both outgoing and incoming specific to one condition\n specificity.out.in[setdiff(which(out.specific.signaling), which(out.in.specific.signaling))] <- 1 # only outgoing specific to one condition\n specificity.out.in[setdiff(which(in.specific.signaling), which(out.in.specific.signaling))] <- -1 # only incoming specific to one condition\n\n\n df <- as.data.frame(mat.diff)\n df$specificity.out.in <- specificity.out.in\n df$specificity = 0\n df$specificity[(specificity.out.in != 0) & (rowSums(mat.diff >= 0) ==2)] = 1 # specific to dataset 2\n df$specificity[(specificity.out.in != 0) & (rowSums(mat.diff <= 0) ==2)] = -1 # specific to dataset 1\n\n # change number to char\n out.in.category <- c(\"Shared\", \"Incoming specific\", \"Outgoing specific\", \"Incoming & Outgoing specific\")\n specificity.category <- c(\"Shared\", paste0(dataset.name[comparison[1]],\" specific\"), paste0(dataset.name[comparison[2]],\" specific\"))\n df$specificity.out.in <- plyr::mapvalues(df$specificity.out.in, from = c(0,-1,1,2),to = out.in.category)\n df$specificity.out.in <- factor(df$specificity.out.in, levels = out.in.category)\n df$specificity <- plyr::mapvalues(df$specificity, from = c(0,-1,1),to = specificity.category)\n df$specificity <- factor(df$specificity, levels = specificity.category)\n\n point.shape.use <- point.shape[out.in.category %in% unique(df$specificity.out.in)]\n df$specificity.out.in = droplevels(df$specificity.out.in, exclude = setdiff(out.in.category,unique(df$specificity.out.in)))\n\n color.use <- color.use[specificity.category %in% unique(df$specificity)]\n df$specificity = droplevels(df$specificity, exclude = setdiff(specificity.category,unique(df$specificity)))\n\n df$labels <- rownames(df)\n gg <- ggplot(data = df, aes(outgoing, incoming)) +\n geom_point(aes(colour = specificity, fill = specificity, shape = specificity.out.in), size = dot.size)\n gg <- gg + theme_linedraw() +theme(panel.grid = element_blank()) +\n geom_hline(yintercept=0,linetype=\"dashed\", color = \"grey50\", size = 0.25) + geom_vline(xintercept=0, linetype=\"dashed\", color = \"grey50\",size = 0.25) +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, hjust = 0.5, face=\"plain\"))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n gg <- gg + scale_shape_manual(values = point.shape.use)\n gg <- gg + theme(legend.title = element_blank())\n if (!is.null(xlims)) {\n gg <- gg + xlim(xlims)\n }\n if (!is.null(ylims)) {\n gg <- gg + ylim(ylims)\n }\n\n if (do.label) {\n if (is.null(signaling.label)) {\n thresh <- stats::quantile(abs(as.matrix(df[,1:2])), probs = 1-top.label)\n idx = abs(df[,1]) > thresh | abs(df[,2]) > thresh\n data.label <- df[idx,]\n } else {\n data.label <- df[rownames(df) %in% signaling.label, ]\n }\n\n gg <- gg + ggrepel::geom_text_repel(data = data.label, mapping = aes(label = labels, colour = specificity), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n#' Heatmap showing the contribution of signals (signaling pathways or ligand-receptor pairs) to cell groups in terms of outgoing or incoming signaling\n#'\n#' In this heatmap, colobar represents the relative signaling strength of a signaling pathway across cell groups (NB: values are row-scaled).\n#' The top colored bar plot shows the total signaling strength of a cell group by summarizing all signaling pathways displayed in the heatmap.\n#' The right grey bar plot shows the total signaling strength of a signaling pathway by summarizing all cell groups displayed in the heatmap.\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the names of signaling networks of interest\n#' @param pattern this parameter can be set as \"outgoing\", \"incoming\" or \"all\". When pattern = \"all\", CellChat aggregates the outgoing and incoming signaling strength together;\n#' @param slot.name the slot name of object that is used to examine the signaling patterns at the level of signaling pathways (slot.name = \"netP\") or ligand-receptor pairs (slot.name = \"net\");\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param title title name\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation anno_barplot rowAnnotation\n#' @importFrom stats setNames\n#'\n#' @return\n#' @export\n#'\nnetAnalysis_signalingRole_heatmap <- function(object, signaling = NULL, pattern = c(\"outgoing\", \"incoming\",\"all\"), slot.name = \"netP\",\n color.use = NULL, color.heatmap = \"BuGn\",\n title = NULL, width = 10, height = 8, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE){\n pattern <- match.arg(pattern)\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n centr <- slot(object, slot.name)$centr\n outgoing <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n incoming <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n dimnames(outgoing) <- list(levels(object@idents), names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]]$outdeg\n incoming[,i] <- centr[[i]]$indeg\n }\n if (pattern == \"outgoing\") {\n mat <- t(outgoing)\n legend.name <- \"Outgoing\"\n } else if (pattern == \"incoming\") {\n mat <- t(incoming)\n legend.name <- \"Incoming\"\n } else if (pattern == \"all\") {\n mat <- t(outgoing+ incoming)\n legend.name <- \"Overall\"\n }\n if (is.null(title)) {\n title <- paste0(legend.name, \" signaling patterns\")\n } else {\n title <- paste0(paste0(legend.name, \" signaling patterns\"), \" - \",title)\n }\n\n if (!is.null(signaling)) {\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n }\n mat.ori <- mat\n mat <- sweep(mat, 1L, apply(mat, 1, max), '/', check.margin = FALSE)\n mat[mat == 0] <- NA\n\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(colnames(mat)))\n }\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n\n df<- data.frame(group = colnames(mat)); rownames(df) <- colnames(mat)\n names(color.use) <- colnames(mat)\n col_annotation <- HeatmapAnnotation(df = df, col = list(group = color.use),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n ha2 = HeatmapAnnotation(Strength = anno_barplot(colSums(mat.ori), border = FALSE,gp = gpar(fill = color.use, col=color.use)), show_annotation_name = FALSE)\n\n pSum <- rowSums(mat.ori)\n pSum.original <- pSum\n pSum <- -1/log(pSum)\n pSum[is.na(pSum)] <- 0\n idx1 <- which(is.infinite(pSum) | pSum < 0)\n if (length(idx1) > 0) {\n values.assign <- seq(max(pSum)*1.1, max(pSum)*1.5, length.out = length(idx1))\n position <- sort(pSum.original[idx1], index.return = TRUE)$ix\n pSum[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n\n ha1 = rowAnnotation(Strength = anno_barplot(pSum, border = FALSE), show_annotation_name = FALSE)\n\n if (min(mat, na.rm = T) == max(mat, na.rm = T)) {\n legend.break <- max(mat, na.rm = T)\n } else {\n legend.break <- c(round(min(mat, na.rm = T), digits = 1), round(max(mat, na.rm = T), digits = 1))\n }\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = \"Relative strength\",\n bottom_annotation = col_annotation, top_annotation = ha2, right_annotation = ha1,\n cluster_rows = cluster.rows,cluster_columns = cluster.rows,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = title,column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 90,\n heatmap_legend_param = list(title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = legend.break,\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n # draw(ht1)\n return(ht1)\n}\n\n\n\n#' Mapping the differential expressed genes (DEG) information onto the inferred cell-cell communications\n#'\n#' This function returns a data frame consisting of all the inferred cell-cell communications with mapped DEG information\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for extracting the DEG in `object@var.features[[features.name]]`\n#' @param variable.all variable.all = TRUE will compute the c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\") for a ligand/receptor complex using the mean value of its all subunits, that is requiring all subunits of the complex are differential expressed;\n#' variable.all = FALSE will compute the minimum value of \"pvalues\" and maximum value of c(\"logFC\", \"pct.1\", \"pct.2\") among the subunits, that is only requiring that any one of the subunits of the complex is differential expressed.\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom dplyr select\n#'\n#' @return a data frame of the inferred cell-cell communications, consisting of source, target, interaction_name, pathway_name, prob and other CellChatDB information as well as DEG information\n#'\n#' @export\n#'\nnetMappingDEG <- function(object, features.name, variable.all = TRUE, thresh = 0.05) {\n features.name <- paste0(features.name, \".info\")\n if (!(features.name %in% names(object@var.features))) {\n stop(\"The input features.name does not exist in `names(object@var.features)`. Please first run `identifyOverExpressedGenes`! \")\n }\n DEG <- object@var.features[[features.name]]\n geneInfo <- object@DB$geneInfo\n complex_input <- object@DB$complex\n\n df.net <- subsetCommunication(object, thresh = thresh)\n if (!is.data.frame(df.net)) {\n net <- data.frame()\n for (ii in 1:length(df.net)) {\n df.net[[ii]]$datasets <- names(df.net)[ii]\n net <- rbind(net, df.net[[ii]])\n }\n } else {\n net <- df.net\n }\n net$source.ligand <- paste0(net$source,\".\", net$ligand)\n net$target.receptor <- paste0(net$target,\".\", net$receptor)\n\n DEG$clusters.features <- paste0(DEG$clusters,\".\", DEG$features)\n\n net <- cbind(net, data.frame(ligand.pvalues = NA, ligand.logFC = NA, ligand.pct.1 = NA, ligand.pct.2 = NA,\n receptor.pvalues = NA, receptor.logFC = NA, receptor.pct.1 = NA, receptor.pct.2 = NA))\n # compute values for ligand\n idx1.ligand <- net$ligand %in% geneInfo$Symbol\n idx2.ligand <- which((net$ligand %in% geneInfo$Symbol) == \"FALSE\")\n idx.pos <- match(net$source.ligand, DEG$clusters.features)\n idx1.source.ligand <- which(!is.na(idx.pos))\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n idx2.source.ligand <- which(idx1.ligand & !(net$source.ligand %in% DEG$clusters.features))\n net[idx1.source.ligand, c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")] <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n\n if (length(idx2.ligand) > 0) {\n net.temp.all <- data.frame()\n for (i in 1:length(idx2.ligand)) {\n complex <- net$ligand[idx2.ligand[i]]\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n\n source.ligand.complex <- paste0(net$source[idx2.ligand[i]],\".\", complexsubunitsV)\n idx.pos <- match(source.ligand.complex, DEG$clusters.features)\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n if (length(idx1.clusters.features) > 0) {\n net.temp <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\"), drop = FALSE]\n if (variable.all == TRUE) {\n net.temp <- colMeans(net.temp, na.rm = TRUE)\n } else {\n net.temp <- c(min(net.temp$pvalues), apply(net.temp[, 2:ncol(net.temp), drop = FALSE], 2, function(x) max(x, na.rm = TRUE)))\n names(net.temp)[1] <- \"pvalues\"\n }\n net.temp <- as.data.frame(t(net.temp))\n colnames(net.temp) <- c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")\n } else {\n net.temp <- data.frame(ligand.pvalues = NA, ligand.logFC = NA, ligand.pct.1 = NA, ligand.pct.2 = NA)\n }\n net.temp.all <- rbind(net.temp.all, net.temp)\n }\n net[idx2.ligand, c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")] <- net.temp.all\n }\n\n # compute values for receptor\n idx1.receptor <- net$receptor %in% geneInfo$Symbol\n idx2.receptor <- which((net$receptor %in% geneInfo$Symbol) == \"FALSE\")\n idx.pos <- match(net$target.receptor, DEG$clusters.features)\n idx1.target.receptor <- which(!is.na(idx.pos))\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n net[idx1.target.receptor, c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")] <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n\n if (length(idx2.receptor) > 0) {\n net.temp.all <- data.frame()\n for (i in 1:length(idx2.receptor)) {\n complex <- net$receptor[idx2.receptor[i]]\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n\n target.receptor.complex <- paste0(net$target[idx2.receptor[i]],\".\", complexsubunitsV)\n idx.pos <- match(target.receptor.complex, DEG$clusters.features)\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n if (length(idx1.clusters.features) > 0) {\n net.temp <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n if (variable.all == TRUE) {\n net.temp <- colMeans(net.temp, na.rm = TRUE)\n } else {\n net.temp <- c(min(net.temp$pvalues, na.rm = TRUE), apply(net.temp[, 2:ncol(net.temp), drop = FALSE], 2, function(x) max(x, na.rm = TRUE)))\n names(net.temp)[1] <- \"pvalues\"\n }\n net.temp <- as.data.frame(t(net.temp))\n colnames(net.temp) <- c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")\n } else {\n net.temp <- data.frame(receptor.pvalues = NA, receptor.logFC = NA, receptor.pct.1 = NA, receptor.pct.2 = NA)\n }\n net.temp.all <- rbind(net.temp.all, net.temp)\n }\n net[idx2.receptor, c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")] <- net.temp.all\n }\n # net <- dplyr::select[net, -c(\"source.ligand\", \"target.receptor\")]\n return(net)\n}\n\n\n#' Compute and visualize the enrichment score of ligand-receptor pairs in one condition compared to another condition\n#'\n#' @param df a dataframe\n#' @param measure compute the enrichment score in terms of \"ligand\", \"signaling\",or \"LR-pair\"\n#' @param color.use defining the color for each group of datasets\n#' @param color.name the color names in RColorBrewer::brewer.pal\n#' @param n.color the number of colors\n#' @param species define the species as one of the c('mouse','human') to extract the CellChatDB; For other species, users need to provide a ligand-receptor database `db`\n#' @param db a customized ligand-receptor database `db`\n#' @param variable.both variable.both = TRUE will require that both ligand and receptor from one pair are over-expressed;\n#' variable.both = FALSE will only require that either ligand or receptor from one pair is over-expressed.\n#' @param scale A vector of length 2 indicating the range of the size of the words.\n#' @param min.freq words with frequency below min.freq will not be plotted\n#' @param max.words Maximum number of words to be plotted. least frequent terms dropped\n#' @param random.order plot words in random order. If false, they will be plotted in decreasing frequency\n#' @param rot.per \tproportion words with 90 degree rotation\n#' @param return.data whether return the data frame for plotting wordcloud\n#' @param seed set a seed\n#' @param ... Other parameters passing to wordcloud::wordcloud\n#' @import dplyr\n#' @return A ggplot object\n#' @export\n#'\ncomputeEnrichmentScore <- function(df, measure = c(\"ligand\", \"signaling\",\"LR-pair\"), variable.both = TRUE, species = c('mouse','human'), db = NULL, color.use = NULL, color.name = \"Dark2\", n.color = 8,\n scale=c(4,.8), min.freq = 0, max.words = 200, random.order = FALSE, rot.per = 0,return.data = FALSE,seed = 1,...) {\n measure <- match.arg(measure)\n species <- match.arg(species)\n LRpairs <- as.character(unique(df$interaction_name))\n ES <- vector(length = length(LRpairs))\n for (i in 1:length(LRpairs)) {\n df.i <- subset(df, interaction_name == LRpairs[i])\n idx = which(rowSums(is.na(df.i)) > 0)\n if (variable.both & (length(idx) > 0)) {\n df.i <- df.i[-idx, ,drop = FALSE]\n }\n ES[i] = mean(abs(df.i$ligand.logFC) * abs(df.i$receptor.logFC) *abs(df.i$ligand.pct.2-df.i$ligand.pct.1)*abs(df.i$receptor.pct.2-df.i$receptor.pct.1), na.rm = TRUE)\n }\n idx.na <- which(is.na(ES))\n if (length(idx.na) > 0) {\n ES <- ES[-idx.na]\n LRpairs <- LRpairs[-idx.na]\n }\n\n if (length(ES) == 0) {\n stop(\"No enriched signaling! Please adjust the parameters for selecting differential expressed signaling!\")\n }\n if (is.null(db)) {\n if (species == \"mouse\") {\n CellChatDB <- CellChatDB.mouse\n } else if (species == 'human') {\n CellChatDB <- CellChatDB.human\n } else {\n stop(\"Only mouse and human are supported currently. Please provide a `db` instead! \")\n }\n } else {\n CellChatDB <- db\n }\n df.es <- CellChatDB$interaction[LRpairs, c(\"ligand\",'receptor','pathway_name')]\n df.es$score <- ES\n # summarize the enrichment score\n df.es.ensemble <- df.es %>% group_by(ligand) %>% summarize(total = sum(score)) # avg = mean(score),\n\n set.seed(seed)\n if (is.null(color.use)) {\n color.use <- RColorBrewer::brewer.pal(n.color, color.name)\n }\n\n wordcloud::wordcloud(words = df.es.ensemble$ligand, freq = df.es.ensemble$total, min.freq = min.freq, max.words = max.words,scale=scale,\n random.order = random.order, rot.per = rot.per, colors = color.use,...)\n if (return.data) {\n return(df.es.ensemble)\n }\n}\n\n\n#' Find the enriched signaling according to the genes (e.g.DEGs) and cell groups of interest\n#'\n#' @param object CellChat object\n#' @param features a vector giving the genes of interest\n#' @param idents a vector giving the names of cell groups of interest. If idents = NULL, it returns signaling according to the input features.\n#' @param pattern \"both\", \"outgoing\" or \"incoming\"\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @return a dataframe of the cell-cell communication associated with the input features.\n#' @export\n#' @examples\n#'\\dontrun{\n#' # find all the significant outgoing signaling according to the features and cell groups of interest\n#' df <- findEnrichedSignaling(object, features = c(\"CCL19\", \"CXCL12\"), idents = c(\"Inflam. FIB\", \"COL11A1+ FIB\"), pattern =\"outgoing\")\n#'}\nfindEnrichedSignaling <- function(object, features, idents = NULL, pattern = c(\"both\",\"outgoing\",\"incoming\"), thresh = 0.05) {\n pattern <- match.arg(pattern)\n df.net <- subsetCommunication(object, thresh = thresh)\n if (!is.null(idents)) {\n if (pattern == \"both\") {\n idx <- (df.net$source %in% idents) | (df.net$target %in% idents)\n } else if (pattern == \"outgoing\") {\n idx <- df.net$source %in% idents\n } else if (pattern == \"incoming\"){\n idx <- df.net$target %in% idents\n }\n idx.feature <- (df.net$ligand %in% features) | (df.net$receptor %in% features)\n df.net.sub <- df.net[idx & idx.feature, , drop = FALSE]\n } else {\n if (pattern == \"both\") {\n idx.feature <- (df.net$ligand %in% features) | (df.net$receptor %in% features)\n } else if (pattern == \"outgoing\") {\n idx.feature <- (df.net$ligand %in% features)\n } else if (pattern == \"incoming\"){\n idx.feature <- (df.net$receptor %in% features)\n }\n df.net.sub <- df.net[idx.feature, , drop = FALSE]\n }\n return(df.net.sub)\n}\n\n"], ["/CellChat/R/visualization.R", "#' ggplot theme in CellChat\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#' @importFrom ggplot2 theme_classic element_rect theme element_blank element_line element_text\nCellChat_theme_opts <- function() {\n theme(strip.background = element_rect(colour = \"white\", fill = \"white\")) +\n theme_classic() +\n theme(panel.border = element_blank()) +\n theme(axis.line.x = element_line(color = \"black\")) +\n theme(axis.line.y = element_line(color = \"black\")) +\n theme(panel.grid.minor.x = element_blank(), panel.grid.minor.y = element_blank()) +\n theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_blank()) +\n theme(panel.background = element_rect(fill = \"white\")) +\n theme(legend.key = element_blank()) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))\n}\n\n\n#' Generate ggplot2 colors\n#'\n#' @param n number of colors to generate\n#' @importFrom grDevices hcl\n#' @export\n#'\nggPalette <- function(n) {\n hues = seq(15, 375, length = n + 1)\n grDevices::hcl(h = hues, l = 65, c = 100)[1:n]\n}\n\n#' Generate colors from a customed color palette\n#'\n#' @param n number of colors\n#'\n#' @return A color palette for plotting\n#' @importFrom grDevices colorRampPalette\n#'\n#' @export\n#'\nscPalette <- function(n) {\n colorSpace <- c('#E41A1C','#377EB8','#4DAF4A','#984EA3','#F29403','#F781BF','#BC9DCC','#A65628','#54B0E4','#222F75','#1B9E77','#B2DF8A',\n '#E3BE00','#FB9A99','#E7298A','#910241','#00CDD1','#A6CEE3','#CE1261','#5E4FA2','#8CA77B','#00441B','#DEDC00','#DCF0B9','#8DD3C7','#999999')\n if (n <= length(colorSpace)) {\n colors <- colorSpace[1:n]\n } else {\n colors <- grDevices::colorRampPalette(colorSpace)(n)\n }\n return(colors)\n}\n\n#' Visualize the inferred cell-cell communication network\n#'\n#' Automatically save plots in the current working directory.\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param top the fraction of interactions to show (0 < top <= 1)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max.individual the maximum weight of edge when plotting the individual L-R netwrok; defualt = max(net)\n#' @param edge.weight.max.aggregate the maximum weight of edge when plotting the aggregated signaling pathway network\n#' @param edge.width.max The maximum edge width for visualization\n#' @param layout \"hierarchy\", \"circle\" or \"chord\"\n#' @param height height of plot\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param pt.title font size of the text\n#' @param title.space the space between the title and plot\n#' @param vertex.label.cex The label size of vertex in the network\n#' @param out.format the format of output figures: svg, png and pdf\n#'\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the network mediated by ligand-receptor using \"circle\" or \"chord\"\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x, text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`. NB: some parameters might be not supported\n#' @importFrom svglite svglite\n#' @importFrom grDevices dev.off pdf\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#'\nnetVisual <- function(object, signaling, signaling.name = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max.individual = NULL, edge.weight.max.aggregate = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, pt.title = 12, title.space = 6, vertex.label.cex = 0.8,from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n out.format = c(\"svg\",\"png\"),\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n if (is.null(edge.weight.max.individual)) {\n edge.weight.max.individual = max(prob)\n }\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.null(edge.weight.max.aggregate)) {\n edge.weight.max.aggregate = max(prob.sum)\n }\n\n if (layout == \"hierarchy\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_individual.svg\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_individual.png\"), width = 8, height = nRow*height, units = \"in\",res = 300)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name, \"_hierarchy_individual.pdf\"), width = 8, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_individual.pdf\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n\n\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_aggregate.svg\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_aggregate.png\"), width = 7, height = 1*height, units = \"in\",res = 300)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name, \"_hierarchy_aggregate.pdf\"), width = 7, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_aggregate.pdf\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n\n } else if (layout == \"circle\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"spatial\") {\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"chord\") {\n if (is.element(\"svg\", out.format)) {\n\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n }\n\n}\n\n\n#' Visualize the inferred signaling network of signaling pathways by aggregating all L-R pairs\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param layout \"hierarchy\", \"circle\", \"chord\" or \"spatial\"\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param pt.title font size of the text\n#' @param title.space the space between the title and plot\n#' @param vertex.label.cex The label size of vertex in the network\n#'\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x,text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`,`netVisual_spatial`. NB: some parameters might be not supported\n#' @importFrom grDevices recordPlot\n#'\n#' @return an object of class \"recordedplot\" or ggplot\n#' @export\n#'\n#'\nnetVisual_aggregate <- function(object, signaling, signaling.name = NULL, color.use = NULL, thresh = 0.05, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"),\n pt.title = 12, title.space = 6, vertex.label.cex = 0.8,\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20,\n ...) {\n layout <- match.arg(layout)\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n\n if (layout == \"hierarchy\") {\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.null(edge.weight.max)) {\n edge.weight.max = max(prob.sum)\n }\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n } else if (layout == \"circle\") {\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n gg <- netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n } else if (layout == \"spatial\") {\n prob.sum <- apply(prob, c(1,2), sum)\n if (vertex.weight == \"incoming\"){\n if (length(slot(object, \"netP\")$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n vertex.weight = object@netP$centr[[signaling]]$indeg\n } else if (vertex.weight == \"outgoing\"){\n if (length(slot(object, \"netP\")$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n vertex.weight = object@netP$centr[[signaling]]$outdeg\n }\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n\n } else if (layout == \"chord\") {\n prob.sum <- apply(prob, c(1,2), sum)\n gg <- netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y= legend.pos.y)\n }\n\n return(gg)\n\n}\n\n\n\n#' Visualize the inferred signaling network of individual L-R pairs\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param pairLR.use a char vector or a data frame consisting of one column named \"interaction_name\", defining the L-R pairs of interest\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector.\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex in the network\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param graphics.init whether do graphics initiation using par(...). If graphics.init=FALSE, USERS can use par() in a more fexible way\n#' @param layout \"hierarchy\", \"circle\" or \"chord\"\n#' @param height height of plot\n#' @param thresh threshold of the p-value for determining significant interaction\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n# #' @param vertex.size Deprecated. Use `vertex.weight`\n\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the figures using \"circle\" or \"chord\"\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x, text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`. NB: some parameters might be not supported\n#' @importFrom grDevices dev.off pdf\n#'\n#' @return an object of class \"recordedplot\"\n#' @export\n#'\n#'\nnetVisual_individual <- function(object, signaling, signaling.name = NULL, pairLR.use = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex = 0.8,\n weight.scale = TRUE, edge.weight.max = NULL, edge.width.max=8, graphics.init = TRUE,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, #from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n # if (!is.null(vertex.size)) {\n # warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n # }\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n if (!is.null(pairLR.use)) {\n if (is.data.frame(pairLR.use)) {\n pairLR.name <- intersect(pairLR.name, as.character(pairLR.use$interaction_name))\n } else {\n pairLR.name <- intersect(pairLR.name, as.character(pairLR.use))\n }\n\n if (length(pairLR.name) == 0) {\n stop(\"There is no significant communication for the input L-R pairs!\")\n }\n }\n\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n if (is.null(edge.weight.max)) {\n edge.weight.max = max(prob)\n }\n\n if (layout == \"hierarchy\") {\n if (graphics.init) {\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n }\n\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i,...)\n }\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n\n } else if (layout == \"circle\") {\n # par(mfrow=c(nRow,1))\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n gg[[i]] <- netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n } else if (layout == \"spatial\") {\n # par(mfrow=c(nRow,1))\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n gg[[i]] <- netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n } else if (layout == \"chord\") {\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n gg[[i]] <- netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y)\n }\n }\n return(gg)\n}\n\n\n\n#' Hierarchy plot of cell-cell communications sending to cell groups in vertex.receiver\n#'\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net a weighted matrix defining the signaling network\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether rescale the edge weights\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.dist the distance between labels and dot position\n#' @param space.v the space between different columns in the plot\n#' @param space.h the space between different rows in the plot\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param alpha.edge the transprency of edge\n#' @param label.edge whether label edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_\n#' @importFrom grDevices adjustcolor recordPlot\n#' @importFrom shape Arrows\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_hierarchy1 <- function(net, vertex.receiver, color.use = NULL, title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight=20, vertex.weight.max = NULL, vertex.size.max = NULL,\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6,\n label.dist = 2.8, space.v = 1.5, space.h = 1.6, shape= NULL, label.edge=FALSE,edge.curved=0, margin=0.2,\n vertex.label.cex=0.6,vertex.label.color= \"black\",arrow.width=1,arrow.size = 0.2,edge.label.color='black',edge.label.cex=0.5, vertex.size = NULL){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n cells.level <- rownames(net)\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n if (is.null(color.use)) {\n color.use <- scPalette(nrow(net))\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+6\n\n m <- length(vertex.receiver)\n net2 <- net\n reorder.row <- c(vertex.receiver, setdiff(1:nrow(net),vertex.receiver))\n net2 <- net2[reorder.row,vertex.receiver]\n # Expand out to symmetric (M+N)x(M+N) matrix\n m1 <- nrow(net2); n1 <- ncol(net2)\n net3 <- rbind(cbind(matrix(0, m1, m1), net2), matrix(0, n1, m1+n1))\n\n row.names(net3) <- c(row.names(net)[vertex.receiver], row.names(net)[setdiff(1:m1,vertex.receiver)], rep(\"\",m))\n colnames(net3) <- row.names(net3)\n color.use3 <- c(color.use[vertex.receiver], color.use[setdiff(1:m1,vertex.receiver)], rep(\"#FFFFFF\",length(vertex.receiver)))\n color.use3.frame <- c(color.use[vertex.receiver], color.use[setdiff(1:m1,vertex.receiver)], color.use[vertex.receiver])\n\n if (length(vertex.weight) != 1) {\n vertex.weight = c(vertex.weight[vertex.receiver], vertex.weight[setdiff(1:m1,vertex.receiver)],vertex.weight[vertex.receiver])\n }\n if (is.null(shape)) {\n shape <- c(rep(\"circle\",m), rep(\"circle\", m1-m), rep(\"circle\",m))\n }\n\n g <- graph_from_adjacency_matrix(net3, mode = \"directed\", weighted = T)\n edge.start <- ends(g, es=E(g), names=FALSE)\n coords <- matrix(NA, nrow(net3), 2)\n coords[1:m,1] <- 0; coords[(m+1):m1,1] <- space.h; coords[(m1+1):nrow(net3),1] <- space.h/2;\n coords[1:m,2] <- seq(space.v, 0, by = -space.v/(m-1)); coords[(m+1):m1,2] <- seq(space.v, 0, by = -space.v/(m1-m-1));coords[(m1+1):nrow(net3),2] <- seq(space.v, 0, by = -space.v/(n1-1));\n coords_scale<-coords\n\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use3[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use3.frame[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n E(g)$label<-E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n # E(g)$width<-0.3+edge.max.width/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n E(g)$width<- 0.3+E(g)$weight/edge.weight.max*edge.width.max\n }else{\n E(g)$width<-0.3+edge.width.max*E(g)$weight\n }\n\n E(g)$arrow.width<-arrow.width\n E(g)$arrow.size<-arrow.size\n E(g)$label.color<-edge.label.color\n E(g)$label.cex<-edge.label.cex\n E(g)$color<-adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n\n label.dist <- c(rep(space.h*label.dist,m), rep(space.h*label.dist, m1-m),rep(0, nrow(net3)-m1))\n label.locs <- c(rep(-pi, m), rep(0, m1-m),rep(-pi, nrow(net3)-m1))\n # text.pos <- cbind(c(-space.h/1.5, space.h/10, space.h/1.2), space.v-space.v/10)\n text.pos <- cbind(c(-space.h/1.5, space.h/22, space.h/1.5), space.v-space.v/7)\n igraph::add.vertex.shape(\"fcircle\", clip=igraph::igraph.shape.noclip,plot=mycircle, parameters=list(vertex.frame.color=1, vertex.frame.width=1))\n plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin,rescale=T,vertex.shape=\"fcircle\", vertex.frame.width = c(rep(1,m1), rep(2,nrow(net3)-m1)),\n vertex.label.degree=label.locs, vertex.label.dist=label.dist, vertex.label.family=\"Helvetica\")\n text(text.pos, c(\"Source\",\"Target\",\"Source\"), cex = 0.8, col = c(\"#c51b7d\",\"#c51b7d\",\"#2f6661\"))\n arrow.pos1 <- c(-space.h/1.5, space.v-space.v/4, space.h/100000, space.v-space.v/4)\n arrow.pos2 <- c(space.h/1.5, space.v-space.v/4, space.h/20, space.v-space.v/4)\n shape::Arrows(arrow.pos1[1], arrow.pos1[2], arrow.pos1[3], arrow.pos1[4], col = \"#c51b7d\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n shape::Arrows(arrow.pos2[1], arrow.pos2[2], arrow.pos2[3], arrow.pos2[4], col = \"#2f6661\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n if (!is.null(title.name)) {\n title.pos = c(space.h/8, space.v)\n text(title.pos[1],title.pos[2],paste0(title.name, \" signaling network\"), cex = 1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Hierarchy plot of cell-cell communication sending to cell groups not in vertex.receiver\n#'\n#' This function loads the significant interactions as a weighted matrix, and colors\n#' represent different types of cells as a structure. The width of edges represent the strength of the communication.\n#'\n#' @param net a weighted matrix defining the signaling network\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether rescale the edge weights\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.dist the distance between labels and dot position\n#' @param space.v the space between different columns in the plot\n#' @param space.h the space between different rows in the plot\n#' @param label.edge Whether or not shows the label of edges (number of connections between different cell types)\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_\n#' @importFrom grDevices adjustcolor recordPlot\n#' @importFrom shape Arrows\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_hierarchy2 <-function(net, vertex.receiver, color.use = NULL, title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight=20, vertex.weight.max = NULL, vertex.size.max = NULL,\n edge.weight.max = NULL, edge.width.max=8,alpha.edge = 0.6,\n label.dist = 2.8, space.v = 1.5, space.h = 1.6, shape= NULL, label.edge=FALSE,edge.curved=0, margin=0.2,\n vertex.label.cex=0.6,vertex.label.color= \"black\",arrow.width=1,arrow.size = 0.2,edge.label.color='black',edge.label.cex=0.5, vertex.size = NULL){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- levels(object@idents)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- levels(object@idents)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- levels(object@idents)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n\n if (is.null(color.use)) {\n color.use <- scPalette(nrow(net))\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+6\n\n m <- length(vertex.receiver)\n m0 <- nrow(net)-length(vertex.receiver)\n net2 <- net\n reorder.row <- c(setdiff(1:nrow(net),vertex.receiver), vertex.receiver)\n net2 <- net2[reorder.row,vertex.receiver]\n # Expand out to symmetric (M+N)x(M+N) matrix\n m1 <- nrow(net2); n1 <- ncol(net2)\n net3 <- rbind(cbind(matrix(0, m1, m1), net2), matrix(0, n1, m1+n1))\n row.names(net3) <- c(row.names(net)[setdiff(1:m1,vertex.receiver)],row.names(net)[vertex.receiver], rep(\"\",m))\n colnames(net3) <- row.names(net3)\n color.use3 <- c(color.use[setdiff(1:m1,vertex.receiver)],color.use[vertex.receiver], rep(\"#FFFFFF\",length(vertex.receiver)))\n color.use3.frame <- c(color.use[setdiff(1:m1,vertex.receiver)], color.use[vertex.receiver], color.use[vertex.receiver])\n\n\n if (length(vertex.weight) != 1) {\n vertex.weight = c(vertex.weight[setdiff(1:m1,vertex.receiver)], vertex.weight[vertex.receiver], vertex.weight[vertex.receiver])\n }\n if (is.null(shape)) {\n shape <- rep(\"circle\",nrow(net3))\n }\n\n g <- graph_from_adjacency_matrix(net3, mode = \"directed\", weighted = T)\n edge.start <- ends(g, es=igraph::E(g), names=FALSE)\n coords <- matrix(NA, nrow(net3), 2)\n coords[1:m0,1] <- 0; coords[(m0+1):m1,1] <- space.h; coords[(m1+1):nrow(net3),1] <- space.h/2;\n coords[1:m0,2] <- seq(space.v, 0, by = -space.v/(m0-1)); coords[(m0+1):m1,2] <- seq(space.v, 0, by = -space.v/(m1-m0-1));coords[(m1+1):nrow(net3),2] <- seq(space.v, 0, by = -space.v/(n1-1));\n coords_scale<-coords\n\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use3[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use3.frame[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n # E(g)$width<-0.3+edge.max.width/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n igraph::E(g)$color<-adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n\n label.dist <- c(rep(space.h*label.dist,m), rep(space.h*label.dist, m1-m),rep(0, nrow(net3)-m1))\n label.locs <- c(rep(-pi, m0), rep(0, m1-m0),rep(-pi, nrow(net3)-m1))\n #text.pos <- cbind(c(-space.h/1.5, space.h/10, space.h/1.2), space.v-space.v/10)\n text.pos <- cbind(c(-space.h/1.5, space.h/22, space.h/1.5), space.v-space.v/7)\n igraph::add.vertex.shape(\"fcircle\", clip=igraph::igraph.shape.noclip,plot=mycircle, parameters=list(vertex.frame.color=1, vertex.frame.width=1))\n plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin,rescale=T,vertex.shape=\"fcircle\", vertex.frame.width = c(rep(1,m1), rep(2,nrow(net3)-m1)),\n vertex.label.degree=label.locs, vertex.label.dist=label.dist, vertex.label.family=\"Helvetica\")\n text(text.pos, c(\"Source\",\"Target\",\"Source\"), cex = 0.8, col = c(\"#c51b7d\",\"#2f6661\",\"#2f6661\"))\n\n arrow.pos1 <- c(-space.h/1.5, space.v-space.v/4, space.h/100000, space.v-space.v/4)\n arrow.pos2 <- c(space.h/1.5, space.v-space.v/4, space.h/20, space.v-space.v/4)\n shape::Arrows(arrow.pos1[1], arrow.pos1[2], arrow.pos1[3], arrow.pos1[4], col = \"#c51b7d\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n shape::Arrows(arrow.pos2[1], arrow.pos2[2], arrow.pos2[3], arrow.pos2[4], col = \"#2f6661\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n\n if (!is.null(title.name)) {\n title.pos = c(space.h/8, space.v)\n text(title.pos[1],title.pos[2],paste0(title.name, \" signaling network\"), cex = 1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Circle plot of cell-cell communication network\n#'\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net A weighted matrix representing the connections\n#' @param color.use Colors represent different cell groups\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.edge Whether or not shows the label of edges\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param layout The layout specification. It must be a call to a layout\n#' specification function.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param text.x,text.y the x- and y-coordinates to add the text\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_ in_circle\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_circle <-function(net, color.use = NULL,title.name = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex=1,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6, label.edge = FALSE,edge.label.color='black',edge.label.cex=0.8,\n edge.curved=0.2,shape='circle',layout=in_circle(), margin=0.2, vertex.size = NULL,\n arrow.width=1,arrow.size = 0.2,\n text.x = 0, text.y = 1.5){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use)) | (!is.null(idents.use)) ) {\n if (is.null(rownames(net))) {\n stop(\"The input weighted matrix should have rownames!\")\n }\n cells.level <- rownames(net)\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n df.net <- filter(df.net, (source %in% idents.use) | (target %in% idents.use))\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (is.null(color.use)) {\n color.use = scPalette(nrow(net))\n names(color.use) <- rownames(net)\n } else {\n if (is.null(names(color.use))) {\n stop(\"The input `color.use` should be a named vector! \\n\")\n }\n }\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx.isolate <- intersect(idx1, idx2)\n if (length(idx.isolate) > 0) {\n net <- net[-idx.isolate, ]\n net <- net[, -idx.isolate]\n color.use = color.use[-idx.isolate]\n if (length(unique(vertex.weight)) > 1) {\n vertex.weight <- vertex.weight[-idx.isolate]\n }\n }\n }\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edge.start <- igraph::ends(g, es=igraph::E(g), names=FALSE)\n coords<-layout_(g,layout)\n if(nrow(coords)!=1){\n coords_scale=scale(coords)\n }else{\n coords_scale<-coords\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n\n loop.angle<-ifelse(coords_scale[igraph::V(g),1]>0,-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]),pi-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]))\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n #E(g)$width<-0.3+edge.width.max/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n igraph::E(g)$color<- grDevices::adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n igraph::E(g)$loop.angle <- rep(0, length(igraph::E(g)))\n\n if(sum(edge.start[,2]==edge.start[,1])!=0){\n igraph::E(g)$loop.angle[which(edge.start[,2]==edge.start[,1])]<-loop.angle[edge.start[which(edge.start[,2]==edge.start[,1]),1]]\n }\n radian.rescale <- function(x, start=0, direction=1) {\n c.rotate <- function(x) (x + start) %% (2 * pi) * direction\n c.rotate(scales::rescale(x, c(0, 2 * pi), range(x)))\n }\n label.locs <- radian.rescale(x=1:length(igraph::V(g)), direction=-1, start=0)\n label.dist <- vertex.weight/max(vertex.weight)+2\n plot(g,edge.curved=edge.curved,vertex.shape=shape,layout=coords_scale,margin=margin, vertex.label.dist=label.dist,\n vertex.label.degree=label.locs, vertex.label.family=\"Helvetica\", edge.label.family=\"Helvetica\") # \"sans\"\n if (!is.null(title.name)) {\n text(text.x,text.y,title.name, cex = 1.1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n\n#' generate circle symbol\n#'\n#' @param coords coordinates of points\n#' @param v vetex\n#' @param params parameters\n#' @importFrom graphics symbols\n#' @return\nmycircle <- function(coords, v=NULL, params) {\n vertex.color <- params(\"vertex\", \"color\")\n if (length(vertex.color) != 1 && !is.null(v)) {\n vertex.color <- vertex.color[v]\n }\n vertex.size <- 1/200 * params(\"vertex\", \"size\")\n if (length(vertex.size) != 1 && !is.null(v)) {\n vertex.size <- vertex.size[v]\n }\n vertex.frame.color <- params(\"vertex\", \"frame.color\")\n if (length(vertex.frame.color) != 1 && !is.null(v)) {\n vertex.frame.color <- vertex.frame.color[v]\n }\n vertex.frame.width <- params(\"vertex\", \"frame.width\")\n if (length(vertex.frame.width) != 1 && !is.null(v)) {\n vertex.frame.width <- vertex.frame.width[v]\n }\n\n mapply(coords[,1], coords[,2], vertex.color, vertex.frame.color,\n vertex.size, vertex.frame.width,\n FUN=function(x, y, bg, fg, size, lwd) {\n symbols(x=x, y=y, bg=bg, fg=fg, lwd=lwd,\n circles=size, add=TRUE, inches=FALSE)\n })\n}\n\n\n#' Spatial plot of cell-cell communication network\n#'\n#' Autocrine interactions are omitted on this plot. Group centroids may be not accurate for some data due to complex geometry.\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net A weighted matrix representing the connections\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param meta a data frame with at least two columns named `labels` and `samples`.\n#' `meta$labels` is a vector giving the group label of each cell/spot. `meta$samples` is a factor vector defining the sample labels of each dataset. The length should be the same as the number of rows in `coordinates`.\n#' @param sample.use the sample used for visualization, which should be the element in `meta$samples`.\n#' @param color.use Colors represent different cell groups\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param remove.loop whether remove the self-loop in the communication network. Default: TRUE\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param alpha.edge the transprency of edge\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param arrow.angle The width of arrows\n#' @param alpha.image the transparency of individual spots\n# #' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param point.size the size of spots\n#' @param legend.size the size of legend\n#' @importFrom igraph graph_from_adjacency_matrix get.edgelist ends E V\n#' @import ggplot2\n#' @importFrom ggnetwork geom_nodetext_repel\n#' @return an object of ggplot\n#' @export\nnetVisual_spatial <-function(net, coordinates, meta, sample.use = NULL, color.use = NULL,title.name = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE, remove.loop = TRUE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex = 5,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, edge.curved=0.2, alpha.edge = 0.6, arrow.angle = 5, arrow.size = 0.2, alpha.image = 0.15, point.size = 1.5, legend.size = 5){\n cells.level <- rownames(net)\n labels <- meta$labels\n samples <- meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n num_cluster <- length(cells.level)\n node_coords <- matrix(0, nrow = num_cluster, ncol = 2)\n for (i in c(1:num_cluster)) {\n node_coords[i,1] <- median(coordinates[as.character(labels) == cells.level[i], 1])\n node_coords[i,2] <- median(coordinates[as.character(labels) == cells.level[i], 2])\n }\n rownames(node_coords) <- cells.level\n\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use)) | (!is.null(idents.use)) ) {\n if (is.null(rownames(net))) {\n stop(\"The input weighted matrix should have rownames!\")\n }\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n df.net <- filter(df.net, (source %in% idents.use) | (target %in% idents.use))\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n\n if (remove.loop) {\n diag(net) <- 0\n }\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n node_coords <- node_coords[-idx, ]\n cells.level <- cells.level[-idx]\n }\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edgelist <- get.edgelist(g)\n # loop_curve = c()\n # for (i in c(1:nrow(edgelist))) {\n # if (edgelist[i,1] == edgelist[i,2]){\n # loop_curve = c(loop_curve ,i)\n # }\n # }\n # edgelist <- edgelist[-loop_curve,]\n\n edges <- data.frame(node_coords[edgelist[,1],,drop =FALSE], node_coords[edgelist[,2],,drop =FALSE])\n colnames(edges) <- c(\"X1\",\"Y1\",\"X2\",\"Y2\")\n node_coords = data.frame(node_coords)\n node_idents = factor(cells.level, levels = cells.level)\n node_family = data.frame(node_coords,node_idents)\n if (is.null(color.use)) {\n color.use = scPalette(length(igraph::V(g)))\n names(color.use) <- cells.level\n }\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n # width of edge\n if (weight.scale == TRUE) {\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n gg <- ggplot(data=node_family,aes(X1, X2)) +\n geom_curve(aes(x=X1, y=Y1, xend = X2, yend = Y2), data=edges, size = igraph::E(g)$width, curvature = edge.curved, alpha = alpha.edge, arrow = arrow(angle = arrow.angle, type = \"closed\",length = unit(arrow.size, \"inches\")),colour=color.use[edgelist[,1]]) +\n geom_point(aes(X1, X2,colour = node_idents), data=node_family, size = vertex.weight,show.legend = TRUE) +scale_color_manual(values = color.use) +\n guides(color = guide_legend(override.aes = list(size=legend.size))) +\n xlab(NULL) + ylab(NULL) +\n coord_fixed() + theme(aspect.ratio = 1)+ theme(legend.key = element_blank()) +\n theme(panel.background = element_blank(),axis.ticks = element_blank(), panel.border = element_blank(),axis.text=element_blank(),legend.title = element_blank())\n\n gg <- gg + geom_point(aes(x_cent, y_cent), data = coordinates,colour = color.use[labels],alpha = alpha.image, size = point.size, show.legend = FALSE)\n gg <- gg + scale_y_reverse()\n if (vertex.label.cex > 0){\n gg <- gg + ggnetwork::geom_nodetext_repel(aes(label = node_idents), color=\"black\", size = vertex.label.cex)\n }\n if (!is.null(title.name)){\n gg <- gg + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0))\n }\n\n gg\n return(gg)\n\n}\n\n\n\n\n\n\n#' Circle plot showing differential cell-cell communication network between two datasets\n#'\n#' The width of edges represent the relative number of interactions or interaction strength.\n#' Red (or blue) colored edges represent increased (or decreased) signaling in the second dataset compared to the first one.\n#'\n#' @param object A merged CellChat objects\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param color.use Colors represent different cell groups\n#' @param color.edge Colors for indicating whether the signaling is increased (`color.edge[1]`) or decreased (`color.edge[2]`)\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.edge Whether or not shows the label of edges\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param layout The layout specification. It must be a call to a layout\n#' specification function.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n# #' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_ in_circle\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_diffInteraction <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\", \"count.merged\", \"weight.merged\"), color.use = NULL, color.edge = c('#b2182b','#2166ac'), title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = 15, vertex.label.cex=1,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6, label.edge = FALSE,edge.label.color='black',edge.label.cex=0.8,\n edge.curved=0.2,shape='circle',layout=in_circle(), margin=0.2,\n arrow.width=1,arrow.size = 0.2){\n options(warn = -1)\n measure <- match.arg(measure)\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n if (measure %in% c(\"count\", \"count.merged\")) {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure %in% c(\"weight\", \"weight.merged\")) {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n net <- net.diff\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- rownames(net.diff)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n net[is.na(net)] <- 0\n }\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n net[abs(net) < stats::quantile(abs(net), probs = 1-top, na.rm= T)] <- 0\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edge.start <- igraph::ends(g, es=igraph::E(g), names=FALSE)\n coords<-layout_(g,layout)\n if(nrow(coords)!=1){\n coords_scale=scale(coords)\n }else{\n coords_scale<-coords\n }\n if (is.null(color.use)) {\n color.use = scPalette(length(igraph::V(g)))\n }\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n\n loop.angle<-ifelse(coords_scale[igraph::V(g),1]>0,-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]),pi-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]))\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n #igraph::E(g)$color<- grDevices::adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n igraph::E(g)$color <- ifelse(igraph::E(g)$weight > 0, color.edge[1],color.edge[2])\n igraph::E(g)$color <- grDevices::adjustcolor(igraph::E(g)$color, alpha.edge)\n\n igraph::E(g)$weight <- abs(igraph::E(g)$weight)\n\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n #E(g)$width<-0.3+edge.width.max/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n igraph::E(g)$loop.angle <- 0\n if(sum(edge.start[,2]==edge.start[,1])!=0){\n igraph::E(g)$loop.angle[which(edge.start[,2]==edge.start[,1])]<-loop.angle[edge.start[which(edge.start[,2]==edge.start[,1]),1]]\n }\n radian.rescale <- function(x, start=0, direction=1) {\n c.rotate <- function(x) (x + start) %% (2 * pi) * direction\n c.rotate(scales::rescale(x, c(0, 2 * pi), range(x)))\n }\n label.locs <- radian.rescale(x=1:length(igraph::V(g)), direction=-1, start=0)\n label.dist <- vertex.weight/max(vertex.weight)+2\n plot(g,edge.curved=edge.curved,vertex.shape=shape,layout=coords_scale,margin=margin, vertex.label.dist=label.dist,\n vertex.label.degree=label.locs, vertex.label.family=\"Helvetica\", edge.label.family=\"Helvetica\") # \"sans\"\n if (!is.null(title.name)) {\n text(0,1.5,title.name, cex = 1.1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Visualization of network using heatmap\n#'\n#' This heatmap can be used to 1) show differential number of interactions or interaction strength in the cell-cell communication network between two datasets;\n#' 2) the number of interactions or interaction strength in a single dataset;\n#' 3) the inferred cell-cell communication network in a single dataset, defined by `signaling`. Please see @Details below for detailed explanations of this heatmap plot.\n#'\n#' When show differential number of interactions or interaction strength in the cell-cell communication network between two datasets, the width of edges represent the relative number of interactions or interaction strength.\n#' Red (or blue) colored edges represent increased (or decreased) signaling in the second dataset compared to the first one.\n#'\n#' The top colored bar plot represents the sum of absolute values displayed in each column of the heatmap. The right colored bar plot represents the sum of absolute values in each row.\n#'\n#'\n#' @param object A merged CellChat object or a single CellChat object\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param signaling a character vector giving the name of signaling networks in a single CellChat object\n#' @param slot.name the slot name of object. Set is to be \"netP\" if input signaling is a pathway name; Set is to be \"net\" if input signaling is a ligand-receptor pair\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap A vector of two colors corresponding to max/min values, or a color name in brewer.pal only when the data in the heatmap do not contain negative values.\n#' By default, color.heatmap = c('#2166ac','#b2182b') when taking a merged CellChat object as input; color.heatmap = \"Reds\" when taking a single CellChat object as input.\n#' @param title.name the name of the title\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param row.show,col.show a vector giving the index or the name of row or columns to show in the heatmap\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation anno_barplot rowAnnotation\n#' @return an object of ComplexHeatmap\n#' @export\nnetVisual_heatmap <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\"), signaling = NULL, slot.name = c(\"netP\", \"net\"), color.use = NULL, color.heatmap = NULL,\n title.name = NULL, width = NULL, height = NULL, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE,\n sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, row.show = NULL, col.show = NULL){\n if (!is.null(measure)) {\n measure <- match.arg(measure)\n }\n slot.name <- match.arg(slot.name)\n if (class(object@net[[1]]) == \"list\") {\n message(\"Do heatmap based on a merged object \\n\")\n if (is.null(color.heatmap)) {\n color.heatmap <- c('#2166ac','#b2182b')\n }\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n legend.name = \"Relative values\"\n } else {\n message(\"Do heatmap based on a single object \\n\")\n if (is.null(color.heatmap)) {\n color.heatmap <- \"Reds\"\n }\n if (!is.null(signaling)) {\n prob <- slot(object, slot.name)$prob\n if (slot.name == \"net\") {\n prob[object@net$pval > thresh] <- 0\n }\n net.diff <- prob[,,signaling]\n if (is.null(title.name)) {\n title.name = paste0(signaling, \" signaling network\")\n }\n legend.name <- \"Communication Prob.\"\n } else if (!is.null(measure)) {\n net.diff <- object@net[[measure]]\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Interaction strength\"\n }\n }\n legend.name <- title.name\n }\n }\n\n net <- net.diff\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- rownames(net.diff)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (is.null(color.use)) {\n color.use <- scPalette(ncol(net))\n }\n names(color.use) <- colnames(net)\n color.use.row <- color.use\n color.use.col <- color.use\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n #idx <- intersect(idx1, idx2)\n # if (length(idx) > 0) {\n # net <- net[-idx, ]\n # net <- net[, -idx]\n # }\n if (length(idx1) > 0) {\n net <- net[-idx1, ]\n color.use.row <- color.use.row[-idx1]\n }\n if (length(idx2) > 0) {\n net <- net[, -idx2]\n color.use.col <- color.use.col[-idx2]\n }\n }\n\n mat <- net\n if (!is.null(row.show)) {\n mat <- mat[row.show, , drop=FALSE]\n color.use.row <- color.use.row[row.show]\n }\n if (!is.null(col.show)) {\n mat <- mat[ ,col.show, drop=FALSE]\n color.use.col <- color.use.col[col.show]\n }\n\n\n if (min(mat) < 0) {\n color.heatmap.use = colorRamp3(c(min(mat), 0, max(mat)), c(color.heatmap[1], \"#f7f7f7\", color.heatmap[2]))\n colorbar.break <- c(round(min(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",min(mat, na.rm = T)))+1), 0, round(max(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",max(mat, na.rm = T)))+1))\n # color.heatmap.use = colorRamp3(c(seq(min(mat), -(max(mat)-min(max(mat)))/9, length.out = 4), 0, seq((max(mat)-min(max(mat)))/9, max(mat), length.out = 4)), RColorBrewer::brewer.pal(n = 9, name = color.heatmap))\n } else {\n if (length(color.heatmap) == 3) {\n color.heatmap.use = colorRamp3(c(0, min(mat), max(mat)), color.heatmap)\n } else if (length(color.heatmap) == 2) {\n color.heatmap.use = colorRamp3(c(min(mat), max(mat)), color.heatmap)\n } else if (length(color.heatmap) == 1) {\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n }\n colorbar.break <- c(round(min(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",min(mat, na.rm = T)))+1), round(max(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",max(mat, na.rm = T)))+1))\n }\n # col_fun(as.vector(mat))\n\n df.col<- data.frame(group = colnames(mat)); rownames(df.col) <- colnames(mat)\n df.row<- data.frame(group = rownames(mat)); rownames(df.row) <- rownames(mat)\n col_annotation <- HeatmapAnnotation(df = df.col, col = list(group = color.use.col),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n row_annotation <- HeatmapAnnotation(df = df.row, col = list(group = color.use.row), which = \"row\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ha1 = rowAnnotation(Strength = anno_barplot(rowSums(abs(mat)), border = FALSE,gp = gpar(fill = color.use.row, col=color.use.row)), show_annotation_name = FALSE)\n ha2 = HeatmapAnnotation(Strength = anno_barplot(colSums(abs(mat)), border = FALSE,gp = gpar(fill = color.use.col, col=color.use.col)), show_annotation_name = FALSE)\n\n if (sum(abs(mat) > 0) == 1) {\n color.heatmap.use = c(\"white\", color.heatmap.use)\n } else {\n mat[mat == 0] <- NA\n }\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = legend.name,\n bottom_annotation = col_annotation, left_annotation =row_annotation, top_annotation = ha2, right_annotation = ha1,\n cluster_rows = cluster.rows,cluster_columns = cluster.rows,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n # width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = title.name,column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 90,\n row_title = \"Sources (Sender)\",row_title_gp = gpar(fontsize = font.size.title),row_title_rot = 90,\n heatmap_legend_param = list(title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, #at = colorbar.break,\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n # draw(ht1)\n return(ht1)\n}\n\n\n#' Visualization of (differential) number of interactions\n#'\n#' @param object A merged CellChat object or a single CellChat object\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param invert.source,invert.target retain the complementary set\n#' @param signaling a character vector giving the name of signaling networks in a single CellChat object\n#' @param slot.name the slot name of object. Set is to be \"netP\" if input signaling is a pathway name; Set is to be \"net\" if input signaling is a ligand-receptor pair\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name the name of the title\n#' @param x.lab.rot do rotation for the x-ticklabels\n#' @param ... Parameters passing to `barplot_internal`\n#' @importFrom methods slot\n#' @return an object of ggplot\n#' @export\nnetVisual_barplot <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\"), sources.use = NULL, targets.use = NULL, invert.source = FALSE, invert.target = FALSE,signaling = NULL, slot.name = c(\"netP\", \"net\"), color.use = NULL,\n title.name = NULL,x.lab.rot = FALSE,...){\n if (!is.null(measure)) {\n measure <- match.arg(measure)\n }\n slot.name <- match.arg(slot.name)\n if (is.list(object@net[[1]])) {\n message(\"Show differential number of interactions based on a merged object \\n\")\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n } else {\n message(\"Show number of interactions based on a single object \\n\")\n if (!is.null(signaling)) {\n net.diff <- slot(object, slot.name)$prob[,,signaling]\n if (is.null(title.name)) {\n title.name = paste0(signaling, \" signaling network\")\n }\n } else if (!is.null(measure)) {\n net.diff <- object@net[[measure]]\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Interaction strength\"\n }\n }\n }\n }\n\n net <- net.diff\n cells.level <- rownames(net.diff)\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n if (invert.source == TRUE) {\n sources.use <- setdiff(rownames(net.diff), sources.use)\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n if (invert.target == TRUE) {\n targets.use <- setdiff(rownames(net.diff), targets.use)\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n }\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(cells.level))\n }\n names(color.use) <- cells.level\n color.use <- color.use[cells.level %in% unique(df.net$target)]\n\n gg <- barplot_internal(df.net, x = \"target\", y = \"value\", fill = \"target\", color.use = color.use, title.name = title.name,x.lab.rot = x.lab.rot,...)\n\n return(gg)\n\n}\n\n\n#' Show all the significant interactions (L-R pairs) from some cell groups to other cell groups\n#'\n#' The dot color and size represent the calculated communication probability and p-values.\n#'\n#' @param object CellChat object\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest and the order of L-R on y-axis\n#' @param sort.by.source,sort.by.target,sort.by.source.priority set the order of interacting cell pairs on x-axis; please check examples for details\n#' @param color.heatmap A character string or vector indicating the colormap option to use. It can be the avaibale color palette in viridis_pal() or brewer.pal()\n#' @param direction Sets the order of colors in the scale. If 1, the default colors are used. If -1, the order of colors is reversed.\n#' @param n.colors number of basic colors to generate from color palette\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param comparison a numerical vector giving the datasets for comparison in the merged object; e.g., comparison = c(1,2)\n#' @param group a numerical vector giving the group information of different datasets; e.g., group = c(1,2,2)\n#' @param remove.isolate whether to remove the entire empty columns, i.e., communication between certain cell groups\n#' @param max.dataset a scale, keeping the communications with highest probability in max.dataset (i.e., certrain condition)\n#' @param min.dataset a scale, keeping the communications with lowest probability in min.dataset (i.e., certrain condition)\n#' @param min.quantile,max.quantile minimum and maximum quantile cutoff values for the colorbar, may specify quantile in [0,1]\n#' @param line.on whether to add vertical line when doing comparison analysis for the merged object\n#' @param line.size size of vertical line if added\n#' @param color.text.use whether to color the xtick labels according to the dataset origin when doing comparison analysis\n#' @param color.text the colors for xtick labels according to the dataset origin when doing comparison analysis\n#' @param dot.size.min,dot.size.max Size of smallest and largest points\n#' @param title.name main title of the plot\n#' @param font.size,font.size.title font size of all the text and the title name\n#' @param show.legend whether to show legend\n#' @param grid.on,color.grid whether to add grid\n#' @param angle.x,vjust.x,hjust.x parameters for adjusting the rotation of xtick labels\n#' @param return.data whether to return the data.frame for replotting\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # show all the significant interactions (L-R pairs) from some cell groups (defined by 'sources.use') to other cell groups (defined by 'targets.use')\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), remove.isolate = FALSE)\n#'\n#' # show all the significant interactions (L-R pairs) associated with certain signaling pathways\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), signaling = c(\"CCL\",\"CXCL\"))\n#'\n#' # show all the significant interactions (L-R pairs) based on user's input (defined by `pairLR.use`; the order of L-R is also based on user's input)\n#' pairLR.use <- extractEnrichedLR(cellchat, signaling = c(\"CCL\",\"CXCL\",\"FGF\"))\n#' netVisual_bubble(cellchat, sources.use = c(3,4), targets.use = c(5:8), pairLR.use = pairLR.use, remove.isolate = TRUE)\n#'\n#' # set the order of interacting cell pairs on x-axis\n#' # (1) Default: first sort cell pairs based on the appearance of sources in levels(object@idents), and then based on the appearance of targets in levels(object@idents)\n#' # (2) sort cell pairs based on the targets.use defined by users\n#' netVisual_bubble(cellchat, targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.target = T)\n#' # (3) sort cell pairs based on the sources.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T)\n#' # (4) sort cell pairs based on the sources.use and then targets.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T, sort.by.target = T)\n#' # (5) sort cell pairs based on the targets.use and then sources.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T, sort.by.target = T, sort.by.source.priority = FALSE)\n#'\n#'# show all the increased interactions in the second dataset compared to the first dataset\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:8), remove.isolate = TRUE, max.dataset = 2)\n#'\n#'# show all the decreased interactions in the second dataset compared to the first dataset\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:8), remove.isolate = TRUE, max.dataset = 1)\n#'}\nnetVisual_bubble <- function(object, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR.use = NULL, sort.by.source = FALSE, sort.by.target = FALSE, sort.by.source.priority = TRUE, color.heatmap = c(\"Spectral\",\"viridis\"), n.colors = 10, direction = -1, thresh = 0.05,\n comparison = NULL, group = NULL, remove.isolate = FALSE, max.dataset = NULL, min.dataset = NULL,\n min.quantile = 0, max.quantile = 1, line.on = TRUE, line.size = 0.2, color.text.use = TRUE, color.text = NULL, dot.size.min = NULL, dot.size.max = NULL,\n title.name = NULL, font.size = 10, font.size.title = 10, show.legend = TRUE,\n grid.on = TRUE, color.grid = \"grey90\", angle.x = 90, vjust.x = NULL, hjust.x = NULL,\n return.data = FALSE){\n color.heatmap <- match.arg(color.heatmap)\n if (is.list(object@net[[1]])) {\n message(\"Comparing communications on a merged object \\n\")\n } else {\n message(\"Comparing communications on a single object \\n\")\n }\n if (is.null(vjust.x) | is.null(hjust.x)) {\n angle=c(0, 45, 90)\n hjust=c(0, 1, 1)\n vjust=c(0, 1, 0.5)\n vjust.x = vjust[angle == angle.x]\n hjust.x = hjust[angle == angle.x]\n }\n if (length(color.heatmap) == 1) {\n color.use <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n scales::viridis_pal(option = color.heatmap, direction = -1)(n.colors)\n })\n } else {\n color.use <- color.heatmap\n }\n if (direction == -1) {\n color.use <- rev(color.use)\n }\n\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n pairLR.use$pathway_name <- as.character(pairLR.use$pathway_name)\n } else if (\"interaction_name\" %in% colnames(pairLR.use)) {\n pairLR.use$interaction_name <- as.character(pairLR.use$interaction_name)\n }\n }\n\n if (is.null(comparison)) {\n cells.level <- levels(object@idents)\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.net$source.target <- paste(df.net$source, df.net$target, sep = \" -> \")\n source.target <- paste(rep(sources.use, each = length(targets.use)), targets.use, sep = \" -> \")\n source.target.isolate <- setdiff(source.target, unique(df.net$source.target))\n if (length(source.target.isolate) > 0) {\n df.net.isolate <- as.data.frame(matrix(NA, nrow = length(source.target.isolate), ncol = ncol(df.net)))\n colnames(df.net.isolate) <- colnames(df.net)\n df.net.isolate$source.target <- source.target.isolate\n df.net.isolate$interaction_name_2 <- df.net$interaction_name_2[1]\n df.net.isolate$pval <- 1\n a <- stringr::str_split(df.net.isolate$source.target, \" -> \", simplify = T)\n df.net.isolate$source <- as.character(a[, 1])\n df.net.isolate$target <- as.character(a[, 2])\n df.net <- rbind(df.net, df.net.isolate)\n }\n\n df.net$pval[df.net$pval > 0.05] = 1\n df.net$pval[df.net$pval > 0.01 & df.net$pval <= 0.05] = 2\n df.net$pval[df.net$pval <= 0.01] = 3\n df.net$prob[df.net$prob == 0] <- NA\n df.net$prob.original <- df.net$prob\n df.net$prob <- -1/log(df.net$prob)\n\n idx1 <- which(is.infinite(df.net$prob) | df.net$prob < 0)\n if (sum(idx1) > 0) {\n values.assign <- seq(max(df.net$prob, na.rm = T)*1.1, max(df.net$prob, na.rm = T)*1.5, length.out = length(idx1))\n position <- sort(prob.original[idx1], index.return = TRUE)$ix\n df.net$prob[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n # rownames(df.net) <- df.net$interaction_name_2\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n group.names <- paste(rep(levels(df.net$source), each = length(levels(df.net$target))), levels(df.net$target), sep = \" -> \")\n\n df.net$interaction_name_2 <- as.character(df.net$interaction_name_2)\n df.net <- with(df.net, df.net[order(interaction_name_2),])\n df.net$interaction_name_2 <- factor(df.net$interaction_name_2, levels = unique(df.net$interaction_name_2))\n cells.order <- group.names\n df.net$source.target <- factor(df.net$source.target, levels = cells.order)\n df <- df.net\n } else {\n dataset.name <- names(object@net)\n df.net.all <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.all <- data.frame()\n for (ii in 1:length(comparison)) {\n cells.level <- levels(object@idents[[comparison[ii]]])\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n\n df.net <- df.net.all[[comparison[ii]]]\n df.net$interaction_name_2 <- as.character(df.net$interaction_name_2)\n df.net$source.target <- paste(df.net$source, df.net$target, sep = \" -> \")\n source.target <- paste(rep(sources.use, each = length(targets.use)), targets.use, sep = \" -> \")\n source.target.isolate <- setdiff(source.target, unique(df.net$source.target))\n if (length(source.target.isolate) > 0) {\n df.net.isolate <- as.data.frame(matrix(NA, nrow = length(source.target.isolate), ncol = ncol(df.net)))\n colnames(df.net.isolate) <- colnames(df.net)\n df.net.isolate$source.target <- source.target.isolate\n df.net.isolate$interaction_name_2 <- df.net$interaction_name_2[1]\n df.net.isolate$pval <- 1\n a <- stringr::str_split(df.net.isolate$source.target, \" -> \", simplify = T)\n df.net.isolate$source <- as.character(a[, 1])\n df.net.isolate$target <- as.character(a[, 2])\n df.net <- rbind(df.net, df.net.isolate)\n }\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n group.names <- paste(rep(levels(df.net$source), each = length(levels(df.net$target))), levels(df.net$target), sep = \" -> \")\n group.names0 <- group.names\n group.names <- paste0(group.names0, \" (\", dataset.name[comparison[ii]], \")\")\n\n if (nrow(df.net) > 0) {\n df.net$pval[df.net$pval > 0.05] = 1\n df.net$pval[df.net$pval > 0.01 & df.net$pval <= 0.05] = 2\n df.net$pval[df.net$pval <= 0.01] = 3\n df.net$prob[df.net$prob == 0] <- NA\n df.net$prob.original <- df.net$prob\n df.net$prob <- -1/log(df.net$prob)\n } else {\n df.net <- as.data.frame(matrix(NA, nrow = length(group.names), ncol = 5))\n colnames(df.net) <- c(\"interaction_name_2\",\"source.target\",\"prob\",\"pval\",\"prob.original\")\n df.net$source.target <- group.names0\n }\n # df.net$group.names <- sub(paste0(' \\\\(',dataset.name[comparison[ii]],'\\\\)'),'',as.character(df.net$source.target))\n df.net$group.names <- as.character(df.net$source.target)\n df.net$source.target <- paste0(df.net$source.target, \" (\", dataset.name[comparison[ii]], \")\")\n df.net$dataset <- dataset.name[comparison[ii]]\n df.all <- rbind(df.all, df.net)\n }\n if (nrow(df.all) == 0) {\n stop(\"No interactions are detected. Please consider changing the cell groups for analysis. \")\n }\n\n idx1 <- which(is.infinite(df.all$prob) | df.all$prob < 0)\n if (sum(idx1) > 0) {\n values.assign <- seq(max(df.all$prob, na.rm = T)*1.1, max(df.all$prob, na.rm = T)*1.5, length.out = length(idx1))\n position <- sort(df.all$prob.original[idx1], index.return = TRUE)$ix\n df.all$prob[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n\n df.all$interaction_name_2[is.na(df.all$interaction_name_2)] <- df.all$interaction_name_2[!is.na(df.all$interaction_name_2)][1]\n\n df <- df.all\n df <- with(df, df[order(interaction_name_2),])\n df$interaction_name_2 <- factor(df$interaction_name_2, levels = unique(df$interaction_name_2))\n\n cells.order <- c()\n dataset.name.order <- c()\n for (i in 1:length(group.names0)) {\n for (j in 1:length(comparison)) {\n cells.order <- c(cells.order, paste0(group.names0[i], \" (\", dataset.name[comparison[j]], \")\"))\n dataset.name.order <- c(dataset.name.order, dataset.name[comparison[j]])\n }\n }\n df$source.target <- factor(df$source.target, levels = cells.order)\n }\n\n min.cutoff <- quantile(df$prob, min.quantile,na.rm= T)\n max.cutoff <- quantile(df$prob, max.quantile,na.rm= T)\n df$prob[df$prob < min.cutoff] <- min.cutoff\n df$prob[df$prob > max.cutoff] <- max.cutoff\n\n\n if (remove.isolate) {\n df <- df[!is.na(df$prob), ]\n line.on <- FALSE\n }\n if (!is.null(max.dataset)) {\n # line.on <- FALSE\n # df <- df[!is.na(df$prob),]\n signaling <- as.character(unique(df$interaction_name_2))\n for (i in signaling) {\n df.i <- df[df$interaction_name_2 == i, ,drop = FALSE]\n cell <- as.character(unique(df.i$group.names))\n for (j in cell) {\n df.i.j <- df.i[df.i$group.names == j, , drop = FALSE]\n values <- df.i.j$prob\n idx.max <- which(values == max(values, na.rm = T))\n idx.min <- which(values == min(values, na.rm = T))\n #idx.na <- c(which(is.na(values)), which(!(dataset.name[comparison] %in% df.i.j$dataset)))\n dataset.na <- c(df.i.j$dataset[is.na(values)], setdiff(dataset.name[comparison], df.i.j$dataset))\n if (length(idx.max) > 0) {\n if (all(!(df.i.j$dataset[idx.max] %in% dataset.name[max.dataset]))) {\n df.i.j$prob <- NA\n } else if (all((idx.max != idx.min) & !is.null(min.dataset))) {\n if (all(!(df.i.j$dataset[idx.min] %in% dataset.name[min.dataset]))) {\n df.i.j$prob <- NA\n } else if (length(dataset.na) > 0 & sum(!(dataset.name[min.dataset] %in% dataset.na)) > 0) {\n df.i.j$prob <- NA\n }\n }\n }\n df.i[df.i$group.names == j, \"prob\"] <- df.i.j$prob\n }\n df[df$interaction_name_2 == i, \"prob\"] <- df.i$prob\n }\n #df <- df[!is.na(df$prob), ]\n }\n if (remove.isolate) {\n df <- df[!is.na(df$prob), ]\n line.on <- FALSE\n }\n if (nrow(df) == 0) {\n stop(\"No interactions are detected. Please consider changing the cell groups for analysis. \")\n }\n # Re-order y-axis\n if (!is.null(pairLR.use)) {\n interaction_name_2.order <- intersect(object@DB$interaction[pairLR.use$interaction_name, ]$interaction_name_2, unique(df$interaction_name_2))\n df$interaction_name_2 <- factor(df$interaction_name_2, levels = interaction_name_2.order)\n }\n\n # Re-order x-axis\n df$source.target = droplevels(df$source.target, exclude = setdiff(levels(df$source.target),unique(df$source.target)))\n if (sort.by.target & !sort.by.source) {\n if (!is.null(targets.use)) {\n df$target <- factor(df$target, levels = intersect(targets.use, df$target))\n df <- with(df, df[order(target, source),])\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n if (sort.by.source & !sort.by.target) {\n if (!is.null(sources.use)) {\n df$source <- factor(df$source, levels = intersect(sources.use, df$source))\n df <- with(df, df[order(source, target),])\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n if (sort.by.source & sort.by.target) {\n if (!is.null(sources.use)) {\n df$source <- factor(df$source, levels = intersect(sources.use, df$source))\n if (!is.null(targets.use)) {\n df$target <- factor(df$target, levels = intersect(targets.use, df$target))\n }\n if (sort.by.source.priority) {\n df <- with(df, df[order(source, target),])\n } else {\n df <- with(df, df[order(target, source),])\n }\n\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n\n g <- ggplot(df, aes(x = source.target, y = interaction_name_2, color = prob, size = pval)) +\n geom_point(pch = 16) +\n theme_linedraw() + theme(panel.grid.major = element_blank()) +\n theme(axis.text.x = element_text(angle = angle.x, hjust= hjust.x, vjust = vjust.x),\n axis.title.x = element_blank(),\n axis.title.y = element_blank()) +\n scale_x_discrete(position = \"bottom\")\n\n values <- c(1,2,3); names(values) <- c(\"p > 0.05\", \"0.01 < p < 0.05\",\"p < 0.01\")\n if (is.null(dot.size.max)) {\n dot.size.max = max(df$pval)\n }\n if (is.null(dot.size.min)) {\n dot.size.min = min(df$pval)\n }\n g <- g + scale_radius(range = c(dot.size.min, dot.size.max), breaks = sort(unique(df$pval)),labels = names(values)[values %in% sort(unique(df$pval))], name = \"p-value\")\n #g <- g + scale_radius(range = c(1,3), breaks = values,labels = names(values), name = \"p-value\")\n if (min(df$prob, na.rm = T) != max(df$prob, na.rm = T)) {\n g <- g + scale_colour_gradientn(colors = colorRampPalette(color.use)(99), na.value = \"white\", limits=c(quantile(df$prob, 0,na.rm= T), quantile(df$prob, 1,na.rm= T)),\n breaks = c(quantile(df$prob, 0,na.rm= T), quantile(df$prob, 1,na.rm= T)), labels = c(\"min\",\"max\")) +\n guides(color = guide_colourbar(barwidth = 0.5, title = \"Commun. Prob.\"))\n } else {\n g <- g + scale_colour_gradientn(colors = colorRampPalette(color.use)(99), na.value = \"white\") +\n guides(color = guide_colourbar(barwidth = 0.5, title = \"Commun. Prob.\"))\n }\n\n g <- g + theme(text = element_text(size = font.size),plot.title = element_text(size=font.size.title)) +\n theme(legend.title = element_text(size = 8), legend.text = element_text(size = 6))\n\n if (grid.on) {\n if (length(unique(df$source.target)) > 1) {\n g <- g + geom_vline(xintercept=seq(1.5, length(unique(df$source.target))-0.5, 1),lwd=0.1,colour=color.grid)\n }\n if (length(unique(df$interaction_name_2)) > 1) {\n g <- g + geom_hline(yintercept=seq(1.5, length(unique(df$interaction_name_2))-0.5, 1),lwd=0.1,colour=color.grid)\n }\n }\n if (!is.null(title.name)) {\n g <- g + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5))\n }\n\n if (!is.null(comparison)) {\n if (line.on) {\n xintercept = seq(0.5+length(dataset.name[comparison]), length(group.names0)*length(dataset.name[comparison]), by = length(dataset.name[comparison]))\n g <- g + geom_vline(xintercept = xintercept, linetype=\"dashed\", color = \"grey60\", size = line.size)\n }\n if (color.text.use) {\n if (is.null(group)) {\n group <- 1:length(comparison)\n names(group) <- dataset.name[comparison]\n }\n if (is.null(color.text)) {\n color <- ggPalette(length(unique(group)))\n } else {\n color <- color.text\n }\n names(color) <- names(group[!duplicated(group)])\n color <- color[group]\n #names(color) <- dataset.name[comparison]\n dataset.name.order <- levels(df$source.target)\n dataset.name.order <- stringr::str_match(dataset.name.order, \"\\\\(.*\\\\)\")\n dataset.name.order <- stringr::str_sub(dataset.name.order, 2, stringr::str_length(dataset.name.order)-1)\n xtick.color <- color[dataset.name.order]\n g <- g + theme(axis.text.x = element_text(colour = xtick.color))\n }\n }\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (return.data) {\n return(list(communication = df, gg.obj = g))\n } else {\n return(g)\n }\n\n}\n\n\n\n\n#' Chord diagram for visualizing cell-cell communication for a signaling pathway\n#'\n#' Names of cell states will be displayed in this chord diagram\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the name of signaling networks\n#' @param net a weighted matrix or a data frame with three columns defining the cell-cell communication network\n#' @param slot.name the slot name of object: slot.name = \"net\" when visualizing cell-cell communication network per each ligand-receptor pair associated with a given signaling pathway;\n#' slot.name = \"netP\" when visualizing cell-cell communication network at the level of signaling pathways\n#' @param color.use colors for the cell groups\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param remove.isolate whether remove sectors without any links\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the figures\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param ... other parameters passing to chordDiagram\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_cell <- function(object, signaling = NULL, net = NULL, slot.name = \"netP\",\n color.use = NULL,group = NULL,cell.order = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n remove.isolate = FALSE, link.visible = TRUE, scale = FALSE, directional = 1,link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20, nCol = NULL,\n thresh = 0.05,...){\n\n if (!is.null(signaling)) {\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n }\n\n if (slot.name == \"netP\") {\n message(\"Plot the aggregated cell-cell communication network at the signaling pathway level\")\n net <- apply(prob, c(1,2), sum)\n if (is.null(title.name)) {\n title.name <- paste0(signaling, \" signaling pathway network\")\n }\n # par(mfrow = c(1,1), xpd=TRUE)\n # par(mar = c(5, 4, 4, 2))\n gg <- netVisual_chord_cell_internal(net, color.use = color.use, group = group, cell.order = cell.order, sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap, big.gap = big.gap,annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y, ...)\n } else if (slot.name == \"net\") {\n message(\"Plot the cell-cell communication network per each ligand-receptor pair associated with a given signaling pathway\")\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n # layout(matrix(1:length(pairLR.name.use), ncol = nCol))\n # par(xpd=TRUE)\n # par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE, mar = c(5, 4, 4, 2) +0.1)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n #par(mar = c(5, 4, 4, 2))\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n gg[[i]] <- netVisual_chord_cell_internal(net, color.use = color.use, group = group,cell.order = cell.order,sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap,big.gap = big.gap, annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y, ...)\n }\n }\n\n } else if (!is.null(net)) {\n gg <- netVisual_chord_cell_internal(net, color.use = color.use, group = group,cell.order = cell.order,sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap, big.gap = big.gap,annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y, ...)\n } else {\n stop(\"Please assign values to either `signaling` or `net`\")\n }\n\n return(gg)\n}\n\n\n#' Chord diagram for visualizing cell-cell communication from a weighted adjacency matrix or a data frame\n#'\n#' Names of cell states/groups will be displayed in this chord diagram\n#'\n#' @param net a weighted matrix or a data frame with three columns defining the cell-cell communication network\n#' @param color.use colors for the cell groups\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param remove.isolate whether remove sectors without any links\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name of the plot\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param ... other parameters passing to chordDiagram\n#' @importFrom circlize circos.clear chordDiagram circos.track circos.text get.cell.meta.data\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_cell_internal <- function(net, color.use = NULL, group = NULL, cell.order = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n remove.isolate = FALSE, link.visible = TRUE, scale = FALSE, directional = 1, link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20,...){\n if (inherits(x = net, what = c(\"matrix\", \"Matrix\"))) {\n cell.levels <- union(rownames(net), colnames(net))\n net <- reshape2::melt(net, value.name = \"prob\")\n colnames(net)[1:2] <- c(\"source\",\"target\")\n } else if (is.data.frame(net)) {\n if (all(c(\"source\",\"target\", \"prob\") %in% colnames(net)) == FALSE) {\n stop(\"The input data frame must contain three columns named as source, target, prob\")\n }\n cell.levels <- as.character(union(net$source,net$target))\n }\n if (!is.null(cell.order)) {\n cell.levels <- cell.order\n }\n net$source <- as.character(net$source)\n net$target <- as.character(net$target)\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cell.levels[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cell.levels[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n }\n # remove the interactions with zero values\n net <- subset(net, prob > 0)\n if(dim(net)[1]<=0){message(\"No interaction between those cells\")}\n # create a fake data if keeping the cell types (i.e., sectors) without any interactions\n if (!remove.isolate) {\n cells.removed <- setdiff(cell.levels, as.character(union(net$source,net$target)))\n if (length(cells.removed) > 0) {\n net.fake <- data.frame(cells.removed, cells.removed, 1e-10*sample(length(cells.removed), length(cells.removed)))\n colnames(net.fake) <- colnames(net)\n net <- rbind(net, net.fake)\n link.visible <- net[, 1:2]\n link.visible$plot <- FALSE\n if(nrow(net) > nrow(net.fake)){\n link.visible$plot[1:(nrow(net) - nrow(net.fake))] <- TRUE\n }\n # directional <- net[, 1:2]\n # directional$plot <- 0\n # directional$plot[1:(nrow(net) - nrow(net.fake))] <- 1\n # link.arr.type = \"big.arrow\"\n # message(\"Set scale = TRUE when remove.isolate = FALSE\")\n scale = TRUE\n }\n }\n\n df <- net\n cells.use <- union(df$source,df$target)\n\n # define grid order\n order.sector <- cell.levels[cell.levels %in% cells.use]\n\n # define grid color\n if (is.null(color.use)){\n color.use = scPalette(length(cell.levels))\n names(color.use) <- cell.levels\n } else if (is.null(names(color.use))) {\n names(color.use) <- cell.levels\n }\n grid.col <- color.use[order.sector]\n names(grid.col) <- order.sector\n\n # set grouping information\n if (!is.null(group)) {\n group <- group[names(group) %in% order.sector]\n }\n\n # define edge color\n edge.color <- color.use[as.character(df$source)]\n\n if (directional == 0 | directional == 2) {\n link.arr.type = \"triangle\"\n } else {\n link.arr.type = \"big.arrow\"\n }\n\n circos.clear()\n chordDiagram(df,\n order = order.sector,\n col = edge.color,\n grid.col = grid.col,\n transparency = transparency,\n link.border = link.border,\n directional = directional,\n direction.type = c(\"diffHeight\",\"arrows\"),\n link.arr.type = link.arr.type, # link.border = \"white\",\n annotationTrack = \"grid\",\n annotationTrackHeight = annotationTrackHeight,\n preAllocateTracks = list(track.height = max(strwidth(order.sector))),\n small.gap = small.gap,\n big.gap = big.gap,\n link.visible = link.visible,\n scale = scale,\n group = group,\n link.target.prop = link.target.prop,\n reduce = reduce,\n ...)\n circos.track(track.index = 1, panel.fun = function(x, y) {\n xlim = get.cell.meta.data(\"xlim\")\n xplot = get.cell.meta.data(\"xplot\")\n ylim = get.cell.meta.data(\"ylim\")\n sector.name = get.cell.meta.data(\"sector.index\")\n circos.text(mean(xlim), ylim[1], sector.name, facing = \"clockwise\", niceFacing = TRUE, adj = c(0, 0.5),cex = lab.cex)\n }, bg.border = NA)\n\n # https://jokergoo.github.io/circlize_book/book/legends.html\n if (show.legend) {\n lgd <- ComplexHeatmap::Legend(at = names(grid.col), type = \"grid\", legend_gp = grid::gpar(fill = grid.col), title = \"Cell State\")\n ComplexHeatmap::draw(lgd, x = unit(1, \"npc\")-unit(legend.pos.x, \"mm\"), y = unit(legend.pos.y, \"mm\"), just = c(\"right\", \"bottom\"))\n }\n\n if(!is.null(title.name)){\n # title(title.name, cex = 1)\n text(-0, 1.02, title.name, cex=1)\n }\n circos.clear()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Chord diagram for visualizing cell-cell communication for a set of ligands/receptors or signaling pathways\n#'\n#' Names of ligands/receptors or signaling pathways will be displayed in this chord diagram\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object: slot.name = \"net\" when visualizing links at the level of ligands/receptors; slot.name = \"netP\" when visualizing links at the level of signaling pathways\n#' @param signaling a character vector giving the name of signaling networks\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param net A data frame consisting of the interactions of interest.\n#' net should have at least three columns: \"source\",\"target\" and \"interaction_name\" when visualizing links at the level of ligands/receptors;\n#' \"source\",\"target\" and \"pathway_name\" when visualizing links at the level of signaling pathway; \"interaction_name\" and \"pathway_name\" must be the matched names in CellChatDB$interaction.\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param color.use colors for the cell groups\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name of the plot\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param ... other parameters to chordDiagram\n#' @importFrom circlize circos.clear chordDiagram circos.track circos.text get.cell.meta.data\n#' @importFrom dplyr select %>% group_by summarize\n#' @importFrom grDevices recordPlot\n#' @importFrom stringr str_split\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_gene <- function(object, slot.name = \"net\", color.use = NULL,\n signaling = NULL, pairLR.use = NULL, net = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n link.visible = TRUE, scale = FALSE, directional = 1, link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, legend.pos.x = 20, legend.pos.y = 20, show.legend = TRUE,\n thresh = 0.05,\n ...){\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use) | sum(c(\"interaction_name\",\"pathway_name\") %in% colnames(pairLR.use) == 0)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n message(\"slot.name is set to be 'netP' when pairLR.use contains signaling pathways\")\n slot.name = \"netP\"\n }\n }\n\n if (!is.null(pairLR.use) & !is.null(signaling)) {\n stop(\"Please do not assign values to 'signaling' when using 'pairLR.use'\")\n }\n\n if (is.null(net)) {\n prob <- slot(object, \"net\")$prob\n pval <- slot(object, \"net\")$pval\n prob[pval > thresh] <- 0\n net <- reshape2::melt(prob, value.name = \"prob\")\n colnames(net)[1:3] <- c(\"source\",\"target\",\"interaction_name\")\n cols.default <- c(\"interaction_name_2\", \"pathway_name\", \"ligand\", \"receptor\" ,\"annotation\",\"evidence\")\n cols.common <- intersect(cols.default,colnames(object@LR$LRsig))\n pairLR = dplyr::select(object@LR$LRsig, cols.common)\n idx <- match(net$interaction_name, rownames(pairLR))\n temp <- pairLR[idx,]\n net <- cbind(net, temp)\n }\n\n if (!is.null(signaling)) {\n pairLR.use <- data.frame()\n for (i in 1:length(signaling)) {\n pairLR.use.i <- searchPair(signaling = signaling[i], pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.use <- rbind(pairLR.use, pairLR.use.i)\n }\n }\n\n if (!is.null(pairLR.use)){\n if (\"interaction_name\" %in% colnames(pairLR.use)) {\n net <- subset(net,interaction_name %in% pairLR.use$interaction_name)\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n net <- subset(net, pathway_name %in% as.character(pairLR.use$pathway_name))\n }\n }\n\n if (slot.name == \"netP\") {\n net <- dplyr::select(net, c(\"source\",\"target\",\"pathway_name\",\"prob\"))\n net$source_target <- paste(net$source, net$target, sep = \"sourceTotarget\")\n net <- net %>% dplyr::group_by(source_target, pathway_name) %>% dplyr::summarize(prob = sum(prob))\n a <- stringr::str_split(net$source_target, \"sourceTotarget\", simplify = T)\n net$source <- as.character(a[, 1])\n net$target <- as.character(a[, 2])\n net$ligand <- net$pathway_name\n net$receptor <- \" \"\n }\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- levels(object@idents)[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n } else {\n sources.use <- levels(object@idents)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- levels(object@idents)[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n } else {\n targets.use <- levels(object@idents)\n }\n # remove the interactions with zero values\n df <- subset(net, prob > 0)\n\n if (nrow(df) == 0) {\n stop(\"No signaling links are inferred! \")\n }\n\n if (length(unique(net$ligand)) == 1) {\n message(\"You may try the function `netVisual_chord_cell` for visualizing individual signaling pathway\")\n }\n\n df$id <- 1:nrow(df)\n # deal with duplicated sector names\n ligand.uni <- unique(df$ligand)\n for (i in 1:length(ligand.uni)) {\n df.i <- df[df$ligand == ligand.uni[i], ]\n source.uni <- unique(df.i$source)\n for (j in 1:length(source.uni)) {\n df.i.j <- df.i[df.i$source == source.uni[j], ]\n df.i.j$ligand <- paste0(df.i.j$ligand, paste(rep(' ',j-1),collapse = ''))\n df$ligand[df$id %in% df.i.j$id] <- df.i.j$ligand\n }\n }\n receptor.uni <- unique(df$receptor)\n for (i in 1:length(receptor.uni)) {\n df.i <- df[df$receptor == receptor.uni[i], ]\n target.uni <- unique(df.i$target)\n for (j in 1:length(target.uni)) {\n df.i.j <- df.i[df.i$target == target.uni[j], ]\n df.i.j$receptor <- paste0(df.i.j$receptor, paste(rep(' ',j-1),collapse = ''))\n df$receptor[df$id %in% df.i.j$id] <- df.i.j$receptor\n }\n }\n\n cell.order.sources <- levels(object@idents)[levels(object@idents) %in% sources.use]\n cell.order.targets <- levels(object@idents)[levels(object@idents) %in% targets.use]\n\n df$source <- factor(df$source, levels = cell.order.sources)\n df$target <- factor(df$target, levels = cell.order.targets)\n # df.ordered.source <- df[with(df, order(source, target, -prob)), ]\n # df.ordered.target <- df[with(df, order(target, source, -prob)), ]\n df.ordered.source <- df[with(df, order(source, -prob)), ]\n df.ordered.target <- df[with(df, order(target, -prob)), ]\n\n order.source <- unique(df.ordered.source[ ,c('ligand','source')])\n order.target <- unique(df.ordered.target[ ,c('receptor','target')])\n\n # define sector order\n order.sector <- c(order.source$ligand, order.target$receptor)\n\n # define cell type color\n if (is.null(color.use)){\n color.use = scPalette(nlevels(object@idents))\n names(color.use) <- levels(object@idents)\n color.use <- color.use[levels(object@idents) %in% as.character(union(df$source,df$target))]\n } else if (is.null(names(color.use))) {\n names(color.use) <- levels(object@idents)\n color.use <- color.use[levels(object@idents) %in% as.character(union(df$source,df$target))]\n }\n\n # define edge color\n edge.color <- color.use[as.character(df.ordered.source$source)]\n names(edge.color) <- as.character(df.ordered.source$source)\n\n # define grid colors\n grid.col.ligand <- color.use[as.character(order.source$source)]\n names(grid.col.ligand) <- as.character(order.source$source)\n grid.col.receptor <- color.use[as.character(order.target$target)]\n names(grid.col.receptor) <- as.character(order.target$target)\n grid.col <- c(as.character(grid.col.ligand), as.character(grid.col.receptor))\n names(grid.col) <- order.sector\n\n df.plot <- df.ordered.source[ ,c('ligand','receptor','prob')]\n\n if (directional == 2) {\n link.arr.type = \"triangle\"\n } else {\n link.arr.type = \"big.arrow\"\n }\n circos.clear()\n chordDiagram(df.plot,\n order = order.sector,\n col = edge.color,\n grid.col = grid.col,\n transparency = transparency,\n link.border = link.border,\n directional = directional,\n direction.type = c(\"diffHeight\",\"arrows\"),\n link.arr.type = link.arr.type,\n annotationTrack = \"grid\",\n annotationTrackHeight = annotationTrackHeight,\n preAllocateTracks = list(track.height = max(strwidth(order.sector))),\n small.gap = small.gap,\n big.gap = big.gap,\n link.visible = link.visible,\n scale = scale,\n link.target.prop = link.target.prop,\n reduce = reduce,\n ...)\n\n circos.track(track.index = 1, panel.fun = function(x, y) {\n xlim = get.cell.meta.data(\"xlim\")\n xplot = get.cell.meta.data(\"xplot\")\n ylim = get.cell.meta.data(\"ylim\")\n sector.name = get.cell.meta.data(\"sector.index\")\n circos.text(mean(xlim), ylim[1], sector.name, facing = \"clockwise\", niceFacing = TRUE, adj = c(0, 0.5),cex = lab.cex)\n }, bg.border = NA)\n\n # https://jokergoo.github.io/circlize_book/book/legends.html\n if (show.legend) {\n lgd <- ComplexHeatmap::Legend(at = names(color.use), type = \"grid\", legend_gp = grid::gpar(fill = color.use), title = \"Cell State\")\n ComplexHeatmap::draw(lgd, x = unit(1, \"npc\")-unit(legend.pos.x, \"mm\"), y = unit(legend.pos.y, \"mm\"), just = c(\"right\", \"bottom\"))\n }\n\n circos.clear()\n if(!is.null(title.name)){\n text(-0, 1.02, title.name, cex=1)\n }\n gg <- recordPlot()\n return(gg)\n}\n\n\n\n\n#' River plot showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways\n#'\n#' River (alluvial) plot shows the correspondence between the inferred latent patterns and cell groups as well as ligand-receptor pairs or signaling pathways.\n#'\n#' The thickness of the flow indicates the contribution of the cell group or signaling pathway to each latent pattern. The height of each pattern is proportional to the number of its associated cell groups or signaling pathways.\n#'\n#' Outgoing patterns reveal how the sender cells coordinate with each other as well as how they coordinate with certain signaling pathways to drive communication.\n#'\n#' Incoming patterns show how the target cells coordinate with each other as well as how they coordinate with certain signaling pathways to respond to incoming signaling.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object: “netP” or “net”. Use “netP” to analyze cell-cell communication at the level of signaling pathways, and “net” to analyze cell-cell communication at the level of ligand-receptor pairs.\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param cutoff the threshold for filtering out weak links\n#' @param sources.use a vector giving the index or the name of source cell groups of interest\n#' @param targets.use a vector giving the index or the name of target cell groups of interest\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.use.pattern the character vector defining the color of each pattern\n#' @param color.use.signaling the character vector defining the color of each signaling\n#' @param do.order whether reorder the cell groups or signaling according to their similarity\n#' @param main.title the title of plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom methods slot\n#' @importFrom stats cutree dist hclust\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @import ggalluvial\n# #' @importFrom ggalluvial geom_stratum geom_flow to_lodes_form\n#' @importFrom ggplot2 geom_text scale_x_discrete scale_fill_manual theme ggtitle\n#' @importFrom cowplot plot_grid ggdraw draw_label\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_river <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = 0.5,\n sources.use = NULL, targets.use = NULL, signaling = NULL,\n color.use = NULL, color.use.pattern = NULL, color.use.signaling = \"grey50\",\n do.order = FALSE, main.title = NULL,\n font.size = 2.5, font.size.title = 12){\n message(\"Please make sure you have load `library(ggalluvial)` when running this function\")\n requireNamespace(\"ggalluvial\")\n # suppressMessages(require(ggalluvial))\n res.pattern <- methods::slot(object, slot.name)$pattern[[pattern]]\n data1 = res.pattern$pattern$cell\n data2 = res.pattern$pattern$signaling\n if (is.null(color.use.pattern)) {\n nPatterns <- length(unique(data1$Pattern))\n if (pattern == \"outgoing\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(1,nPatterns*2, by = 2)]\n } else if (pattern == \"incoming\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(2,nPatterns*2, by = 2)]\n }\n }\n if (is.null(main.title)) {\n if (pattern == \"outgoing\") {\n main.title = \"Outgoing communication patterns of secreting cells\"\n } else if (pattern == \"incoming\") {\n main.title = \"Incoming communication patterns of target cells\"\n }\n }\n\n if (is.null(data2)) {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n if (is.null(color.use)) {\n color.use <- scPalette(nCellGroup)\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n gg <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10))+\n ggtitle(main.title)\n\n } else {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n cells.level = levels(object@idents)\n if (is.null(color.use)) {\n color.use <- scPalette(length(cells.level))[cells.level %in% unique(plot.data$CellGroup)]\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n if (!is.null(sources.use)) {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% sources.use)\n }\n if (!is.null(targets.use)) {\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% targets.use)\n }\n ## connect cell groups with patterns\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n StatStratum <- ggalluvial::StatStratum\n gg1 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10)) +\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n ## connect patterns with signaling\n data2$Contribution[data2$Contribution < cutoff] <- 0\n plot.data <- data2\n nPatterns<-length(unique(plot.data$Pattern))\n nSignaling<-length(unique(plot.data$Signaling))\n if (length(color.use.signaling) == 1) {\n color.use.all <- c(color.use.pattern, rep(color.use.signaling, nSignaling))\n } else {\n color.use.all <- c(color.use.pattern, color.use.signaling)\n }\n\n if (!is.null(signaling)) {\n plot.data <- plot.data[plot.data$Signaling %in% signaling, ]\n }\n\n plot.data.long <- ggalluvial::to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"Signaling\"]], plot.data[[\"Pattern\"]]), sum)\n mat[is.na(mat)] <- 0; mat <- mat[-which(rowSums(mat) == 0), ]\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(colnames(mat),names(cluster)[order.name]))\n }\n\n gg2 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"Pattern\", \"Signaling\")),y= Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"forward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) + # 2.5\n scale_x_discrete(limits = c(), labels=c(\"Patterns\", \"Signaling\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size= 10))+\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n ## connect cell groups with signaling\n # data1 = data1[data1$Contribution > 0,]\n # data2 = data2[data2$Contribution > 0,]\n\n # data3 = merge(data1, data2, by.x=\"Pattern\", by.y=\"Pattern\")\n # data3$Contribution <- data3$Contribution.x * data3$Contribution.y\n # data3 <- data3[,colnames(data3) %in% c(\"CellGroup\",\"Signaling\",\"Contribution\")]\n\n # plot.data <- data3\n # nSignaling<-length(unique(plot.data$Signaling))\n # nCellGroup<-length(unique(plot.data$CellGroup))\n #\n # if (length(color.use.signaling) == 1) {\n # color.use.signaling <- rep(color.use.signaling, nSignaling)\n # }\n #\n #\n # ## connect cell groups with patterns\n # plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n # if (do.order) {\n # mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Signaling\"]]), sum)\n # d <- dist(as.matrix(mat))\n # hc <- hclust(d, \"ave\")\n # k <- length(unique(grep(\"Signaling\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n # cluster <- hc %>% cutree(k)\n # order.name <- order(cluster)\n # plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n # color.use <- color.use[order.name]\n # }\n # color.use.all <- c(color.use, color.use.signaling)\n\n # gg3 <- ggplot(plot.data.long, aes(x = factor(x, levels = c(\"CellGroup\", \"Signaling\")),y=Contribution,\n # stratum = stratum, alluvium = connection,\n # fill = stratum, label = stratum)) +\n # geom_flow(width = 1/3,aes.flow = \"forward\") +\n # geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n # geom_text(stat = \"stratum\", size = 2.5) +\n # scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Signaling\")) +\n # scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n # theme_bw()+\n # theme(legend.position = \"none\",\n # axis.title = element_blank(),\n # axis.text.y= element_blank(),\n # panel.grid.major = element_blank(),\n # panel.grid.minor = element_blank(),\n # panel.border = element_blank(),\n # axis.ticks = element_blank(),axis.text=element_text(size=10)) +\n # theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n\n gg <- cowplot::plot_grid(gg1, gg2,align = \"h\", nrow = 1)\n title <- cowplot::ggdraw() + cowplot::draw_label(main.title,size = font.size.title)\n gg <- cowplot::plot_grid(title, gg, ncol=1, rel_heights=c(0.1, 1))\n }\n return(gg)\n}\n\n#' Dot plots showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways\n#'\n#' Using a contribution score of each cell group to each signaling pathway computed by multiplying W by H obtained from `identifyCommunicationPatterns`, we constructed a dot plot in which the dot size is proportion to the contribution score to show association between cell group and their enriched signaling pathways.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param cutoff the threshold for filtering out weak links. Default is 1/R where R is the number of latent patterns. We set the elements in W and H to be zero if they are less than `cutoff`.\n#' @param color.use the character vector defining the color of each cell group\n#' @param pathway.show the character vector defining the signaling to show\n#' @param group.show the character vector defining the cell group to show\n#' @param shape the shape of the symbol: 21 for circle and 22 for square\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param main.title the title of plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom methods slot\n#' @import ggplot2\n#' @importFrom dplyr group_by top_n\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_dot <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = NULL, color.use = NULL,\n pathway.show = NULL, group.show = NULL,\n shape = 21, dot.size = c(1, 3), dot.alpha = 1, main.title = NULL,\n font.size = 10, font.size.title = 12){\n pattern <- match.arg(pattern)\n patternSignaling <- methods::slot(object, slot.name)$pattern[[pattern]]\n data1 = patternSignaling$pattern$cell\n data2 = patternSignaling$pattern$signaling\n data = patternSignaling$data\n if (is.null(main.title)) {\n if (pattern == \"outgoing\") {\n main.title = \"Outgoing communication patterns of secreting cells\"\n } else if (pattern == \"incoming\") {\n main.title = \"Incoming communication patterns of target cells\"\n }\n }\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(data1$CellGroup))\n }\n if (is.null(cutoff)) {\n cutoff <- 1/length(unique(data1$Pattern))\n }\n options(warn = -1)\n data1$Contribution[data1$Contribution < cutoff] <- 0\n data2$Contribution[data2$Contribution < cutoff] <- 0\n data3 = merge(data1, data2, by.x=\"Pattern\", by.y=\"Pattern\")\n data3$Contribution <- data3$Contribution.x * data3$Contribution.y\n data3 <- data3[,colnames(data3) %in% c(\"CellGroup\",\"Signaling\",\"Contribution\")]\n if (!is.null(pathway.show)) {\n data3 <- data3[data3$Signaling %in% pathway.show, ]\n pathway.add <- pathway.show[which(pathway.show %in% data3$Signaling == 0)]\n if (length(pathway.add) > 1) {\n data.add <- expand.grid(CellGroup = levels(data1$CellGroup), Signaling = pathway.add)\n data.add$Contribution <- 0\n data3 <- rbind(data3, data.add)\n }\n data3$Signaling <- factor(data3$Signaling, levels = pathway.show)\n }\n if (!is.null(group.show)) {\n data3$CellGroup <- as.character(data3$CellGroup)\n data3 <- data3[data3$CellGroup %in% group.show, ]\n data3$CellGroup <- factor(data3$CellGroup, levels = group.show)\n }\n\n data <- as.data.frame(as.table(data));\n data <- data[data[,3] != 0, ]\n data12 <- paste0(data[,1],data[,2])\n data312 <- paste0(data3[,1],data3[,2])\n idx1 <- which(match(data312, data12, nomatch = 0) ==0)\n data3$Contribution[idx1] <- 0\n data3$id <- data312\n data3 <- data3 %>% group_by(id) %>% top_n(1, Contribution)\n\n data3$Contribution[which(data3$Contribution == 0)] <- NA\n\n df <- data3\n gg <- ggplot(data = df, aes(x = Signaling, y = CellGroup)) +\n geom_point(aes(size = Contribution, fill = CellGroup, colour = CellGroup), shape = shape) +\n scale_size_continuous(range = dot.size) +\n theme_linedraw() +\n scale_x_discrete(position = \"bottom\") +\n ggtitle(main.title) +\n theme(plot.title = element_text(hjust = 0.5)) +\n theme(text = element_text(size = font.size),plot.title = element_text(size=font.size.title, face=\"plain\"),\n axis.text.x = element_text(angle = 45, hjust=1),\n axis.text.y = element_text(angle = 0, hjust=1),\n axis.title.x = element_blank(),\n axis.title.y = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25)) +\n theme(panel.grid.major = element_line(colour=\"grey90\", size = (0.1)))\n gg <- gg + scale_y_discrete(limits = rev(levels(data3$CellGroup)))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE, na.value = \"white\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, na.value = \"white\")\n gg <- gg + guides(colour=\"none\") + guides(fill=\"none\")\n gg <- gg + theme(legend.title = element_text(size = 10), legend.text = element_text(size = 8))\n gg\n return(gg)\n}\n\n\n#' 2D visualization of the learned manifold of signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param pathway.labeled a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param pathway.remove.show whether show the removed signaling names\n#' @param color.use defining the color for each cell group\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embedding <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), color.use = NULL, pathway.labeled = NULL, top.label = 1, pathway.remove = NULL, pathway.remove.show = TRUE, dot.size = c(2, 6), label.size = 2, dot.alpha = 0.5,\n xlabel = \"Dim 1\", ylabel = \"Dim 2\", title = NULL,\n font.size = 10, font.size.title = 12, do.label = T, show.legend = T, show.axes = T) {\n type <- match.arg(type)\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n Groups <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n prob <- methods::slot(object, slot.name)$prob\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n }\n\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(dimnames(prob)[[3]] %in% pathway.remove)\n prob <- prob[ , , -pathway.remove.idx]\n }\n\n prob_sum <- apply(prob, 3, sum)\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum), labels = as.character(unlist(dimnames(prob)[3])), Groups = as.factor(Groups))\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(Groups)))\n }\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.,fill = Groups, colour = Groups), shape = 21) +\n CellChat_theme_opts() +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\"))+\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE)\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n if (do.label) {\n if (is.null(pathway.labeled)) {\n if (top.label < 1) {\n if (length(comparison) == 2) {\n g.t <- rankSimilarity(object, slot.name = slot.name, type = type, comparison1 = comparison)\n pathway.labeled <- as.character(g.t$data$name[(nrow(g.t$data)-ceiling(top.label * nrow(g.t$data))+1):nrow(g.t$data) ])\n data.label <- df[df$labels %in% pathway.labeled, , drop = FALSE]\n }\n } else {\n data.label <- df\n }\n\n } else {\n data.label <- df[df$labels %in% pathway.labeled, , drop = FALSE]\n }\n gg <- gg + ggrepel::geom_text_repel(data = data.label, mapping = aes(label = labels, colour = Groups), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n\n # gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = Groups), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (length(pathway.remove) > 0 & pathway.remove.show) {\n gg <- gg + annotate(geom = 'text', label = paste(\"Isolate pathways: \", paste(pathway.remove, collapse = ', ')), x = -Inf, y = Inf, hjust = 0, vjust = 1, size = label.size,fontface=\"italic\")\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n gg\n}\n\n\n#' Zoom into the 2D visualization of the learned manifold learning of the signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param color.use defining the color for each cell group\n#' @param nCol the number of columns of the plot\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom cowplot plot_grid\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingZoomIn <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), color.use = NULL, pathway.remove = NULL, nCol = 1, dot.size = c(2, 6), label.size = 2.8, dot.alpha = 0.5,\n xlabel = NULL, ylabel = NULL, do.label = T, show.legend = F, show.axes = T) {\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n prob <- methods::slot(object, slot.name)$prob\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n }\n\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(dimnames(prob)[[3]] %in% pathway.remove)\n prob <- prob[ , , -pathway.remove.idx]\n }\n\n prob_sum <- apply(prob, 3, sum)\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum), labels = as.character(unlist(dimnames(prob)[3])), clusters = as.factor(clusters))\n\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n\n # zoom into each cluster and do labels\n ggAll <- vector(\"list\", length(unique(clusters)))\n for (i in 1:length(unique(clusters))) {\n clusterID = i\n title <- paste0(\"Group \", clusterID)\n df2 <- df[df$clusters %in% clusterID,]\n gg <- ggplot(data = df2, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.), shape = 21, colour = alpha(color.use[clusterID], alpha = 1), fill = alpha(color.use[clusterID], alpha = dot.alpha)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size=12))+\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels), colour = color.use[clusterID], size = label.size, segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n ggAll[[i]] <- gg\n }\n gg.combined <- cowplot::plot_grid(plotlist = ggAll, ncol = nCol)\n\n gg.combined\n\n}\n\n\n\n#' 2D visualization of the joint manifold learning of signaling networks from two datasets\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object\n#' @param pathway.labeled a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param pathway.remove.show whether show the removed signaling names\n#' @param color.use defining the color for each cell group\n#' @param point.shape a numeric vector giving the point shapes. By default point.shape <- c(21, 0, 24, 23, 25, 10, 12), see available shapes at http://www.sthda.com/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingPairwise <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, color.use = NULL, point.shape = NULL, pathway.labeled = NULL, top.label = 1, pathway.remove = NULL, pathway.remove.show = TRUE, dot.size = c(2, 6), label.size = 2.5, dot.alpha = 0.5,\n xlabel = \"Dim 1\", ylabel = \"Dim 2\", title = NULL,do.label = T, show.legend = T, show.axes = T) {\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"2D visualization of signaling networks from datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n object.names <- setdiff(names(methods::slot(object, slot.name)), \"similarity\")[comparison]\n prob <- list()\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n prob[[i]] = object.net$prob\n }\n\n if (is.null(point.shape)) {\n point.shape <- c(21, 0, 24, 23, 25, 10, 12)\n }\n\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove <- sub(\"--.*\", \"\", pathway.remove)\n }\n\n if (length(pathway.remove) > 0) {\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n pathway.remove.idx <- which(paste0(dimnames(probi)[[3]],\"--\",object.names[i]) %in% pathway.remove)\n # pathway.remove.idx <- which(dimnames(probi)[[3]] %in% pathway.remove)\n if (length(pathway.remove.idx) > 0) {\n probi <- probi[ , , -pathway.remove.idx]\n }\n prob[[i]] <- probi\n }\n }\n prob_sum.each <- list()\n signalingAll <- c()\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n prob_sum.each[[i]] <- apply(probi, 3, sum)\n signalingAll <- c(signalingAll, paste0(names(prob_sum.each[[i]]),\"--\",object.names[i]))\n }\n prob_sum <- unlist(prob_sum.each)\n names(prob_sum) <- signalingAll\n\n group <- sub(\".*--\", \"\", names(prob_sum))\n labels = sub(\"--.*\", \"\", names(prob_sum))\n\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum),\n labels = as.character(labels), clusters = as.factor(clusters), group = factor(group, levels = unique(group)))\n # color dots (light inside color and dark border) based on clustering and no labels\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.,fill = clusters, colour = clusters, shape = group)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) +\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) #+ scale_alpha(group, range = c(0.1, 1))\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n gg <- gg + scale_shape_manual(values = point.shape[1:length(prob)])\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = clusters, alpha=group), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n }\n\n if (length(pathway.remove) > 0 & pathway.remove.show) {\n gg <- gg + annotate(geom = 'text', label = paste(\"Isolate pathways: \", paste(pathway.remove, collapse = ', ')), x = -Inf, y = Inf, hjust = 0, vjust = 1, size = label.size,fontface=\"italic\")\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n gg\n}\n\n\n\n#' Zoom into the 2D visualization of the joint manifold learning of signaling networks from two datasets\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param color.use defining the color for each cell group\n#' @param nCol number of columns in the plot\n#' @param point.shape a numeric vector giving the point shapes. By default point.shape <- c(21, 0, 24, 23, 25, 10, 12), see available shapes at http://www.sthda.com/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingPairwiseZoomIn <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, color.use = NULL, nCol = 1, point.shape = NULL, pathway.remove = NULL, dot.size = c(2, 6), label.size = 2.8, dot.alpha = 0.5,\n xlabel = NULL, ylabel = NULL, do.label = T, show.legend = F, show.axes = T) {\n\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"2D visualization of signaling networks from datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n object.names <- setdiff(names(methods::slot(object, slot.name)), \"similarity\")[comparison]\n prob <- list()\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n prob[[i]] = object.net$prob\n }\n\n if (is.null(point.shape)) {\n point.shape <- c(21, 0, 24, 23, 25, 10, 12)\n }\n\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove <- sub(\"--.*\", \"\", pathway.remove)\n }\n\n if (length(pathway.remove) > 0) {\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n pathway.remove.idx <- which(paste0(dimnames(probi)[[3]],\"--\",object.names[i]) %in% pathway.remove)\n # pathway.remove.idx <- which(dimnames(probi)[[3]] %in% pathway.remove)\n if (length(pathway.remove.idx) > 0) {\n probi <- probi[ , , -pathway.remove.idx]\n }\n prob[[i]] <- probi\n }\n }\n\n prob_sum.each <- list()\n signalingAll <- c()\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n prob_sum.each[[i]] <- apply(probi, 3, sum)\n signalingAll <- c(signalingAll, paste0(names(prob_sum.each[[i]]),\"--\",object.names[i]))\n }\n prob_sum <- unlist(prob_sum.each)\n names(prob_sum) <- signalingAll\n\n group <- sub(\".*--\", \"\", names(prob_sum))\n labels = sub(\"--.*\", \"\", names(prob_sum))\n\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum),\n labels = as.character(labels), clusters = as.factor(clusters), group = factor(group, levels = unique(group)))\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n\n # zoom into each cluster and do labels\n ggAll <- vector(\"list\", length(unique(clusters)))\n for (i in 1:length(unique(clusters))) {\n clusterID = i\n title <- paste0(\"Cluster \", clusterID)\n df2 <- df[df$clusters %in% clusterID,]\n gg <- ggplot(data = df2, aes(x, y)) +\n geom_point(aes(size = Commun.Prob., shape = group),fill = alpha(color.use[clusterID], alpha = dot.alpha), colour = alpha(color.use[clusterID], alpha = 1)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) +\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n idx <- match(unique(df2$group), levels(df$group), nomatch = 0)\n gg <- gg + scale_shape_manual(values= point.shape[idx])\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels), colour = color.use[clusterID], size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n ggAll[[i]] <- gg\n }\n gg.combined <- cowplot::plot_grid(plotlist = ggAll, ncol = nCol)\n\n gg.combined\n\n}\n\n\n#' A Seurat wrapper function for plotting gene expression using violin plot, dot plot or bar plot\n#'\n#' This function create a Seurat object from an input CellChat object, and then plot gene expression distribution using a modified violin plot or dot plot based on Seurat's function or a bar plot.\n#' Please check \\code{\\link{StackedVlnPlot}},\\code{\\link{dotPlot}} and \\code{\\link{barPlot}}for detailed description of the arguments.\n#'\n#' USER can extract the signaling genes related to the inferred L-R pairs or signaling pathway using \\code{\\link{extractEnrichedLR}}, and then plot gene expression using Seurat package.\n#'\n#' @param object CellChat object\n#' @param features Features to plot gene expression\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param type violin plot or dot plot\n#' @param color.use defining the color for each cell group\n#' @param group.by Name of one metadata columns to group (color) cells. Default is the defined cell groups in CellChat object\n#' @param ... other arguments passing to either VlnPlot or DotPlot from Seurat package\n#' @return\n#' @export\n#'\n#' @examples\n\nplotGeneExpression <- function(object, features = NULL, signaling = NULL, enriched.only = TRUE, type = c(\"violin\", \"dot\",\"bar\"), color.use = NULL, group.by = NULL, ...) {\n type <- match.arg(type)\n meta <- object@meta\n if (is.list(object@idents)) {\n meta$group.cellchat <- object@idents$joint\n } else {\n meta$group.cellchat <- object@idents\n }\n if (!identical(rownames(meta), colnames(object@data.signaling))) {\n cat(\"The cell barcodes in 'meta' is \", head(rownames(meta)),'\\n')\n warning(\"The cell barcodes in 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of 'mata'!\")\n rownames(meta) <- colnames(object@data.signaling)\n }\n\n w10x <- Seurat::CreateSeuratObject(counts = object@data.signaling, meta.data = meta)\n if (is.null(group.by)) {\n group.by <- \"group.cellchat\"\n }\n Seurat::Idents(w10x) <- group.by\n if (!is.null(features) & !is.null(signaling)) {\n warning(\"`features` will be used when inputing both `features` and `signaling`!\")\n }\n if (!is.null(features)) {\n feature.use <- features\n } else if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, enriched.only = enriched.only)\n feature.use <- res$geneLR\n }\n if (type == \"violin\") {\n gg <- StackedVlnPlot(w10x, features = feature.use, color.use = color.use, ...)\n } else if (type == \"dot\") {\n gg <- dotPlot(w10x, features = feature.use, color.use = color.use, ...)\n } else if (type == \"bar\") {\n gg <- barPlot(w10x, features = feature.use, color.use = color.use, ...)\n }\n return(gg)\n}\n\n\n#' Dot plot\n#'\n#'The size of the dot encodes the percentage of cells within a class, while the color encodes the AverageExpression level across all cells within a class\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param rotation whether rotate the plot\n#' @param colormap RColorbrewer palette to use (check available palette using RColorBrewer::display.brewer.all()). default will use customed color palette\n#' @param color.direction Sets the order of colours in the scale. If 1, the default, colours are as output by RColorBrewer::brewer.pal(). If -1, the order of colours is reversed.\n#' @param color.use defining the color for each condition/dataset\n#' @param idents Which classes to include in the plot (default is all)\n#' @param group.by Name of one or more metadata columns to group (color) cells by\n#' (for example, orig.ident); pass 'ident' to group by identity class\n#' @param split.by Name of a metadata column to split plot by;\n#' @param legend.width legend width\n#' @param scale whther show x-axis text\n#' @param col.min Minimum scaled average expression threshold (everything smaller will be set to this)\n#' @param col.max Maximum scaled average expression threshold (everything larger will be set to this)\n#' @param dot.scale Scale the size of the points, similar to cex\n#' @param assay Name of assay to use, defaults to the active assay\n#' @param angle.x angle for x-axis text rotation\n#' @param hjust.x adjust x axis text\n#' @param angle.y angle for y-axis text rotation\n#' @param hjust.y adjust y axis text\n#' @param show.legend whether show the legend\n#' @param ... Extra parameters passed to DotPlot from Seurat package\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\ndotPlot <- function(object, features, rotation = TRUE, colormap = \"OrRd\", color.direction = 1, color.use = c(\"#F8766D\",\"#00BFC4\"), scale = TRUE, col.min = -2.5, col.max = 2.5, dot.scale = 6, assay = \"RNA\",\n idents = NULL, group.by = NULL, split.by = NULL, legend.width = 0.5,\n angle.x = 45, hjust.x = 1, angle.y = 0, hjust.y = 0.5, show.legend = TRUE, ...) {\n\n gg <- Seurat::DotPlot(object, features = features, assay = assay, cols = color.use,\n scale = scale, col.min = col.min, col.max = col.max, dot.scale = dot.scale,\n idents = idents, group.by = group.by, split.by = split.by,...)\n gg <- gg + theme(axis.title.x=element_blank(), axis.title.y=element_blank()) +\n theme(axis.text.x = element_text(size = 10), axis.text.y = element_text(size = 10), axis.line = element_line(colour = 'black')) +\n theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))+\n theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x), axis.text.y = element_text(angle = angle.y, hjust = hjust.y))\n\n gg <- gg + theme(legend.title = element_text(size = 10), legend.text = element_text(size = 8))\n if (is.null(split.by)) {\n gg <- gg + guides(color = guide_colorbar(barwidth = legend.width, title = \"Scaled expression\"),size = guide_legend(title = 'Percent expressed'))\n }\n\n if (rotation) {\n gg <- gg + coord_flip()\n }\n if (!is.null(colormap)) {\n if (is.null(split.by)) {\n gg <- gg + scale_color_distiller(palette = colormap, direction = color.direction, guide = guide_colorbar(title = \"Scaled Expression\", ticks = T, label = T, barwidth = legend.width), na.value = \"lightgrey\")\n }\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n return(gg)\n}\n\n\n\n#' Stacked Violin plot\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param color.use defining the color for each cell group\n#' @param colors.ggplot whether use ggplot color scheme; default: colors.ggplot = FALSE\n#' @param split.by Name of a metadata column to split plot by;\n#' @param idents Which classes to include in the plot (default is all)\n#' @param show.text.y whther show y-axis text\n#' @param line.size line width in the violin plot\n#' @param pt.size size of the dots\n#' @param plot.margin adjust the white space between each plot\n#' @param angle.x angle for x-axis text rotation\n#' @param vjust.x adjust x axis text\n#' @param hjust.x adjust x axis text\n#' @param ... Extra parameters passed to VlnPlot from Seurat package\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\n#' @importFrom patchwork wrap_plots\n# #' @importFrom Seurat VlnPlot\nStackedVlnPlot<- function(object, features, idents = NULL, split.by = NULL,\n color.use = NULL, colors.ggplot = FALSE,\n angle.x = 90, vjust.x = NULL, hjust.x = NULL, show.text.y = TRUE, line.size = NULL,\n pt.size = 0,\n plot.margin = margin(0, 0, 0, 0, \"cm\"),\n ...) {\n options(warn=-1)\n if (is.null(color.use)) {\n numCluster <- length(levels(Seurat::Idents(object)))\n if (colors.ggplot) {\n color.use <- NULL\n } else {\n color.use <- scPalette(numCluster)\n }\n }\n if (is.null(vjust.x) | is.null(hjust.x)) {\n angle=c(0, 45, 90)\n hjust=c(0, 1, 1)\n vjust=c(0, 1, 0.5)\n vjust.x = vjust[angle == angle.x]\n hjust.x = hjust[angle == angle.x]\n }\n\n plot_list<- purrr::map(features, function(x) modify_vlnplot(object = object, features = x, idents = idents, split.by = split.by, cols = color.use, pt.size = pt.size,\n show.text.y = show.text.y, line.size = line.size, ...))\n\n # Add back x-axis title to bottom plot. patchwork is going to support this?\n plot_list[[length(plot_list)]]<- plot_list[[length(plot_list)]] +\n theme(axis.text.x=element_text(), axis.ticks.x = element_line()) +\n theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x, vjust = vjust.x)) +\n theme(axis.text.x = element_text(size = 10))\n\n p<- patchwork::wrap_plots(plotlist = plot_list, ncol = 1)\n return(p)\n}\n\n#' modified vlnplot\n#' @param object Seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param split.by Name of a metadata column to split plot by;\n#' @param idents Which classes to include in the plot (default is all)\n#' @param cols defining the color for each cell group\n#' @param show.text.y whther show y-axis text\n#' @param line.size line width in the violin plot\n#' @param pt.size size of the dots\n#' @param plot.margin adjust the white space between each plot\n#' @param ... pass any arguments to VlnPlot in Seurat\n#' @import ggplot2\n# #' @importFrom Seurat VlnPlot\n#'\nmodify_vlnplot<- function(object,\n features,\n idents = NULL,\n split.by = NULL,\n cols = NULL,\n show.text.y = TRUE,\n line.size = NULL,\n pt.size = 0,\n plot.margin = margin(0, 0, 0, 0, \"cm\"),\n ...) {\n options(warn=-1)\n p<- Seurat::VlnPlot(object, features = features, cols = cols, pt.size = pt.size, idents = idents, split.by = split.by, ... ) +\n xlab(\"\") + ylab(features) + ggtitle(\"\")\n p <- p + theme(text = element_text(size = 10)) + theme(axis.line = element_line(size=line.size)) +\n theme(axis.text.x = element_text(size = 10), axis.text.y = element_text(size = 8), axis.line.x = element_line(colour = 'black', size=line.size),axis.line.y = element_line(colour = 'black', size= line.size))\n # theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))\n p <- p + theme(legend.position = \"none\",\n plot.title= element_blank(),\n axis.title.x = element_blank(),\n axis.text.x = element_blank(),\n axis.ticks.x = element_blank(),\n axis.title.y = element_text(size = rel(1), angle = 0),\n axis.text.y = element_text(size = rel(1)),\n plot.margin = plot.margin ) +\n theme(axis.text.y = element_text(size = 8))\n\n p <- p + scale_y_continuous(labels = function(x) {\n idx0 = which(x == 0)\n if (length(idx0) > 0) {\n if (idx0 > 1) {\n c(rep(x = \"\", times = idx0-1), \"0\",rep(x = \"\", times = length(x) -2-idx0), x[length(x) - 1], \"\")\n } else {\n c(\"0\", rep(x = \"\", times = length(x)-3), x[length(x) - 1], \"\")\n }\n } else {\n c(as.character(min(x)), rep(x = \"\", times = length(x)-3), x[length(x) - 1], \"\")\n }\n })\n # #c(rep(x = \"\", times = length(x)-2), x[length(x) - 1], \"\"))\n\n p <- p + theme(element_line(size=line.size))\n\n if (!show.text.y) {\n p <- p + theme(axis.ticks.y=element_blank(), axis.text.y=element_blank())\n }\n return(p)\n}\n\n#' extract the max value of the y axis\n#' @param p ggplot object\n#' @importFrom ggplot2 ggplot_build\nextract_max<- function(p){\n ymax<- max(ggplot_build(p)$layout$panel_scales_y[[1]]$range$range)\n return(signif(ymax,2))\n}\n\n\n#' Bar plot for average gene expression\n#'\n#' Please check \\code{\\link{barplot_internal}}for detailed description of the arguments.\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param color.use defining the color for each condition/dataset\n#' @param group.by Name of one or more metadata columns to group (color) cells by\n#' (for example, orig.ident); pass 'ident' to group by identity class\n#' @param method methods for computing the average gene expression per cell group. By default = \"truncatedMean\", where a value should be assigned to 'trim;\n#' @param trim the fraction (0 to 0.5) of observations to be trimmed from each end of x before the mean is computed.\n#' @param split.by Name of a metadata column to split plot by;\n#' @param assay Name of assay to use, defaults to the active assay\n#' @param x.lab.rot whether do rotation for the x.tick.label\n#' @param ncol number of columns to show in the plot\n#' @param ... Extra parameters passed to barplot_internal\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\nbarPlot <- function(object, features, group.by = NULL, split.by = NULL, color.use = NULL, method = c(\"truncatedMean\", \"triMean\",\"median\"),trim = 0.1, assay = \"RNA\",\n x.lab.rot = FALSE, ncol = 1, ...) {\n method <- match.arg(method)\n if (is.null(group.by)) {\n labels = Seurat::Idents(object)\n } else {\n labels = object@meta.data[,group.by]\n }\n FunMean <- switch(method,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n triMean = triMean,\n median = function(x) median(x, na.rm = TRUE))\n if (packageVersion(\"Seurat\") < \"5.0.0\") {\n data.all <- object[[assay]]@data\n } else {\n data.all <- object[[assay]]$data\n }\n if (!is.null(split.by)) {\n group = object@meta.data[,split.by]\n group.levels <- levels(group)\n df <- data.frame()\n for (i in 1:length(group.levels)) {\n data = data.all[, group == group.levels[i], drop = FALSE]\n labels.use <- labels[group == group.levels[i]]\n dataavg <- aggregate(t(data[features, ]), list(labels.use) , FUN = FunMean)\n dataavg <- t(dataavg[,-1])\n colnames(dataavg) <- levels(labels.use)\n dataavg <- as.data.frame(dataavg)\n dataavg$gene = rownames(dataavg)\n df1 = reshape2::melt(dataavg, id.vars = c(\"gene\"))\n colnames(df1) <- c(\"gene\",\"labels\",\"value\")\n df1$condition = group.levels[i]\n df = rbind(df, df1)\n }\n df$labels <- factor(df$labels, levels = levels(labels))\n df$condition <- factor(df$condition, levels = group.levels)\n\n } else {\n data = data.all\n dataavg <- aggregate(t(data[features, ]), list(labels) , FUN = FunMean)\n dataavg <- t(dataavg[,-1])\n colnames(dataavg) <- levels(labels)\n dataavg$gene = rownames(dataavg)\n df1 = reshape2::melt(dataavg, id.vars = c(\"gene\"))\n colnames(df1) <- c(\"gene\",\"labels\",\"value\")\n df1$condition = df1[,\"labels\"]\n df = df1\n }\n gg <- list()\n for (i in 1:length(features)) {\n if (i < length(features)) {\n df.use = subset(df, gene == features[i])\n gg[[i]] <- barplot_internal(df.use, x = \"labels\", y = \"value\", fill = \"condition\",color.use = color.use,ylabel = features[i],remove.xtick = TRUE,x.lab.rot = x.lab.rot,...)\n }else {\n gg[[i]] <- barplot_internal(df.use, x = \"labels\", y = \"value\", fill = \"condition\",color.use = color.use,ylabel = features[i],remove.xtick = FALSE,x.lab.rot = x.lab.rot,...)\n }\n }\n\n p<- patchwork::wrap_plots(plotlist = gg, ncol = ncol)+ patchwork::plot_layout(guides = \"collect\")\n return(p)\n\n}\n\n#' Bar plot for dataframe\n#'\n#' @param df a dataframe\n#' @param x Name of one column to show on the x-axis\n#' @param y Name of one column to show on the y-axis\n#' @param fill Name of one column to compare the values\n#' @param color.use defining the color of bar plot;\n#' @param percent.y whether showing y-values as percentage\n#' @param width bar width\n#' @param legend.title Name of legend\n#' @param xlabel Name of x label\n#' @param ylabel Name of y label\n#' @param remove.xtick whether remove x tick\n#' @param title.name Name of the main title\n#' @param stat.add whether adding statistical test\n#' @param stat.method,label.x parameters for ggpubr::stat_compare_means\n#' @param show.legend Whether show the legend\n#' @param x.lab.rot Whether rorate the xtick labels\n#' @param size.text font size\n\n#' @import ggplot2\n#' @importFrom ggpubr stat_compare_means\n#'\n#' @return ggplot2 object\n#' @export\nbarplot_internal <- function(df, x = \"cellType\", y = \"value\", fill = \"condition\", legend.title = NULL, width=0.6, title.name = NULL,\n xlabel = NULL, ylabel = NULL, color.use = NULL,remove.xtick = FALSE,\n stat.add = FALSE, stat.method = \"wilcox.test\", percent.y = FALSE, label.x = 1.5,\n show.legend = TRUE, x.lab.rot = FALSE, size.text = 10) {\n\n gg <- ggplot(df, aes_string(x=x, y=y, fill = fill, color = fill)) + geom_bar(stat=\"identity\", width=width, position=position_dodge()) +\n theme_classic() + scale_x_discrete(limits = (levels(df$x))) + theme(axis.text.x = element_text(angle = 45, hjust = 1,size=10))\n\n gg <- gg + ylab(ylabel) + xlab(xlabel) + theme_classic() +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = size.text), axis.text = element_text(colour=\"black\"))\n if (!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values = alpha(color.use, alpha = 1), drop = FALSE)\n gg <- gg + scale_color_manual(values = alpha(color.use, alpha = 1), drop = FALSE) + guides(colour = FALSE)\n }\n if (stat.add) {\n gg <- gg + ggpubr::stat_compare_means(mapping = aes_string(group = fill), method = stat.method, label.x = label.x,\n label = \"p.format\", size = 3)\n }\n # if (show.mean) {\n # gg <- gg + stat_summary(fun.y=mean, geom=\"point\", shape=20, size=10, color=\"red\", fill=\"red\")\n # }\n if (remove.xtick) {\n gg <- gg + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.title.x=element_blank())\n }\n if (percent.y) {\n gg <- gg + scale_y_continuous(labels = scales::percent_format(accuracy = 1))\n }\n if (is.null(legend.title)) {\n gg <- gg + theme(legend.title = element_blank())\n } else {\n gg <- gg + guides(fill=guide_legend(legend.title))\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n if (x.lab.rot) {\n gg <- gg + theme(axis.text.x = element_text(angle = 45, hjust = 1, size=size.text))\n }\n gg\n return(gg)\n}\n\n\n########################################\n# spatial plot #\n########################################\n#' Visualize spatial cell groups\n#'\n#' This function takes a CellChat object as input, and then plot cell groups of interest.\n#'\n#' @param object cellchat object\n#' @param color.use defining the color for each cell group\n#' @param group.by Name of one metadata columns to group (color) cells. Default is the defined cell groups in CellChat object\n#' @param sample.use the sample name used for visualization, which should be the element in `object@meta$samples`.\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups\n#' @param idents.use a vector giving the index or the name of cell groups of interest\n#' @param alpha the transparency of individual spot\n#' @param shape.by the shape of individual spot\n#' @param title.name title name\n#' @param point.size the size of spots\n#' @param legend.size the size of legend\n#' @param legend.text.size the text size on the legend\n#' @param legend.position legend position\n#' @param ncol number of columns of the legend text\n#' @param byrow arrange the legend text byrow or not\n#' @return\n#' @export\n#'\n#' @examples\nspatialDimPlot <- function(object, color.use = NULL, group.by = NULL, sample.use = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL,\n alpha = 1, shape.by = 16, title.name = NULL, point.size = 2.4,\n legend.size = 5, legend.text.size = 8, legend.position = \"right\", ncol = 1, byrow = FALSE){\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[,group.by]\n labels <- factor(labels)\n }\n cells.level <- levels(labels)\n\n coordinates <- object@images$coordinates\n samples <- object@meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n\n if (is.null(sources.use) & is.null(targets.use)){\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n } else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use, \"Others\"))\n\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use, targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n\n gg <- ggplot(data = coordinates,aes(x=x_cent,y=y_cent,colour = labels))+\n geom_point(alpha = alpha, size = point.size, shape=shape.by) +\n scale_color_manual(values = color.use, na.value = \"grey90\") + theme(legend.position = legend.position) +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size)) + # , legend.key.size = unit(0.4, \"inches\")\n guides(color = guide_legend(override.aes = list(size=legend.size), ncol = ncol, byrow = byrow)) +\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n coord_fixed() + theme(aspect.ratio = 1)+ theme(legend.key = element_blank())\n gg <- gg + scale_y_reverse()\n\n if (!is.null(title.name)){\n gg <- gg + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))\n }\n return(gg)\n\n}\n\n\n#' A spatial feature plots\n#'\n#' This function takes a CellChat object as input, and then plot gene expression distribution over spots/cells on the image.\n#'\n#' @param object cellchat object\n#' @param features a char vector containing features to visualize. `features` can be genes or column names of `object@meta`.\n#' @param signaling signalling names to visualize\n#' @param pairLR.use a data frame consisting of one column named \"interaction_name\", defining the L-R pairs of interest\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param do.group set `do.group = TRUE` when only showing enriched signaling based on cell group-level communication; set `do.group = FALSE` when only showing enriched signaling based on individual cell-level communication\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param color.heatmap A character string or vector indicating the colormap option to use. It can be the avaibale color palette in brewer.pal() or viridis_pal() (e.g., \"Spectral\",\"viridis\")\n#' @param n.colors,direction n.colors: number of basic colors to generate from color palette; direction: Sets the order of colors in the scale. If 1, the default colors are used. If -1, the order of colors is reversed.\n#' @param do.binary,cutoff whether binarizing the expression using a given cutoff\n#' @param color.use defining the color for cells/spots expressing ligand only, expressing receptor only, expressing both ligand & receptor and cells/spots without expression of given ligands and receptors\n#' @param alpha the transparency of individual spot\n#' @param point.size the size of cell slot\n#' @param shape.by the shape of individual spot\n#' @param legend.size the size of legend\n#' @param legend.text.size the text size on the legend\n#' @param ncol number of columns if plotting multiple plots\n#' @param show.legend whether show each figure legend\n#' @param show.legend.combined whether show the figure legend for the last plot\n#' @return\n#' @export\n#'\n#' @examples\n\nspatialFeaturePlot <- function(object, features = NULL, signaling = NULL, pairLR.use = NULL, sample.use = NULL, enriched.only = TRUE,thresh = 0.05, do.group = TRUE,\n color.heatmap = \"Spectral\", n.colors = 8, direction = -1,\n do.binary = FALSE, cutoff = NULL, color.use = NULL, alpha = 1,\n point.size = 0.8, legend.size = 3, legend.text.size = 8, shape.by = 16, ncol = NULL,\n show.legend = TRUE, show.legend.combined = FALSE){\n data <- object@data\n meta <- object@meta\n coords <- object@images$coordinates\n samples <- meta$samples\n if (ncol(coords) == 2) {\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coords = coords\n coords[,1] = temp_coords[,2]\n coords[,2] = temp_coords[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n scales::viridis_pal(option = color.heatmap, direction = -1)(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n } else {\n colormap <- color.heatmap\n }\n\n if (is.null(features) & is.null(signaling) & is.null(pairLR.use)){\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)){\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)){\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)){\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n\n df <- data.frame(x = coords[, 1], y = coords[, 2])\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, enriched.only = enriched.only, thresh = thresh)\n feature.use <- res$geneLR\n } else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n } else {\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(paste0('There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.'))\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\",\"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex, object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex, object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n } else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) > 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n } else if (length(intersect(feature.use, colnames(meta))) > 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[ ,feature.use, drop = FALSE])\n } else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \",cutoff,\"to the values...\", '\\n')\n data.use[data.use <= cutoff] <- 0\n }\n\n\n if (is.null(ncol)) {\n if (length(feature.use) > 9) {\n ncol <- 4\n } else {\n ncol <- min(length(feature.use), 4)\n }\n }\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i, ]\n g <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = feature.data), alpha = alpha, size=point.size, shape=shape.by) +\n scale_colour_gradientn(colours = colormap, guide = guide_colorbar(title = NULL, ticks = T, label = T, barwidth = 0.5), na.value = \"grey90\") +\n theme(legend.position = \"right\") +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size), legend.key.size = unit(0.15, \"inches\")) + # , legend.key.size = unit(0.4, \"inches\")\n ggtitle(feature.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))+\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n theme(legend.key = element_blank())\n g <- g + coord_fixed() + theme(aspect.ratio = 1) + scale_y_reverse()\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (show.legend.combined & i == numFeature) {\n g <- g + theme(legend.position = \"right\", legend.key.height = grid::unit(0.15, \"in\"), legend.key.width = grid::unit(0.5, \"in\"), legend.title = element_blank(),legend.key = element_blank())\n }\n gg[[i]] <- g\n }\n if (ncol > 1) {\n gg <- patchwork::wrap_plots(gg, ncol = ncol)\n } else {\n gg <- gg[[1]]\n }\n\n } else {\n\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, enriched.only = enriched.only, thresh = thresh)\n # gene.pair = searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n # LR.pair <- gene.pair[res$interaction_name, c(\"ligand\",\"receptor\")]\n LR.pair <- object@LR$LRsig[res$interaction_name, c(\"ligand\",\"receptor\")]\n } else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n } else {\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(paste0('There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.'))\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\",\"receptor\")]\n } else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n # compute the expression of ligand or receptor\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL; rownames(dataR) <- geneR;\n # data.use <- matrix(0, nrow = nrow(dataL)*2, ncol = ncol(dataL))\n # data.use[seq_len(nrow(data.use)) %% 2 == 1, ] <- dataL\n # data.use[seq_len(nrow(data.use)) %% 2 == 0, ] <- dataR\n # rownames(data.use)[seq_len(nrow(data.use)) %% 2 == 1] <- geneL\n # rownames(data.use)[seq_len(nrow(data.use)) %% 2 == 0] <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n if (is.null(ncol)) {\n if (length(feature.use) > 9) {\n ncol <- 4\n } else {\n ncol <- min(length(feature.use), 4)\n }\n }\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \" )\n }\n gg <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i, ] > cutoff\n idx2 = dataR[i, ] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\",ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i],geneR[i],\"Both\",\"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i],geneR[i],\"Both\",\"None\")\n\n if (length(setdiff(levels(group), unique(group))) > 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group), unique(group)))\n }\n\n df$feature.data <- group\n g <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = feature.data), alpha = alpha, size=point.size, shape=shape.by) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size), legend.key.size = unit(0.15, \"inches\")) + # , legend.key.size = unit(0.4, \"inches\")\n guides(color = guide_legend(override.aes = list(size=legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))+\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n theme(legend.key = element_blank())\n g <- g + coord_fixed() + theme(aspect.ratio = 1) + scale_y_reverse()\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (show.legend.combined & i == numFeature) {\n g <- g + theme(legend.position = \"right\", legend.key.height = grid::unit(0.15, \"in\"), legend.key.width = grid::unit(0.5, \"in\"), legend.title = element_blank(),legend.key = element_blank())\n }\n gg[[i]] <- g\n }\n if (ncol > 1) {\n gg <- patchwork::wrap_plots(gg, ncol = ncol)\n } else {\n gg <- gg[[1]]\n }\n\n }\n return(gg)\n}\n"], ["/CellChat/R/modeling.R", "\n#' Compute the communication probability/strength between any interacting cell groups\n#'\n#' To further speed up on large-scale datasets, USER can downsample the data using the function 'subset' from Seurat package (e.g., pbmc.small <- subset(pbmc, downsample = 500)), or using the function `sketchData` from CellChat, in particular for the large cell clusters;\n#'\n#'\n#' @param object CellChat object\n#' @param type Methods for computing the average gene expression per cell group. By default = \"triMean\", producing fewer but stronger interactions;\n#' When setting `type = \"truncatedMean\"`, a value should be assigned to 'trim', producing more interactions.\n#' @param trim the fraction (0 to 0.25) of observations to be trimmed from each end of x before the mean is computed\n#' @param LR.use A subset of ligand-receptor interactions used in inferring communication network\n#' @param raw.use Whether use the raw data (i.e., `object@data.signaling`) or the smoothed data (i.e., `object@data.smooth`).\n#' Set raw.use = FALSE to use the projected data when analyzing single-cell data with shallow sequencing depth because the projected data could help to reduce the dropout effects of signaling genes, in particular for possible zero expression of subunits of ligands/receptors.\n#' @param population.size Whether consider the proportion of cells in each group across all sequenced cells.\n#' Set population.size = FALSE if analyzing sorting-enriched single cells, to remove the potential artifact of population size.\n#' Set population.size = TRUE if analyzing unsorted single-cell transcriptomes, with the reason that abundant cell populations tend to send collectively stronger signals than the rare cell populations.\n#'\n#' Parameters for spatial data analysis:\n#' @param distance.use Whether to use distance constraints to compute communication probability. Setting `distance.use = TRUE` indicates that the cell-cell communication probability is inversely proportional to the computed distance.\n#' Setting `distance.use = FALSE` will only filter out interactions between spatially distant regions, but not add distance constraints.\n#' @param interaction.range The maximum interaction/diffusion length of ligands (Unit: microns). This hard threshold is used to filter out the connections between spatially distant regions\n#' @param scale.distance A scale or normalization factor for the spatial distances when setting `distance.use = TRUE`. For example, scale.distance equals 1, 0.1, 0.01, 0.001, 0.11, or 0.011. We choose this values such that the minimum value of the scaled distances is in [1,2]. This value is not necessary when setting `distance.use = FALSE`.\n#'\n#' When comparing communication across different CellChat objects, the same scale factor should be used. For a single CellChat analysis, different scale factors will not affect the ranking of the signaling based on their interaction strength.\n#'\n#' @param k.min The minimum number of interacting cell pairs required for defining spatially proximal cell groups.\n#' @param contact.dependent Whether using the `contact-dependent` manner for inference signaling, that is determining interacting cell pairs by requiring cells to be in direct membrane-membrane contact. By default `contact.dependent = TRUE` when inferring contact-dependent and juxtacrine signaling (that is \"Cell-Cell Contact\" signaling classified in CellChatDB$interaction$annotation).\n#' If only focusing on `Secreted Signaling`, the `contact-dependent` manner will be not used except for setting `contact.dependent.forced = TRUE`.\n#' @param contact.range The interaction range (Unit: microns) to restrict the contact-dependent signaling when `contact.dependent = TRUE`.\n#' For spatial transcriptomics in a single-cell resolution, `contact.range` is approximately equal to the estimated cell diameter (i.e., the cell center-to-center distance), which means that contact-dependent and juxtacrine signaling can only happens when the two cells are contact to each other.\n#'\n#' Typically, `contact.range = 10`, which is a typical human cell size. However, for low-resolution spatial data such as 10X visium, it should be the cell center-to-center distance (i.e., `contact.range = 100` for visium data). The function `computeCellDistance` can compute the center-to-center distance.\n#'\n#' @param contact.knn.k Number of neighbors to restrict the contact-dependent signaling within the neatest neighbors when `contact.dependent = TRUE`. By default, CellChat uses `contact.range` to restrict the contact-dependent signaling; however, users can also provide a value of `contact.knn.k`, in order to determine interacting cell pairs based on the k-nearest neighbors (knn).\n#' For 10X visium, contact.knn.k = 6. For other spatial technologies, this value may be hard to determine because the sequenced cells/spots are usually not regularly arranged.\n#' @param do.symmetric Whether converting the adjacent matrix into symmetric one when determining spatially proximal cell groups. Default is TRUE, indicating that if adj(i,j) or adj(j,i) is zero, then both are zeros.\n#'\n#' @param contact.dependent.forced Whether forcing to use the `contact-dependent` manner for inference signaling for all L-R pairs including secreted signaling. Users can set `contact.dependent.forced = TRUE` if also preferring interactions within a contact manner for `Secreted Signaling`.\n#'\n#' @param nboot Threshold of p-values\n#' @param seed.use Set a random seed. By default, set the seed to 1.\n#' @param Kh Parameter in Hill function\n#' @param n Parameter in Hill function\n#'\n#'\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom stats aggregate\n#' @importFrom Matrix crossprod\n#' @importFrom utils txtProgressBar setTxtProgressBar\n#'\n#' @return A CellChat object with updated slot 'net':\n#'\n#' object@net$prob is the inferred communication probability (strength) array, where the first, second and third dimensions represent a source, target and ligand-receptor pair, respectively.\n#'\n#' USER can access all the inferred cell-cell communications using the function 'subsetCommunication(object)', which returns a data frame.\n#'\n#' object@net$pval is the corresponding p-values of each interaction\n#'\n#' @export\n#'\ncomputeCommunProb <- function(object, type = c(\"triMean\", \"truncatedMean\",\"thresholdedMean\", \"median\"), trim = 0.1, LR.use = NULL, raw.use = TRUE, population.size = FALSE,\n distance.use = TRUE, interaction.range = 250, scale.distance = 0.01, k.min = 10, contact.dependent = TRUE, contact.range = NULL, contact.knn.k = NULL, contact.dependent.forced = FALSE, do.symmetric = TRUE,\n nboot = 100, seed.use = 1L, Kh = 0.5, n = 1) {\n type <- match.arg(type)\n cat(type, \"is used for calculating the average gene expression per cell group.\", \"\\n\")\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n thresholdedMean = function(x) thresholdedMean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n if (raw.use) {\n data <- as.matrix(object@data.signaling)\n } else {\n data <- as.matrix(object@data.smooth)\n }\n if (is.null(LR.use)) {\n pairLR.use <- object@LR$LRsig\n } else {\n if (length(unique(LR.use$annotation)) > 1) {\n LR.use$annotation <- factor(LR.use$annotation, levels = c(\"Secreted Signaling\",\"ECM-Receptor\", \"Non-protein Signaling\", \"Cell-Cell Contact\"))\n LR.use <- LR.use[order(LR.use$annotation), , drop = FALSE]\n LR.use$annotation <- as.character(LR.use$annotation)\n }\n pairLR.use <- LR.use\n }\n complex_input <- object@DB$complex\n cofactor_input <- object@DB$cofactor\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n\n ptm = Sys.time()\n\n pairLRsig <- pairLR.use\n group <- object@idents\n geneL <- as.character(pairLRsig$ligand)\n geneR <- as.character(pairLRsig$receptor)\n nLR <- nrow(pairLRsig)\n numCluster <- nlevels(group)\n if (numCluster != length(unique(group))) {\n stop(\"Please check `unique(object@idents)` and ensure that the factor levels are correct!\n You may need to drop unused levels using 'droplevels' function. e.g.,\n `meta$labels = droplevels(meta$labels, exclude = setdiff(levels(meta$labels),unique(meta$labels)))`\")\n }\n\n data.use <- data/max(data)\n nC <- ncol(data.use)\n\n # compute the average expression per group\n data.use.avg <- aggregate(t(data.use), list(group), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n colnames(data.use.avg) <- levels(group)\n # compute the expression of ligand or receptor\n dataLavg <- computeExpr_LR(geneL, data.use.avg, complex_input)\n dataRavg <- computeExpr_LR(geneR, data.use.avg, complex_input)\n # take account into the effect of co-activation and co-inhibition receptors\n dataRavg.co.A.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avg, pairLRsig, type = \"A\")\n dataRavg.co.I.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avg, pairLRsig, type = \"I\")\n dataRavg <- dataRavg * dataRavg.co.A.receptor/dataRavg.co.I.receptor\n\n dataLavg2 <- t(replicate(nrow(dataLavg), as.numeric(table(group))/nC))\n dataRavg2 <- dataLavg2\n\n # compute the expression of agonist and antagonist\n index.agonist <- which(!is.na(pairLRsig$agonist) & pairLRsig$agonist != \"\")\n index.antagonist <- which(!is.na(pairLRsig$antagonist) & pairLRsig$antagonist != \"\")\n # quantify the communication probability\n\n # compute the spatial constraint\n if (object@options$datatype != \"RNA\") {\n data.spatial <- object@images$coordinates\n if (\"spatial.factors\" %in% names(object@images)) {\n ratio <- object@images$spatial.factors$ratio\n tol <- object@images$spatial.factors$tol\n } else {\n stop(\"`object@images$spatial.factors` is missing. Please update the object via `updateCellChat`! \\n\")\n }\n\n meta.t = data.frame(group = group, samples = object@meta$samples, row.names = rownames(object@meta))\n res <- computeRegionDistance(coordinates = data.spatial, meta = meta.t, interaction.range = interaction.range, ratio = ratio, tol = tol, k.min = k.min, contact.dependent = contact.dependent, contact.range = contact.range, contact.knn.k = contact.knn.k)\n d.spatial <- res$d.spatial # NaN if no nearby cell pairs\n adj.contact <- res$adj.contact # zeros if no nearby cell pairs\n if (distance.use) {\n print(paste0('>>> Run CellChat on spatial transcriptomics data using distances as constraints of the computed communication probability <<< [', Sys.time(),']'))\n d.spatial <- d.spatial * scale.distance\n diag(d.spatial) <- NaN\n d.min <- min(d.spatial, na.rm = TRUE)\n if (d.min < 1) {\n cat(\"The suggested minimum value of scaled distances is in [1,2], and the calculated value here is \", d.min,\"\\n\")\n stop(\"Please increase the value of `scale.distance` and use a value that is slighly smaller than \", format(1/d.min, digits = 2) ,\"\\n\")\n }\n P.spatial <- 1/d.spatial\n P.spatial[is.na(d.spatial)] <- 0\n diag(P.spatial) <- max(P.spatial) # if this value is 1, the self-connections will have more larger weight.\n d.spatial <- d.spatial/scale.distance # This is only for saving the data\n } else {\n print(paste0('>>> Run CellChat on spatial transcriptomics data without distance values as constraints of the computed communication probability <<< [', Sys.time(),']'))\n P.spatial <- matrix(1, nrow = numCluster, ncol = numCluster)\n P.spatial[is.na(d.spatial)] <- 0 # diagonal is 1\n }\n\n } else {\n print(paste0('>>> Run CellChat on sc/snRNA-seq data <<< [', Sys.time(),']'))\n d.spatial <- matrix(NaN, nrow = numCluster, ncol = numCluster)\n P.spatial <- matrix(1, nrow = numCluster, ncol = numCluster)\n adj.contact <- matrix(1, nrow = numCluster, ncol = numCluster)\n contact.dependent = FALSE; contact.dependent.forced = FALSE; contact.range = NULL; contact.knn.k = NULL;\n distance.use = NULL; interaction.range = NULL; ratio = NULL; tol = NULL; k.min = NULL;\n }\n\n if (object@options$datatype == \"RNA\") {\n nLR1 <- nLR\n } else {\n if (contact.dependent.forced == TRUE) {\n cat(\"Force to run CellChat in a `contact-dependent` manner for all L-R pairs including secreted signaling.\\n\")\n P.spatial <- P.spatial * adj.contact\n nLR1 <- nLR\n } else { # contact.dependent.forced == F\n if (contact.dependent == TRUE && length(unique(pairLRsig$annotation)) > 0) {\n if (all(unique(pairLRsig$annotation) %in% c(\"Cell-Cell Contact\"))) {\n cat(\"All the input L-R pairs are `Cell-Cell Contact` signaling. Run CellChat in a contact-dependent manner. \\n\")\n P.spatial <- P.spatial * adj.contact\n nLR1 <- nLR\n } else if (all(unique(pairLRsig$annotation) %in% c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\"))) {\n cat(\"Molecules of the input L-R pairs are diffusible. Run CellChat in a diffusion manner based on the `interaction.range`.\\n\")\n nLR1 <- nLR\n } else {\n cat(\"The input L-R pairs have both secreted signaling and contact-dependent signaling. Run CellChat in a contact-dependent manner for `Cell-Cell Contact` signaling, and in a diffusion manner based on the `interaction.range` for other L-R pairs. \\n\")\n nLR1 <- max(which(pairLRsig$annotation %in% c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\")))\n }\n } else { # contact.dependent == F or there is no `annotation` column in the database\n cat(\"Run CellChat in a diffusion manner based on the `interaction.range` for all L-R pairs. Setting `contact.dependent = TRUE` if preferring a contact-dependent manner for `Cell-Cell Contact` signaling. \\n\")\n nLR1 <- nLR\n }\n }\n }\n\n Prob <- array(0, dim = c(numCluster,numCluster,nLR))\n Pval <- array(0, dim = c(numCluster,numCluster,nLR))\n\n set.seed(seed.use)\n permutation <- replicate(nboot, sample.int(nC, size = nC))\n data.use.avg.boot <- my.sapply(\n X = 1:nboot,\n FUN = function(nE) {\n groupboot <- group[permutation[, nE]]\n data.use.avgB <- aggregate(t(data.use), list(groupboot), FUN = FunMean)\n data.use.avgB <- t(data.use.avgB[,-1])\n return(data.use.avgB)\n },\n simplify = FALSE\n )\n pb <- txtProgressBar(min = 0, max = nLR, style = 3, file = stderr())\n\n for (i in 1:nLR) {\n # ligand/receptor\n dataLR <- Matrix::crossprod(matrix(dataLavg[i,], nrow = 1), matrix(dataRavg[i,], nrow = 1))\n P1 <- dataLR^n/(Kh^n + dataLR^n)\n P1_Pspatial <- P1*P.spatial\n if (sum(P1_Pspatial) == 0) {\n Pnull = P1_Pspatial\n Prob[ , , i] <- Pnull\n p = 1\n Pval[, , i] <- matrix(p, nrow = numCluster, ncol = numCluster, byrow = FALSE)\n } else {\n if (i > nLR1) {\n P.spatial <- P.spatial * adj.contact\n }\n # agonist and antagonist\n if (is.element(i, index.agonist)) {\n data.agonist <- computeExpr_agonist(data.use = data.use.avg, pairLRsig, cofactor_input, index.agonist = i, Kh = Kh, n = n)\n P2 <- Matrix::crossprod(matrix(data.agonist, nrow = 1))\n } else {\n P2 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n if (is.element(i, index.antagonist)) {\n data.antagonist <- computeExpr_antagonist(data.use = data.use.avg, pairLRsig, cofactor_input, index.antagonist = i, Kh = Kh, n = n)\n P3 <- Matrix::crossprod(matrix(data.antagonist, nrow = 1))\n } else {\n P3 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n # number of cells\n if (population.size) {\n P4 <- Matrix::crossprod(matrix(dataLavg2[i,], nrow = 1), matrix(dataRavg2[i,], nrow = 1))\n } else {\n P4 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n # Pnull = P1*P2*P3*P4\n Pnull = P1*P2*P3*P4*P.spatial\n Prob[ , , i] <- Pnull\n\n Pnull <- as.vector(Pnull)\n\n #Pboot <- foreach(nE = 1:nboot) %dopar% {\n Pboot <- sapply(\n X = 1:nboot,\n FUN = function(nE) {\n data.use.avgB <- data.use.avg.boot[[nE]]\n dataLavgB <- computeExpr_LR(geneL[i], data.use.avgB, complex_input)\n dataRavgB <- computeExpr_LR(geneR[i], data.use.avgB, complex_input)\n # take account into the effect of co-activation and co-inhibition receptors\n dataRavgB.co.A.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avgB, pairLRsig[i, , drop = FALSE], type = \"A\")\n dataRavgB.co.I.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avgB, pairLRsig[i, , drop = FALSE], type = \"I\")\n dataRavgB <- dataRavgB * dataRavgB.co.A.receptor/dataRavgB.co.I.receptor\n dataLRB = Matrix::crossprod(dataLavgB, dataRavgB)\n P1.boot <- dataLRB^n/(Kh^n + dataLRB^n)\n # agonist and antagonist\n if (is.element(i, index.agonist)) {\n data.agonist <- computeExpr_agonist(data.use = data.use.avgB, pairLRsig, cofactor_input, index.agonist = i, Kh = Kh, n = n)\n P2.boot <- Matrix::crossprod(matrix(data.agonist, nrow = 1))\n } else {\n P2.boot <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n if (is.element(i, index.antagonist)) {\n data.antagonist <- computeExpr_antagonist(data.use = data.use.avgB, pairLRsig, cofactor_input, index.antagonist = i, Kh = Kh, n= n)\n P3.boot <- Matrix::crossprod(matrix(data.antagonist, nrow = 1))\n } else {\n P3.boot <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n if (population.size) {\n groupboot <- group[permutation[, nE]]\n dataLavg2B <- as.numeric(table(groupboot))/nC\n dataLavg2B <- matrix(dataLavg2B, nrow = 1)\n dataRavg2B <- dataLavg2B\n P4.boot = Matrix::crossprod(dataLavg2B, dataRavg2B)\n } else {\n P4.boot = matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n # Pboot = P1.boot*P2.boot*P3.boot*P4.boot\n Pboot = P1.boot*P2.boot*P3.boot*P4.boot*P.spatial\n return(as.vector(Pboot))\n }\n )\n Pboot <- matrix(unlist(Pboot), nrow=length(Pnull), ncol = nboot, byrow = FALSE)\n nReject <- rowSums(Pboot - Pnull > 0)\n p = nReject/nboot\n Pval[, , i] <- matrix(p, nrow = numCluster, ncol = numCluster, byrow = FALSE)\n }\n setTxtProgressBar(pb = pb, value = i)\n }\n close(con = pb)\n Pval[Prob == 0] <- 1\n dimnames(Prob) <- list(levels(group), levels(group), rownames(pairLRsig))\n dimnames(Pval) <- dimnames(Prob)\n net <- list(\"prob\" = Prob, \"pval\" = Pval)\n execution.time = Sys.time() - ptm\n object@options$run.time <- as.numeric(execution.time, units = \"secs\")\n\n object@options$parameter <- list(type.mean = type, trim = trim, raw.use = raw.use, population.size = population.size, nboot = nboot, seed.use = seed.use, Kh = Kh, n = n,\n distance.use = distance.use, interaction.range = interaction.range, ratio = ratio, tol = tol, k.min = k.min,\n contact.dependent = contact.dependent, contact.range = contact.range, contact.knn.k = contact.knn.k, contact.dependent.forced = contact.dependent.forced\n )\n if (object@options$datatype != \"RNA\") {\n object@images$distance <- d.spatial\n }\n object@net <- net\n print(paste0('>>> CellChat inference is done. Parameter values are stored in `object@options$parameter` <<< [', Sys.time(),']'))\n return(object)\n}\n\n\n#' Compute the communication probability on signaling pathway level by summarizing all related ligands/receptors\n#'\n#' @param object CellChat object\n#' @param net A list from object@net; If net = NULL, net = object@net\n#' @param pairLR.use A dataframe giving the ligand-receptor interactions; If pairLR.use = NULL, pairLR.use = object@LR$LRsig\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @return A CellChat object with updated slot 'netP':\n#'\n#' object@netP$prob is the communication probability array on signaling pathway level; USER can convert this array to a data frame using the function 'reshape2::melt()',\n#'\n#' e.g., `df.netP <- reshape2::melt(object@netP$prob, value.name = \"prob\"); colnames(df.netP)[1:3] <- c(\"source\",\"target\",\"pathway_name\")` or access all significant interactions using the function \\code{\\link{subsetCommunication}}\n#'\n#' object@netP$pathways list all the signaling pathways with significant communications.\n#'\n#' From version >= 1.1.0, pathways are ordered based on the total communication probabilities. NB: pathways with small total communication probabilities might be also very important since they might be specifically activated between only few cell types.\n#'\n#' @export\n#'\ncomputeCommunProbPathway <- function(object = NULL, net = NULL, pairLR.use = NULL, thresh = 0.05) {\n if (is.null(net)) {\n net <- object@net\n }\n if (is.null(pairLR.use)) {\n pairLR.use <- object@LR$LRsig\n }\n prob <- net$prob\n prob[net$pval > thresh] <- 0\n\n LR <- dimnames(prob)[[3]]\n LR.sig <- LR[apply(prob, 3, sum) != 0]\n\n pathways <- unique(pairLR.use$pathway_name)\n group <- factor(pairLR.use$pathway_name, levels = pathways)\n prob.pathways <- aperm(apply(prob, c(1, 2), by, group, sum), c(2, 3, 1))\n pathways.sig <- pathways[apply(prob.pathways, 3, sum) != 0]\n prob.pathways.sig <- prob.pathways[,,pathways.sig, drop = FALSE]\n idx <- sort(apply(prob.pathways.sig, 3, sum), decreasing=TRUE, index.return = TRUE)$ix\n pathways.sig <- pathways.sig[idx]\n prob.pathways.sig <- prob.pathways.sig[, , idx]\n\n if (is.null(object)) {\n netP = list(pathways = pathways.sig, prob = prob.pathways.sig)\n return(netP)\n } else {\n object@net$LRs <- LR.sig\n object@netP$pathways <- pathways.sig\n object@netP$prob <- prob.pathways.sig\n return(object)\n }\n}\n\n\n#' Calculate the aggregated network by counting the number of links or summarizing the communication probability\n#'\n#' @param object CellChat object\n#' @param sources.use,targets.use,signaling,pairLR.use Please check the description in function \\code{\\link{subsetCommunication}}\n#' @param remove.isolate whether removing the isolate cell groups without any interactions when applying \\code{\\link{subsetCommunication}}\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param return.object whether return an updated CellChat object\n#' @importFrom dplyr group_by summarize groups\n#' @importFrom stringr str_split\n#'\n#' @return Return an updated CellChat object:\n#'\n#' `object@net$count` is a matrix: rows and columns are sources and targets respectively, and elements are the number of interactions between any two cell groups. USER can convert a matrix to a data frame using the function `reshape2::melt()`\n#'\n#' `object@net$weight` is also a matrix containing the interaction weights between any two cell groups\n#'\n#' `object@net$sum` is deprecated. Use `object@net$weight`\n#'\n#' @export\n#'\naggregateNet <- function(object, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR.use = NULL, remove.isolate = TRUE, thresh = 0.05, return.object = TRUE) {\n net <- object@net\n if (is.null(sources.use) & is.null(targets.use) & is.null(signaling) & is.null(pairLR.use)) {\n prob <- net$prob\n pval <- net$pval\n pval[prob == 0] <- 1\n prob[pval >= thresh] <- 0\n net$count <- apply(prob > 0, c(1,2), sum)\n net$weight <- apply(prob, c(1,2), sum)\n net$weight[is.na(net$weight)] <- 0\n net$count[is.na(net$count)] <- 0\n } else {\n df.net <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.net$source_target <- paste(df.net$source, df.net$target, sep = \"_\")\n df.net2 <- df.net %>% group_by(source_target) %>% summarize(count = n(), .groups = 'drop')\n df.net3 <- df.net %>% group_by(source_target) %>% summarize(prob = sum(prob), .groups = 'drop')\n df.net2$prob <- df.net3$prob\n a <- stringr::str_split(df.net2$source_target, \"_\", simplify = T)\n df.net2$source <- as.character(a[, 1])\n df.net2$target <- as.character(a[, 2])\n cells.level <- levels(object@idents)\n if (remove.isolate) {\n message(\"Isolate cell groups without any interactions are removed. To block it, set `remove.isolate = FALSE`\")\n df.net2$source <- factor(df.net2$source, levels = cells.level[cells.level %in% unique(df.net2$source)])\n df.net2$target <- factor(df.net2$target, levels = cells.level[cells.level %in% unique(df.net2$target)])\n } else {\n df.net2$source <- factor(df.net2$source, levels = cells.level)\n df.net2$target <- factor(df.net2$target, levels = cells.level)\n }\n\n count <- tapply(df.net2[[\"count\"]], list(df.net2[[\"source\"]], df.net2[[\"target\"]]), sum)\n prob <- tapply(df.net2[[\"prob\"]], list(df.net2[[\"source\"]], df.net2[[\"target\"]]), sum)\n net$count <- count\n net$weight <- prob\n net$weight[is.na(net$weight)] <- 0\n net$count[is.na(net$count)] <- 0\n }\n if (return.object) {\n object@net <- net\n return(object)\n } else {\n return(net)\n }\n\n}\n\n\n#' Compute averaged expression values for each cell group\n#'\n#' @param object CellChat object\n#' @param features a char vector giving the used features. default use all features\n#' @param group.by cell group information; default is `object@idents` when input is a single object and `object@idents$joint` when input is a merged object; otherwise it should be one of the column names of the meta slot\n#' @param type methods for computing the average gene expression per cell group.\n#'\n#' By default = \"triMean\", defined as a weighted average of the distribution's median and its two quartiles (https://en.wikipedia.org/wiki/Trimean);\n#'\n#' When setting `type = \"truncatedMean\"`, a value should be assigned to 'trim'. See the function `base::mean`.\n#'\n#' @param trim the fraction (0 to 0.25) of observations to be trimmed from each end of x before the mean is computed.\n#' @param slot.name the data in the slot.name to use\n#' @param data.use a customed data matrix. Default: data.use = NULL and the expression matrix in the 'slot.name' is used\n#'\n#' @return Returns a matrix with genes as rows, cell groups as columns.\n\n#' @export\n#'\ncomputeAveExpr <- function(object, features = NULL, group.by = NULL, type = c(\"triMean\", \"truncatedMean\", \"median\"), trim = NULL,\n slot.name = c(\"data.signaling\", \"data\"), data.use = NULL) {\n type <- match.arg(type)\n slot.name <- match.arg(slot.name)\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n if (is.null(data.use)) {\n data.use <- slot(object, slot.name)\n }\n if (is.null(features)) {\n features.use <- row.names(data.use)\n } else {\n features.use <- intersect(features, row.names(data.use))\n }\n data.use <- data.use[features.use, , drop = FALSE]\n data.use <- as.matrix(data.use)\n\n if (is.null(group.by)) {\n labels <- object@idents\n if (!is.factor(labels)) {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n # compute the average expression per group\n data.use.avg <- aggregate(t(data.use), list(labels), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n rownames(data.use.avg) <- features.use\n colnames(data.use.avg) <- levels(labels)\n return(data.use.avg)\n}\n\n\n\n#' Compute the expression of complex in individual cells using geometric mean\n#' @param complex_input the complex_input from CellChatDB\n#' @param data.use data matrix (row are genes and columns are cells or cell groups)\n#' @param complex the names of complex\n#' @return\n#' @importFrom dplyr select starts_with\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @export\ncomputeExpr_complex <- function(complex_input, data.use, complex) {\n Rsubunits <- complex_input[complex,] %>% dplyr::select(starts_with(\"subunit\"))\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n data.complex = my.sapply(\n X = 1:nrow(Rsubunits),\n FUN = function(x) {\n RsubunitsV <- unlist(Rsubunits[x,], use.names = F)\n RsubunitsV <- RsubunitsV[RsubunitsV != \"\"]\n return(geometricMean(data.use[RsubunitsV, , drop = FALSE]))\n }\n )\n data.complex <- t(data.complex)\n return(data.complex)\n}\n\n# Compute the average expression of complex per cell group using geometric mean\n# @param complex_input the complex_input from CellChatDB\n# @param data.use data matrix (rows are genes and columns are cells)\n# @param complex the names of complex\n# @param group a factor defining the cell groups\n# @param FunMean the function for computing mean expression per group\n# @return\n# @importFrom dplyr select starts_with\n# @importFrom future nbrOfWorkers\n# @importFrom future.apply future_sapply\n# @importFrom pbapply pbsapply\n# #' @export\n.computeExprGroup_complex <- function(complex_input, data.use, complex, group, FunMean) {\n Rsubunits <- complex_input[complex,] %>% dplyr::select(starts_with(\"subunit\"))\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n data.complex = my.sapply(\n X = 1:nrow(Rsubunits),\n FUN = function(x) {\n RsubunitsV <- unlist(Rsubunits[x,], use.names = F)\n RsubunitsV <- RsubunitsV[RsubunitsV != \"\"]\n RsubunitsV <- intersect(RsubunitsV, rownames(data.use))\n if (length(RsubunitsV) > 1) {\n data.avg <- aggregate(t(data.use[RsubunitsV, ,drop = FALSE]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n } else if (length(RsubunitsV) == 1) {\n data.avg <- aggregate(matrix(data.use[RsubunitsV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n } else {\n data.avg = matrix(0, nrow = 1, ncol = length(unique(group)))\n }\n return(geometricMean(data.avg))\n }\n )\n data.complex <- t(data.complex)\n return(data.complex)\n}\n\n#' Compute the expression of ligands or receptors using geometric mean\n#' @param geneLR a char vector giving a set of ligands or receptors\n#' @param data.use data matrix (row are genes and columns are cells or cell groups)\n#' @param complex_input the complex_input from CellChatDB\n# #' @param group a factor defining the cell groups; If NULL, compute the expression of ligands or receptors in individual cells; otherwise, compute the average expression of ligands or receptors per cell group\n# #' @param FunMean the function for computing average expression per cell group\n#' @return\n#' @export\ncomputeExpr_LR <- function(geneLR, data.use, complex_input){\n nLR <- length(geneLR)\n numCluster <- ncol(data.use)\n index.singleL <- which(geneLR %in% rownames(data.use))\n dataL1avg <- data.use[geneLR[index.singleL],]\n dataLavg <- matrix(nrow = nLR, ncol = numCluster)\n dataLavg[index.singleL,] <- dataL1avg\n index.complexL <- setdiff(1:nLR, index.singleL)\n if (length(index.complexL) > 0) {\n complex <- geneLR[index.complexL]\n data.complex <- computeExpr_complex(complex_input, data.use, complex)\n dataLavg[index.complexL,] <- data.complex\n }\n return(dataLavg)\n}\n\n\n#' Modeling the effect of coreceptor on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig a data frame giving ligand-receptor interactions\n#' @param type when type == \"A\", computing expression of co-activation receptor; when type == \"I\", computing expression of co-inhibition receptor.\n#' @return\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @export\ncomputeExpr_coreceptor <- function(cofactor_input, data.use, pairLRsig, type = c(\"A\", \"I\")) {\n type <- match.arg(type)\n if (type == \"A\") {\n coreceptor.all = pairLRsig$co_A_receptor\n } else if (type == \"I\"){\n coreceptor.all = pairLRsig$co_I_receptor\n }\n index.coreceptor <- which(!is.na(coreceptor.all) & coreceptor.all != \"\")\n if (length(index.coreceptor) > 0) {\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n coreceptor <- coreceptor.all[index.coreceptor]\n coreceptor.ind <- cofactor_input[coreceptor, grepl(\"cofactor\" , colnames(cofactor_input) )]\n data.coreceptor.ind = my.sapply(\n X = 1:nrow(coreceptor.ind),\n FUN = function(x) {\n coreceptor.indV <- unlist(coreceptor.ind[x,], use.names = F)\n coreceptor.indV <- coreceptor.indV[coreceptor.indV != \"\"]\n coreceptor.indV <- intersect(coreceptor.indV, rownames(data.use))\n if (length(coreceptor.indV) == 1) {\n return(1 + data.use[coreceptor.indV, ])\n } else if (length(coreceptor.indV) > 1) {\n return(apply(1 + data.use[coreceptor.indV, ], 2, prod))\n } else {\n return(matrix(1, nrow = 1, ncol = ncol(data.use)))\n }\n }\n )\n data.coreceptor.ind <- t(data.coreceptor.ind)\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = ncol(data.use))\n data.coreceptor[index.coreceptor,] <- data.coreceptor.ind\n } else {\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = ncol(data.use))\n }\n return(data.coreceptor)\n}\n\n# Modeling the effect of coreceptor on the ligand-receptor interaction\n#\n# @param data.use data matrix\n# @param cofactor_input the cofactor_input from CellChatDB\n# @param pairLRsig a data frame giving ligand-receptor interactions\n# @param type when type == \"A\", computing expression of co-activation receptor; when type == \"I\", computing expression of co-inhibition receptor.\n# @param group a factor defining the cell groups\n# @param FunMean the function for computing mean expression per group\n# @return\n# @importFrom future nbrOfWorkers\n# @importFrom future.apply future_sapply\n# @importFrom pbapply pbsapply\n# #' @export\n.computeExprGroup_coreceptor <- function(cofactor_input, data.use, pairLRsig, type = c(\"A\", \"I\"), group, FunMean) {\n type <- match.arg(type)\n if (type == \"A\") {\n coreceptor.all = pairLRsig$co_A_receptor\n } else if (type == \"I\"){\n coreceptor.all = pairLRsig$co_I_receptor\n }\n index.coreceptor <- which(!is.na(coreceptor.all) & coreceptor.all != \"\")\n if (length(index.coreceptor) > 0) {\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n coreceptor <- coreceptor.all[index.coreceptor]\n coreceptor.ind <- cofactor_input[coreceptor, grepl(\"cofactor\" , colnames(cofactor_input) )]\n data.coreceptor.ind = my.sapply(\n X = 1:nrow(coreceptor.ind),\n FUN = function(x) {\n coreceptor.indV <- unlist(coreceptor.ind[x,], use.names = F)\n coreceptor.indV <- coreceptor.indV[coreceptor.indV != \"\"]\n coreceptor.indV <- intersect(coreceptor.indV, rownames(data.use))\n if (length(coreceptor.indV) > 1) {\n data.avg <- aggregate(t(data.use[coreceptor.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n return(apply(1 + data.avg, 2, prod))\n # return(1 + apply(data.avg, 2, mean))\n } else if (length(coreceptor.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[coreceptor.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n return(1 + data.avg)\n } else {\n return(matrix(1, nrow = 1, ncol = length(unique(group))))\n }\n }\n )\n data.coreceptor.ind <- t(data.coreceptor.ind)\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = length(unique(group)))\n data.coreceptor[index.coreceptor,] <- data.coreceptor.ind\n } else {\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = length(unique(group)))\n }\n\n return(data.coreceptor)\n}\n\n#' Modeling the effect of agonist on the ligand-receptor interaction\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n#' @param group a factor defining the cell groups\n#' @param index.agonist the index of agonist in the database\n#' @param Kh a parameter in Hill function\n#' @param FunMean the function for computing mean expression per group\n#' @param n Hill coefficient\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExprGroup_agonist <- function(data.use, pairLRsig, cofactor_input, group, index.agonist, Kh, FunMean, n) {\n agonist <- pairLRsig$agonist[index.agonist]\n agonist.ind <- cofactor_input[agonist, grepl(\"cofactor\" , colnames(cofactor_input))]\n agonist.indV <- unlist(agonist.ind, use.names = F)\n agonist.indV <- agonist.indV[agonist.indV != \"\"]\n agonist.indV <- intersect(agonist.indV, rownames(data.use))\n if (length(agonist.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[agonist.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.agonist <- 1 + data.avg^n/(Kh^n + data.avg^n)\n } else if (length(agonist.indV) > 1) {\n data.avg <- aggregate(t(data.use[agonist.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.agonist <- apply(1 + data.avg^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n data.agonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n }\n return(data.agonist)\n}\n\n#' Modeling the effect of antagonist on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n#' @param group a factor defining the cell groups\n#' @param index.antagonist the index of antagonist in the database\n#' @param Kh a parameter in Hill function\n#' @param n Hill coefficient\n#' @param FunMean the function for computing mean expression per group\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExprGroup_antagonist <- function(data.use, pairLRsig, cofactor_input, group, index.antagonist, Kh, FunMean, n) {\n antagonist <- pairLRsig$antagonist[index.antagonist]\n antagonist.ind <- cofactor_input[antagonist, grepl( \"cofactor\" , colnames(cofactor_input) )]\n antagonist.indV <- unlist(antagonist.ind, use.names = F)\n antagonist.indV <- antagonist.indV[antagonist.indV != \"\"]\n antagonist.indV <- intersect(antagonist.indV, rownames(data.use))\n if (length(antagonist.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[antagonist.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.antagonist <- Kh^n/(Kh^n + data.avg^n)\n } else if (length(antagonist.indV) > 1) {\n data.avg <- aggregate(t(data.use[antagonist.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.antagonist <- apply(Kh^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n data.antagonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n }\n return(data.antagonist)\n}\n\n\n#' Modeling the effect of agonist on the ligand-receptor interaction\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n# #' @param group a factor defining the cell groups\n#' @param index.agonist the index of agonist in the database\n#' @param Kh a parameter in Hill function\n# #' @param FunMean the function for computing mean expression per group\n#' @param n Hill coefficient\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExpr_agonist <- function(data.use, pairLRsig, cofactor_input, index.agonist, Kh, n) {\n agonist <- pairLRsig$agonist[index.agonist]\n agonist.ind <- cofactor_input[agonist, grepl(\"cofactor\" , colnames(cofactor_input))]\n agonist.indV <- unlist(agonist.ind, use.names = F)\n agonist.indV <- agonist.indV[agonist.indV != \"\"]\n agonist.indV <- intersect(agonist.indV, rownames(data.use))\n if (length(agonist.indV) == 1) {\n # data.avg <- aggregate(matrix(data.use[agonist.indV,], ncol = 1), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[agonist.indV,, drop = FALSE]\n data.agonist <- 1 + data.avg^n/(Kh^n + data.avg^n)\n } else if (length(agonist.indV) > 1) {\n # data.avg <- aggregate(t(data.use[agonist.indV,]), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[agonist.indV,, drop = FALSE]\n data.agonist <- apply(1 + data.avg^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n # data.agonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n data.agonist = matrix(1, nrow = 1, ncol = ncol(data.use))\n }\n return(data.agonist)\n}\n\n#' Modeling the effect of antagonist on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n# #' @param group a factor defining the cell groups\n#' @param index.antagonist the index of antagonist in the database\n#' @param Kh a parameter in Hill function\n#' @param n Hill coefficient\n# #' @param FunMean the function for computing mean expression per group\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExpr_antagonist <- function(data.use, pairLRsig, cofactor_input, index.antagonist, Kh, n) {\n antagonist <- pairLRsig$antagonist[index.antagonist]\n antagonist.ind <- cofactor_input[antagonist, grepl( \"cofactor\" , colnames(cofactor_input) )]\n antagonist.indV <- unlist(antagonist.ind, use.names = F)\n antagonist.indV <- antagonist.indV[antagonist.indV != \"\"]\n antagonist.indV <- intersect(antagonist.indV, rownames(data.use))\n if (length(antagonist.indV) == 1) {\n # data.avg <- aggregate(matrix(data.use[antagonist.indV,], ncol = 1), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[antagonist.indV,, drop = FALSE]\n data.antagonist <- Kh^n/(Kh^n + data.avg^n)\n } else if (length(antagonist.indV) > 1) {\n # data.avg <- aggregate(t(data.use[antagonist.indV,]), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[antagonist.indV,, drop = FALSE]\n data.antagonist <- apply(Kh^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n # data.antagonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n data.antagonist = matrix(1, nrow = 1, ncol = ncol(data.use))\n }\n return(data.antagonist)\n}\n\n\n#' Compute the geometric mean\n#' @param x a numeric vector\n#' @param na.rm whether remove na\n#' @return\n#' @export\ngeometricMean <- function(x,na.rm=TRUE){\n if (is.null(nrow(x))) {\n exp(mean(log(x),na.rm=na.rm))\n } else {\n exp(apply(log(x),2,mean,na.rm=na.rm))\n }\n}\n\n\n#' Compute the Tukey's trimean\n#' @param x a numeric vector\n#' @param na.rm whether remove na\n#' @return\n#' @importFrom stats quantile\n#' @export\ntriMean <- function(x, na.rm = TRUE) {\n mean(stats::quantile(x, probs = c(0.25, 0.50, 0.50, 0.75), na.rm = na.rm))\n}\n\n#' Compute the average expression per cell group when the percent of expressing cells per cell group larger than a threshold\n#' @param x a numeric vector\n#' @param trim the percent of expressing cells per cell group to be considered as zero\n#' @param na.rm whether remove na\n#' @return\n#' @importFrom Matrix nnzero\n# #' @export\nthresholdedMean <- function(x, trim = 0.1, na.rm = TRUE) {\n percent <- Matrix::nnzero(x)/length(x)\n if (percent < trim) {\n return(0)\n } else {\n return(mean(x, na.rm = na.rm))\n }\n}\n\n#' Filter cell-cell communication if there are only few number of cells in certain cell groups or inconsistent cell-cell communication across samples\n#'\n#' @param object CellChat object\n#' @param min.cells The minmum number of cells required in each cell group for cell-cell communication\n#' @param min.samples The minmum number of samples required for consistent cell-cell communication across samples (that is an interaction present in at least `min.samples` samples) when mutiple samples/replicates/batches are merged as an input for CellChat analysis.\n#' @param rare.keep Whether to keep the interactions associated with the rare populations when min.samples >= 2. When a rare population is identified in the merged samples (say 15 cells in this rare population from two samples), it is likely to filter out the interactions associated with this rare population when setting min.samples >= 2. Setting `rare.keep = TRUE` to retain the identified interactions associated with this rare population.\n#' @param nonFilter.keep Whether to keep the non-filtered cell-cell communication in the CellChat object. This is useful for avoiding re-running `computeCommunProb` if you want to adjust the parameters when running `filterCommunication`.\n#' @return CellChat object with an updated slot net\n#' @export\n#'\nfilterCommunication <- function(object, min.cells = 10, min.samples = NULL, rare.keep = FALSE, nonFilter.keep = FALSE) {\n net <- object@net\n if (nonFilter.keep == TRUE) {\n cat(\"The non-filtered cell-cell communication is stored in `object@net$prob.nonFilter` and `object@net$pval.nonFilter`. \\n\")\n object@net$prob.nonFilter <- net$prob\n object@net$pval.nonFilter <- net$pval\n }\n num.interaction0 <- sum(net$prob > 0)\n cell.excludes <- which(as.numeric(table(object@idents)) <= min.cells)\n if (length(cell.excludes) > 0) {\n cat(\"The cell-cell communication related with the following cell groups are excluded due to the few number of cells: \", toString(levels(object@idents)[cell.excludes]), \"!\",'\\t')\n net$prob[cell.excludes,,] <- 0\n net$prob[,cell.excludes,] <- 0\n num.interaction1 <- sum(net$prob > 0)\n pct.dicrease <- scales::percent((num.interaction0-num.interaction1)/num.interaction0, accuracy = .1)\n cat(paste0(pct.dicrease, \" interactions are removed!\",'\\n'))\n } else {\n num.interaction1 <- num.interaction0\n }\n\n sample.info <- object@meta$samples\n sample.id <- levels(sample.info)\n if (is.null(min.samples)) {\n min.samples <- 1\n } else if (min.samples > length(sample.id)) {\n stop(paste0(\"There are only \", length(sample.id), \" samples in the data. Please change the value of `min.samples`! \"))\n }\n if (length(sample.id) >= 2 & min.samples >= 2) {\n if (object@options$parameter$raw.use == TRUE) {\n data <- as.matrix(object@data.signaling)\n } else {\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n stop(\"`object@data.smooth` is missing. Please update the CellChat object via `updateCellChat`! \\n\")\n }\n data <- as.matrix(object@data.smooth)\n }\n data.use <- data/max(data)\n group <- object@idents\n type <- object@options$parameter$type.mean\n trim <- object@options$parameter$trim\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n thresholdedMean = function(x) thresholdedMean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n LR <- dimnames(net$prob)[[3]]\n idx.nonzero <- which(apply(net$prob, 3, sum) != 0)\n LR.nonzero <- LR[idx.nonzero] # only examine the L-R pairs with nonzero communication probabilities.\n\n interaction_input <- object@DB$interaction\n complex_input <- object@DB$complex\n geneIfo <- object@DB$geneInfo\n idx <- match(LR.nonzero, interaction_input$interaction_name)\n geneL <- as.character(interaction_input$ligand[idx])\n geneR <- as.character(interaction_input$receptor[idx])\n\n geneLR <- c(unique(geneL), unique(geneR))\n geneLR <- extractGeneSubset(geneLR, complex_input, geneIfo)\n data.use <- data.use[rownames(data.use) %in% geneLR, ]\n\n score.LR <- array(0, dim = c(nlevels(group),nlevels(group),length(LR.nonzero), length(sample.id)))\n LR.nonzero.all <- c()\n cell.excludes.sample <- c()\n for (i in 1:length(sample.id)) {\n cell.use <- which(sample.info == sample.id[i])\n group.use <- group[cell.use]\n group.use <- droplevels(group.use)\n # get the rare populations with few cells in each sample\n cell.excludes.sample.i <- which(as.numeric(table(object@idents[cell.use])) <= min.cells)\n cell.excludes.sample <- c(cell.excludes.sample, cell.excludes.sample.i)\n # compute average expression per cell group\n data.use.i <- data.use[, cell.use]\n data.use.avg <- aggregate(t(data.use.i), list(group.use), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n group.exist <- which(levels(group) %in% unique(group.use))\n if (length(group.exist) < nlevels(group)) {\n data.use.avg.temp <- matrix(0, nrow = nrow(data.use), ncol = nlevels(group))\n data.use.avg.temp[ , group.exist] <- data.use.avg\n rownames(data.use.avg.temp) <- rownames(data.use.avg)\n data.use.avg <- data.use.avg.temp\n }\n colnames(data.use.avg) <- levels(group)\n # compute the average expression of ligand or receptor in each cell group\n dataLavg <- computeExpr_LR(geneL, data.use.avg, complex_input)\n dataRavg <- computeExpr_LR(geneR, data.use.avg, complex_input)\n # compute the interaction scores for each ligand-receptor pair based on their expression\n for (jj in 1:length(LR.nonzero)) { # It is not good to use parallel here because it will change the order of LR\n score.LR[,,jj,i] <- Matrix::crossprod(matrix(dataLavg[jj, ], nrow = 1), matrix(dataRavg[jj, ], nrow = 1))\n }\n if (length(cell.excludes.sample.i) > 0) {\n cat(paste0(\"The number of cells of the following cell groups in \", sample.id[i], \" sample are less than \", min.cells, \" cells: \",toString(levels(object@idents)[cell.excludes.sample.i]), \"!\",'\\n'))\n score.LR[cell.excludes.sample.i, , , i] <- 0\n score.LR[ ,cell.excludes.sample.i, , i] <- 0\n }\n #LR.nonzero.all <- c(LR.nonzero.all, LR.nonzero[apply(score.LR[ , , , i], 3, sum) != 0])\n }\n #LR.nonzero.jointOnly <- setdiff(LR.nonzero, unique(LR.nonzero.all))\n\n # get the excluded cell groups that are not observed in the merged data, which is very possible for rare populations\n cell.excludes.sample <- unique(cell.excludes.sample)\n if (length(cell.excludes.sample) > 0) {\n cell.excludes.sample <- setdiff(cell.excludes.sample, cell.excludes)\n }\n\n score.LR[score.LR > 0] <- 1 # binarize the interaction score\n score.LR.consitent <- array(0, dim = c(nlevels(group),nlevels(group),length(LR.nonzero)))\n LR.inconsitent <- c()\n for (jj in 1:length(LR.nonzero)) {\n score.LR.sum <- apply(score.LR[ , , jj, ], c(1,2), sum) # elements 2 and 1 means consistent and inconsistent interactions across samples, respectively.\n # set communication probability to be zero for inconsistent interactions across samples\n if (sum((score.LR.sum > 0) * (score.LR.sum < min.samples)) > 0) {\n #LR.inconsitent <- c(LR.inconsitent, LR.nonzero[jj])\n score.LR.consitent <- (score.LR.sum >= min.samples) * 1\n if (rare.keep == TRUE & length(cell.excludes.sample) > 0) {\n score.LR.consitent[cell.excludes.sample, ] <- 1\n score.LR.consitent[ ,cell.excludes.sample] <- 1\n }\n net$prob[ , , LR.nonzero[jj]] <- net$prob[ , , LR.nonzero[jj]] * score.LR.consitent\n }\n }\n num.interaction2 <- sum(net$prob > 0)\n pct.dicrease <- scales::percent((num.interaction1-num.interaction2)/num.interaction1, accuracy = .1)\n cat(paste0(pct.dicrease, \" interactions are removed due to their inconsistence across \", min.samples, \" samples!\",'\\n'))\n }\n\n object@net <- net\n return(object)\n}\n\n\n#' Identify all the significant interactions (L-R pairs) from some cell groups to other cell groups\n#'\n#' @param object CellChat object\n#' @param from a vector giving the index or the name of source cell groups\n#' @param to a corresponding vector giving the index or the name of target cell groups. Note: The length of 'from' and 'to' must be the same, giving the corresponding pair of cell groups for communication.\n#' @param bidirection whether show the bidirectional communication, i.e., both 'from'->'to' and 'to'->'from'.\n#' @param pair.only whether only return ligand-receptor pairs without pathway names and communication strength\n#' @param pairLR.use0 ligand-receptor pairs to use; default is all the significant interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @return\n#' @export\n#'\nidentifyEnrichedInteractions <- function(object, from, to, bidirection = FALSE, pair.only = TRUE, pairLR.use0 = NULL, thresh = 0.05){\n pairwiseLR <- object@net$pairwiseRank\n if (is.null(pairwiseLR)) {\n stop(\"The interactions between pairwise cell groups have not been extracted!\n Please first run `object <- rankNetPairwise(object)`\")\n }\n group.names.all <- names(pairwiseLR)\n if (!is.numeric(from)) {\n from <- match(from, group.names.all)\n if (sum(is.na(from)) > 0) {\n message(\"Some input cell group names in 'from' do not exist!\")\n from <- from[!is.na(from)]\n }\n }\n if (!is.numeric(to)) {\n to <- match(to, group.names.all)\n if (sum(is.na(to)) > 0) {\n message(\"Some input cell group names in 'to' do not exist!\")\n to <- to[!is.na(to)]\n }\n }\n if (length(from) != length(to)) {\n stop(\"The length of 'from' and 'to' must be the same!\")\n }\n if (bidirection) {\n from2 <- c(from, to)\n to <- c(to, from)\n from <- from2\n }\n if (is.null(pairLR.use0)) {\n k <- 0\n pairLR.use0 <- list()\n for (i in 1:length(from)){\n pairwiseLR_ij <- pairwiseLR[[from[i]]][[to[i]]]\n idx <- pairwiseLR_ij$pval < thresh\n if (length(idx) > 0) {\n k <- k +1\n pairLR.use0[[k]] <- pairwiseLR_ij[idx,]\n }\n }\n pairLR.use0 <- do.call(rbind, pairLR.use0)\n }\n\n k <- 0\n pval <- matrix(nrow = length(rownames(pairLR.use0)), ncol = length(from))\n prob <- pval\n group.names <- c()\n for (i in 1:length(from)) {\n k <- k+1\n pairwiseLR_ij <- pairwiseLR[[from[i]]][[to[i]]]\n pairwiseLR_ij <- pairwiseLR_ij[rownames(pairLR.use0),]\n pval_ij <- pairwiseLR_ij$pval\n prob_ij <- pairwiseLR_ij$prob\n pval_ij[pval_ij > 0.05] = 1\n pval_ij[pval_ij > 0.01 & pval_ij <= 0.05] = 2\n pval_ij[pval_ij <= 0.01] = 3\n prob_ij[pval_ij ==1] <- 0\n pval[,k] <- pval_ij\n prob[,k] <- prob_ij\n group.names <- c(group.names, paste(group.names.all[from[i]], group.names.all[to[i]], sep = \" - \"))\n }\n prob[which(prob == 0)] <- NA\n # remove rows that are entirely NA\n pval <- pval[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n pairLR.use0 <- pairLR.use0[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n prob <- prob[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n if (pair.only) {\n pairLR.use0 <- dplyr::select(pairLR.use0, ligand, receptor)\n }\n return(pairLR.use0)\n}\n\n\n#' Compute the region distance based on the spatial locations of each splot/cell of the spatial transcriptomics\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param meta a data frame including at least two columns named `group` and `samples`. `meta$group` is a factor vector defining the regions/labels of each cell/spot. `meta$samples` is a factor vector defining the sample labels of each dataset.\n#' @param interaction.range The maximum interaction/diffusion range of ligands. This hard threshold is used to filter out the connections between spatially distant regions\n#' @param ratio a numerical vector giving the conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns).\n#'\n#' For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates.\n#' For 10X visium, it is the ratio of the theoretical spot size (i.e., 65um) over the number of pixels that span the diameter of a theoretical spot size in the full-resolution image (i.e., 'spot.size.fullres' in the 'scalefactors_json.json' file).\n#' @param tol a numerical vector giving the tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um.\n#'\n#' For example, for 10X visium, `tol` can be set as `65/2`; for slide-seq, `tol` can be set as `10/2`.\n#' If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance.\n#' @param k.min the minimum number of interacting cell pairs required for defining adjacent cell groups\n#' @param contact.dependent Whether determining spatially proximal cell groups based on either the contact.range or the k-nearest neighbors (knn). By default `contact.dependent = TRUE` when inferring contact-dependent and juxtacrine signaling (including ECM-Receptor and Cell-Cell Contact signaling classified in CellChatDB$interaction$annotation).\n#' If only focusing on `Secreted Signaling`, the `contact.dependent` will be automatically set as FALSE except for `contact.dependent.forced = TRUE`.\n#' @param contact.range The interaction range (Unit: microns) to restrict the contact-dependent signaling.\n#' For spatial transcriptomics in a single-cell resolution, `contact.range` is approximately equal to the estimated cell diameter (i.e., the cell center-to-center distance), which means that contact-dependent and juxtacrine signaling can only happens when the two cells are contact to each other.\n#'\n#' Typically, `contact.range = 10`, which is a typical human cell size. However, for low-resolution spatial data such as 10X visium, it should be the cell center-to-center distance (i.e., `contact.range = 100` for visium data). The function `computeCellDistance` can compute the center-to-center distance.\n#'\n#' @param contact.knn.k Number of neighbors to restrict the contact-dependent signaling within the neatest neighbors. By default, CellChat uses `contact.range` to restrict the contact-dependent signaling; however, users can also provide a value of `contact.knn.k`, in order to determine spatially proximal cell groups based on the k-nearest neighbors (knn).\n#' For 10X visium, contact.knn.k = 6. For other spatial technologies, this value may be hard to determine because the sequenced cells/spots are usually not regularly arranged.\n#' @param do.symmetric Whether converting the adjacent matrix into symmetric one when determining spatially proximal cell groups. Default is TRUE, indicating that if adj(i,j) or adj(j,i) is zero, then both are zeros.\n#'\n#' @importFrom BiocNeighbors queryKNN AnnoyParam\n#' @return A list including a square matrix giving the pairwise region distances and an adjacent matrix indicating physically contacting cell groups based on either the contact.range or the k-nearest neighbors\n#'\n#' @export\ncomputeRegionDistance <- function(coordinates, meta,\n interaction.range = NULL, ratio = NULL, tol = NULL, k.min = 10,\n contact.dependent = TRUE, contact.range = NULL, contact.knn.k = NULL, do.symmetric = TRUE\n) {\n trim <- 0.1\n FunMean <- function(x) mean(x, trim = trim, na.rm = TRUE) # This is used for computing the average distance between two cell groups\n group <- meta$group\n numCluster <- nlevels(group)\n level.use <- levels(group)\n level.use <- level.use[level.use %in% unique(group)]\n samples <- meta$samples\n samples.use <- levels(samples)\n d.spatial <- array(NaN, dim = c(numCluster,numCluster,length(samples.use)))\n adj.spatial <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n adj.contact <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n adj.contact.knn <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n\n if (contact.dependent == TRUE & !is.null(contact.knn.k)) {\n ## find the k-nearest neighbors for each single cell\n # my.knn <- FNN::get.knn(coordinates, k = contact.knn.k)\n # nn.ranked <- my.knn$nn.index # this is a matrix with the size of nCell * contact.knn.k\n nn.ranked <- matrix(NA, nrow = nrow(coordinates), ncol = contact.knn.k)\n for (k in 1:length(samples.use)) {\n idx.k <- which(samples == samples.use[k])\n my.knn <- suppressWarnings(BiocNeighbors::findKNN(coordinates[idx.k, ], k = contact.knn.k, BNPARAM = BiocNeighbors::AnnoyParam(), get.index = TRUE))\n nn.ranked[idx.k, ] <- my.knn$index # this is a matrix with the size of nCell * contact.knn.k\n }\n k.min.contact <- k.min\n } else {\n nn.ranked <- matrix(1, nrow = nrow(coordinates), ncol = 1)\n k.min.contact <- -1 # this produces adj.contact.knn with all elements being 1\n }\n if (contact.dependent == TRUE) {\n if (is.null(contact.range) & is.null(contact.knn.k)) {\n stop(\"Please check the documentation of `computeCommunProb` and provide the value of either `contact.range` or `contact.knn.k`\")\n }\n } else {\n contact.range <- 10000 # this produces adj.contact with all elements being 1\n }\n\n for (k in 1:length(samples.use)) {\n idx.k <- samples == samples.use[k]\n for (i in 1:numCluster) {\n for (j in 1:numCluster) {\n idx.i <- which((group == level.use[i]) & idx.k)\n idx.j <- which((group == level.use[j]) & idx.k)\n if (length(idx.i) == 0 | length(idx.j) == 0) {\n next # if one cell group is missing in one sample, just goes to next loop\n }\n data.spatial.i <- coordinates[idx.i, , drop = FALSE]\n data.spatial.j <- coordinates[idx.j, , drop = FALSE]\n # for each point in the i-th cell group, find its 1-nearest neighbor in the j-th cell group\n #qout <- suppressWarnings(BiocNeighbors::queryKNN(data.spatial.j, data.spatial.i, k = 1, BNPARAM = BiocNeighbors::KmknnParam(), get.index = TRUE))\n qout <- suppressWarnings(BiocNeighbors::queryKNN(data.spatial.j, data.spatial.i, k = 1, BNPARAM = BiocNeighbors::AnnoyParam(), get.index = TRUE))\n # qout$index is an one column matrix with length being `length(idx.i)`, which is the index of the 1-nearest neighbor in the j-th cell group defined by `idx.j`\n # qout$distance is an one column matrix with length being `length(idx.i)`, which is the distance to the 1-nearest neighbor in the j-th cell group defined by `idx.j`\n\n # conver the calculated distance into the distance in micrometers\n qout$distance <- qout$distance*ratio[k]\n # long-range distance\n idx <- qout$distance - interaction.range < tol[k]\n adj.spatial[i,j,k] <- (length(unique(qout$index[idx])) >= k.min) * 1\n # short-range distance based on contact.range\n idx2 <- qout$distance - contact.range < tol[k]\n adj.contact[i,j,k] <- (length(unique(qout$index[idx2])) >= k.min) * 1\n # short-range distance based on knn\n knn.i <- unique(as.vector(nn.ranked[idx.i, ]))\n #adj.contact.knn[i,j,k] <- (length(intersect(knn.i, idx.j)) >= k.min.contact) * 1\n adj.contact.knn[i,j,k] <- (length(intersect(knn.i, unique(qout$index[idx]))) >= k.min.contact) * 1 # knn within the long-range distance\n # computing the average distance between two cell groups\n d.spatial[i,j,k] <- FunMean(qout$distance) # since distances are positive values, different ways for computing the mean have little effects.\n\n }\n }\n }\n\n # merged spatial information from different samples\n d.spatial <- apply(d.spatial, c(1,2), function(x) mean(x, na.rm = TRUE))\n adj.spatial <- apply(adj.spatial, c(1,2), mean)\n adj.contact <- apply(adj.contact, c(1,2), mean)\n adj.contact.knn <- apply(adj.contact.knn, c(1,2), mean)\n # for multi-samples analysis, the following is needed\n adj.spatial[adj.spatial > 0] <- 1\n adj.contact[adj.contact > 0] <- 1\n adj.contact.knn[adj.contact.knn > 0] <- 1\n\n # make these adjacent matrix as symmetric\n if (do.symmetric) {\n adj.spatial <- adj.spatial * t(adj.spatial) # if one is zero, then both are zeros.\n adj.contact <- adj.contact * t(adj.contact) # if one is zero, then both are zeros.\n adj.contact.knn <- adj.contact.knn * t(adj.contact.knn) # if one is zero, then both are zeros.\n }\n d.spatial <- (d.spatial + t(d.spatial))/2\n\n # filter out the spatially distant cell groups\n adj.spatial[adj.spatial == 0] <- NaN\n d.spatial <- d.spatial * adj.spatial\n\n rownames(d.spatial) <- levels(group); colnames(d.spatial) <- levels(group)\n\n if (length(contact.knn.k) > 0) {\n adj.contact = adj.contact.knn\n }\n res <- list(d.spatial = d.spatial, adj.contact = adj.contact)\n return(res)\n\n}\n\n#' Compute cell-cell distance based on the spatial coordinates\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param interaction.range The maximum interaction/diffusion range of ligands. This hard threshold is used to filter out the connections between spatially distant cells\n#' @param ratio The conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns).\n#'\n#' For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates.\n#' For 10X visium, it is the ratio of the theoretical spot size (i.e., 65um) over the number of pixels that span the diameter of a theoretical spot size in the full-resolution image (i.e., 'spot.size.fullres' in the 'scalefactors_json.json' file).\n#' @param tol The tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um.\n#'\n#' For example, for 10X visium, `tol` can be set as `65/2`; for slide-seq, `tol` can be set as `10/2`.\n#' If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance.\n#'\n#' @return an object of class \"dist\" giving the pairwise cell-cell distance\n#' @export\n#'\ncomputeCellDistance <- function(coordinates, interaction.range = NULL, ratio = NULL, tol = NULL){\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n d.spatial <- stats::dist(coordinates)\n if (!is.null(ratio)) {\n d.spatial <- d.spatial*ratio\n }\n\n if(!is.null(interaction.range) & !is.null(tol)){\n message(\"\\n Apply a predefined spatial distance threshold based on the interaction length...\")\n d.spatial[d.spatial > (interaction.range + tol)] <- NaN\n }\n return(d.spatial)\n}\n\n\n"], ["/CellChat/R/app.R", "#' Generate a Shiny App for interactive exploration of CellChat's outputs\n#'\n#' @param object CellChat object\n#' @param ... Other parameters of `shinyApp` function from shiny R package\n#' @return A Shiny app object on the basis of one CellChat object\n#' @export\n#' @importFrom stringr str_split_1\n# #' @importFrom plotly subplot plot_ly ggplotly add_markers highlight highlight_key plotlyOutput layout\n# #' @importFrom bsicons bs_icon\n#' @import shiny bslib\n#'\nrunCellChatApp <- function(object,...) {\n # ##########################################################################\n # set some global options\n # ##########################################################################\n options(stringsAsFactors = FALSE)\n\n # ##########################################################################\n # some useful elements for ui.R\n # ##########################################################################\n choices_cell_groups <-levels(object@idents)\n names(choices_cell_groups) <- levels(object@idents)\n\n choices_pathways <- object@netP$pathways\n names(choices_pathways) <- object@netP$pathways\n\n # all signaling gene names\n choices_gene_names <- CellChat::extractGene(object@DB)\n # all ligand-receptor pair names\n #choices_pairLR_use <- object@DB$interaction$interaction_name\n if (\"LRs\" %in% names(object@net)) {\n choices_pairLR_use <- object@net$LRs\n } else {\n thresh = 0.05\n prob <- object@net$prob\n prob[object@net$pval > thresh] <- 0\n LR <- dimnames(prob)[[3]]\n LR.sig <- LR[apply(prob, 3, sum) != 0]\n choices_pairLR_use <- LR.sig\n }\n\n\n # Palettes (sequential)\n choices_palettes_sequential <- stringr::str_split_1(\"Blues, BuGn, BuPu, GnBu, Greens, Greys, Oranges, OrRd, PuBu, PuBuGn, PuRd, Purples, RdPu, Reds, YlGn, YlGnBu, YlOrBr, YlOrRd\",\", \")\n names(choices_palettes_sequential) <- choices_palettes_sequential\n choices_palettes_diverging <- stringr::str_split_1(\"BrBG, PiYG, PRGn, PuOr, RdBu, RdGy, RdYlBu, RdYlGn, Spectral\",\", \")\n names(choices_palettes_diverging) <- choices_palettes_diverging\n\n # ##########################################################################\n # interactive visualization\n # ##########################################################################\n\n # interactive Heatmap\n # [Colors (ggplot2)](http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/)\n plotly_netVisual_heatmap <- function(obj_heatmap,palette.heatmap,direction.heatmap=1) {\n gg_heatmap <- obj_heatmap@matrix %>%\n as.data.frame() %>%\n mutate(row = rownames(.)) %>%\n tidyr::pivot_longer(\n data = .,\n cols = colnames(.)[-length(colnames(.))],\n names_to = \"column\",\n values_to = \"value\"\n ) %>%\n ggplot() +\n geom_tile(aes(row, column, fill = value),\n width = 0.95,\n height = 0.95) +\n # guides(fill=guide_legend(title=obj_heatmap@row_title))+\n labs(title = '',\n x = '',\n y = obj_heatmap@row_title,\n # I can't set the direction of the legend title, I thick it's a bug\n # fill = obj_heatmap@column_title,\n ) +\n scale_fill_distiller(\n palette = palette.heatmap,\n na.value = 'white',\n direction = direction.heatmap,\n ) +\n theme_minimal()+\n theme(axis.title.y = element_text(size = 14))\n\n # ggplot transpose the matrix, so we need use colSums to calc the 'rowSums'\n # of the matrix\n gg_right <- obj_heatmap@matrix %>%\n colSums(abs(.)) %>%\n tibble(row_sum = ., sources_name = names(.)) %>%\n ggplot() +\n geom_bar(aes(x = sources_name, y = row_sum, fill = sources_name),\n stat = 'identity') +\n labs(title = '',\n x = '',\n y = '',) +\n guides(fill = FALSE) +\n scale_fill_brewer(palette = \"Set1\", direction = 1) +\n theme_minimal() +\n coord_flip()\n\n gg_top <- obj_heatmap@matrix %>%\n rowSums(abs(.)) %>%\n tibble(col_sum = ., sources_name = names(.)) %>%\n ggplot() +\n # use fill to set the columns' colors\n geom_bar(aes(x = sources_name, y = col_sum, fill = sources_name),\n stat = 'identity') +\n labs(title = obj_heatmap@column_title,\n x = '',\n y = '',) +\n guides(fill = FALSE)+\n scale_fill_brewer(palette = \"Set1\", direction = 1) +\n # theme() function should be used behind the theme_*()\n theme_minimal()+\n theme(plot.title = element_text(hjust = 0.5,size = 14))\n\n return(plotly::subplot(\n gg_top,\n plotly::plotly_empty(),\n gg_heatmap,\n gg_right,\n nrows = 2,\n heights = c(0.2, 0.8),\n widths = c(0.8, 0.2),\n margin = 0,\n shareX = TRUE,\n shareY = TRUE,\n titleX = TRUE,\n titleY = TRUE\n )\n )\n }\n\n # interactive DimPlot\n plotly_DimPlot <- function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n reduction = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1)\n {\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[, group.by]\n labels <- factor(labels)\n }\n if (length(names(object@dr)) == 0) {\n stop(\"Please check `addReduction` to add a new reduced space into `object@dr`. \\n\")\n }\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please specify the dimensionality reduction to use. \\n\"))\n }\n }\n coordinates <- as.data.frame(coords)\n samples <- object@meta$samples\n if (ncol(coordinates) >= 2) {\n coordinates <- coordinates[, c(1,2)]\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n # temp_coordinates = coordinates\n # coordinates[,1] = temp_coordinates[,2]\n # coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n\n\n\n cells.level <- levels(labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n if (is.null(sources.use) & is.null(targets.use)) {\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n }\n else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use,\n \"Others\"))\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use,\n targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n # print(color.use)->return a color vector\n coordinates$cell_labels <- labels\n\n py <- plotly::highlight_key(coordinates,~cell_labels) %>%\n plotly::plot_ly(x = ~x_cent, y = ~y_cent,marker = list(size = point.size)) %>%\n plotly::add_markers(color=~cell_labels,alpha=alpha,colors=color.use) %>%\n plotly::layout(\n title = title.name,\n yaxis = list(\n title = \"\",\n #autorange = \"reversed\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n ),\n xaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n )\n ) %>%\n plotly::highlight(on = \"plotly_click\",\n off = \"plotly_relayout\")\n\n return(py)\n }\n\n # interactive FeaturePlot\n # https://plotly.com/r/subplots/\n plotly_FeaturePlot <- function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n reduction = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE){\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(\"Please make sure `object@dr` contains a low-dimensional space of the data and specify the dimensionality reduction to use.\")\n }\n }\n\n samples <- object@meta$samples\n cell_labels <- object@idents\n data <- as.matrix(object@data)\n meta <- object@meta\n coords <- as.data.frame(coords)\n if (ncol(coords) >= 2) {\n coords <- coords[, c(1,2)]\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n\n # add idents info\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = -1))(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n }\n else {\n colormap <- color.heatmap\n }\n if (is.null(features) &\n is.null(signaling) & is.null(pairLR.use)) {\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)) {\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)) {\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)) {\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n df <- data.frame(x = coords[, 1], y = coords[, 2],\n cell_labels = cell_labels)\n\n\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n geneLR.return = TRUE,\n enriched.only = enriched.only,\n thresh = thresh\n )\n feature.use <- res$geneLR\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex,\n object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex,\n object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n }\n else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) >\n 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n }\n else if (length(intersect(feature.use, colnames(meta))) >\n 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[, feature.use, drop = FALSE])\n }\n else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \", cutoff, \"to the values...\",\n \"\\n\")\n data.use[data.use <= cutoff] <- 0\n }\n\n\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 0.95) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_colour_gradientn(\n colours = colormap,\n guide = guide_colorbar(\n title = NULL,\n ticks = T,\n label = T,\n barwidth = 0.5\n ),\n na.value = \"grey90\"\n ) +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + ggtitle(feature.name) +\n theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n # g <- g + coord_fixed() +\n # scale_y_reverse()\n\n gg[[i]] <- g %>% plotly::ggplotly(height = 400)\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n # print(annotations_pos)\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',annotations = annotations)\n }\n else {\n gg <- plotly::ggplotly(gg[[1]])\n }\n }\n else {\n # do.binary\n set_individual_legend <- function(plt) {\n # plt is a plotly plot obj\n plt_build <- plotly::plotly_build(plt)\n\n # get the num of traces\n len_legend <- length(plt_build$x$data)\n\n for (i in 1:len_legend) {\n # set legendgroup\n plt_build$x$data[[i]]$legendgroup <- feature.name\n # set legendtitle\n plt_build$x$data[[i]]$legendgrouptitle <- list(text=feature.name,font=list(size=12))\n }\n return(plt_build)\n }\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n enriched.only = enriched.only,\n thresh = thresh\n )\n LR.pair <- object@LR$LRsig[res$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL\n rownames(dataR) <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \")\n }\n gg <- vector(\"list\", numFeature)\n\n # set subplot title pos\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 1) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i,] > cutoff\n idx2 = dataR[i,] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\", ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i], geneR[i],\n \"Both\", \"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i], geneR[i], \"Both\",\n \"None\")\n if (length(setdiff(levels(group), unique(group))) >\n 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group),\n unique(group)))\n }\n df$feature.data <- group\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + guides(color = guide_legend(override.aes = list(size = legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n # g <- g + coord_fixed() +\n # scale_y_reverse()\n\n # cat(feature.name)\n gg[[i]] <- g %>% plotly::ggplotly(\n type = 'scatter',\n mode='markers+text',\n ) %>% set_individual_legend()\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',\n annotations = annotations,\n legend = list(tracegroupgap = 10,title=list(text=''))\n )\n }\n else {\n gg <- plotly::ggplotly(gg[[1]],\n type = 'scatter',\n mode = 'markers') %>%\n plotly::layout(legend = list(title = list(text = '')))\n }\n }\n return(gg)\n }\n\n # interactive spatialDimPlot\n plotly_spatialDimPlot <- function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1)\n {\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[, group.by]\n labels <- factor(labels)\n }\n\n coordinates <- as.data.frame(object@images$coordinates)\n samples <- object@meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n\n\n cells.level <- levels(labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n if (is.null(sources.use) & is.null(targets.use)) {\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n }\n else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use,\n \"Others\"))\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use,\n targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n # print(color.use)->return a color vector\n coordinates$cell_labels <- labels\n\n py <- plotly::highlight_key(coordinates,~cell_labels) %>%\n plotly::plot_ly(x = ~x_cent, y = ~y_cent,marker = list(size = point.size)) %>%\n plotly::add_markers(color=~cell_labels,alpha=alpha,colors=color.use) %>%\n plotly::layout(\n title = title.name,\n yaxis = list(\n autorange = \"reversed\",\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n showline = FALSE\n ),\n xaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n showline = FALSE\n )\n ) %>%\n plotly::highlight(on = \"plotly_click\",\n off = \"plotly_relayout\")\n\n return(py)\n }\n\n # interactive spatialFeaturePlot\n # https://plotly.com/r/subplots/\n plotly_spatialFeaturePlot <- function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE){\n coords <- as.data.frame(object@images$coordinates)\n samples <- object@meta$samples\n cell_labels <- object@idents\n data <- as.matrix(object@data)\n meta <- object@meta\n\n if (ncol(coords) == 2) {\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coords = coords\n coords[,1] = temp_coords[,2]\n coords[,2] = temp_coords[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n # add idents info\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = -1))(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n }\n else {\n colormap <- color.heatmap\n }\n if (is.null(features) &\n is.null(signaling) & is.null(pairLR.use)) {\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)) {\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)) {\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)) {\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n df <- data.frame(x = coords[, 1], y = coords[, 2],\n cell_labels = cell_labels)\n\n\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n geneLR.return = TRUE,\n enriched.only = enriched.only,\n thresh = thresh\n )\n feature.use <- res$geneLR\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex,\n object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex,\n object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n }\n else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) >\n 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n }\n else if (length(intersect(feature.use, colnames(meta))) >\n 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[, feature.use, drop = FALSE])\n }\n else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \", cutoff, \"to the values...\",\n \"\\n\")\n data.use[data.use <= cutoff] <- 0\n }\n\n\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 0.95) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_colour_gradientn(\n colours = colormap,\n guide = guide_colorbar(\n title = NULL,\n ticks = T,\n label = T,\n barwidth = 0.5\n ),\n na.value = \"grey90\"\n ) +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + ggtitle(feature.name) +\n theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n g <- g + coord_fixed() +\n scale_y_reverse()\n\n gg[[i]] <- g %>% plotly::ggplotly(height = 400)\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n # print(annotations_pos)\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',annotations = annotations)\n }\n else {\n gg <- plotly::ggplotly(gg[[1]])\n }\n }\n else {\n # do.binary\n set_individual_legend <- function(plt) {\n # plt is a plotly plot obj\n plt_build <- plotly::plotly_build(plt)\n\n # get the num of traces\n len_legend <- length(plt_build$x$data)\n\n for (i in 1:len_legend) {\n # set legendgroup\n plt_build$x$data[[i]]$legendgroup <- feature.name\n # set legendtitle\n plt_build$x$data[[i]]$legendgrouptitle <- list(text=feature.name,font=list(size=12))\n }\n return(plt_build)\n }\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n enriched.only = enriched.only,\n thresh = thresh\n )\n LR.pair <- object@LR$LRsig[res$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL\n rownames(dataR) <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \")\n }\n gg <- vector(\"list\", numFeature)\n\n # set subplot title pos\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 1) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i,] > cutoff\n idx2 = dataR[i,] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\", ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i], geneR[i],\n \"Both\", \"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i], geneR[i], \"Both\",\n \"None\")\n if (length(setdiff(levels(group), unique(group))) >\n 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group),\n unique(group)))\n }\n df$feature.data <- group\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + guides(color = guide_legend(override.aes = list(size = legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n g <- g + coord_fixed() +\n scale_y_reverse()\n\n # cat(feature.name)\n gg[[i]] <- g %>% plotly::ggplotly(\n type = 'scatter',\n mode='markers+text',\n ) %>% set_individual_legend()\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',\n annotations = annotations,\n legend = list(tracegroupgap = 10,title=list(text=''))\n )\n }\n else {\n gg <- plotly::ggplotly(gg[[1]],\n type = 'scatter',\n mode = 'markers') %>%\n plotly::layout(legend = list(title = list(text = '')))\n }\n }\n return(gg)\n }\n\n\n\n # ##########################################################################\n # Shiny App's UI\n # ##########################################################################\n ui <- fluidPage(\n theme = bslib::bs_theme(version = 5),\n # ##########################################################################\n # meta info of the HTML pages\n # ##########################################################################\n tags$head(\n # title\n tags$title(\"Interactive CellChat Explorer\"),\n # icon\n tags$link(rel = \"shortcut icon\", type = \"image/x-icon\", href = \"favicon.ico\"),\n tags$link(rel=\"stylesheet\",href=\"https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css\"),\n ),\n tags$body(\n # ##########################################################################\n # logo and title of the website\n # ##########################################################################\n tags$nav(class=\"navbar navbar-light bg-light\",\n div(class=\"container-fluid justify-content-center\",\n tags$a(\n class=\"navbar-brand\",href=\"http://www.cellchat.org/\",\n img(src=\"https://s2.loli.net/2023/08/08/2qjSoRACDtHByOY.png\",class=\"d-inline\",alt=\"\",height=\"30\"),\n tags$p(\"Interactive CellChat Explorer\",class=\"fs-1 d-inline\")\n )\n\n )),\n # ##########################################################################\n # 1.Basic exploration of spatial-resolved gene expression\n # ##########################################################################\n\n # Visualize cell groups and signaling expression\n h3(tags$i(class=\"bi bi-1-square-fill\"),\n \"Visualize cell groups and signaling expression\",class=\"h3\"),\n bslib::card(\n bslib::card_header(\n h6(tags$i(class=\"bi bi-bookmark\"),\n \"Dim Plot\",class=\"h6\")),\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n sliderInput(\n \"dimplot_point_size\",\n label = \"Point size\",\n min = 3,\n max = 8,\n step = 0.5,\n value = 3\n ),\n sliderInput(\n \"dimplot_alpha\",\n label = \"Alpha\",\n min = 0,\n max = 1,\n step = 0.2,\n value = 1\n ),\n )\n ),\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"DimPlot\",\n width = 664,height = 498)\n )\n\n ),\n\n ),\n\n # gene expression distribution\n # https://shiny.posit.co/r/gallery/widgets/datatables-options/\n # https://shiny.posit.co/r/gallery/widgets/selectize-examples/\n navset_card_tab(\n title = h6(tags$i(class=\"bi bi-bookmark-dash\"),\n \"Feature Plot\",class=\"h6\"),\n sidebar = NULL,\n # content\n nav_panel(\n title = \"use gene names\",\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectizeInput(\n inputId = 'selectize_gene_names',\n label = 'Gene Names',\n choices = NULL,\n multiple = TRUE,\n # options = list(maxItems = 4)\n ),\n numericInput(\n \"nrows_feature_plot1\",\n label = \"nrows\",\n min = 1,\n step = 1,\n value = 1,\n ),\n ),\n\n accordion_panel(\n title = \"Color\",\n icon = tags$i(class=\"bi bi-palette-fill\"),\n selectInput(\n \"direction_feature_plot1\",\n label = \"direction\",\n choices = list(\"1\"=1,\"-1\"=-1),\n selected = 1,\n multiple = F\n ),\n selectInput(\n \"palette_feature_plot1\",\n label = \"palette\",\n choices = c(choices_palettes_diverging,choices_palettes_sequential),\n selected = \"Reds\",\n multiple = F\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n numericInput(\n \"cut.off_feature_plot1\",\n label = \"cut.off\",\n min = 0,\n step = 0.1,\n value = 0,\n ),\n sliderInput(\n \"point.size_feature_plot1\",\n label = \"point.size\",\n min = 0,\n max = 2,\n step = 0.1,\n value = 0.4\n )\n )\n\n ),\n # nav content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"gene_expression_distribution\",width = 664,height = 498),\n ),\n )\n ),\n nav_panel(\n title = \"use L-R pairs\",\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectizeInput(\n inputId = 'selectize_pairLR_use',\n label = 'pairLR_use',\n choices = NULL,\n multiple = T\n ),\n numericInput(\n \"nrows_feature_plot2\",\n label = \"nrows\",\n min = 1,\n step = 1,\n value = 1,\n ),\n checkboxInput(\n \"do.binary_feature_plot\",\n label = \"do.binary\",\n value = TRUE),\n ),\n accordion_panel(\n title = \"Color\",\n icon = tags$i(class=\"bi bi-palette-fill\"),\n selectInput(\n \"direction_feature_plot2\",\n label = \"direction\",\n choices = list(\"1\"=1,\"-1\"=-1),\n selected = 1,\n multiple = F\n ),\n selectInput(\n \"palette_feature_plot2\",\n label = \"palette\",\n choices = c(choices_palettes_diverging,choices_palettes_sequential),\n selected = \"Reds\",\n multiple = F\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n numericInput(\n \"cut.off_feature_plot2\",\n label = \"cut.off\",\n min = 0,\n step = 0.1,\n value = 0,\n ),\n sliderInput(\n \"point.size_feature_plot2\",\n label = \"point.size\",\n min = 0,\n max = 2,\n step = 0.1,\n value = 0.4\n )\n )\n ),\n # nav content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"gene_expression_distribution2\",width = 664,height = 498)\n )\n ),\n )\n ),\n\n # ##########################################################################\n # 2.Examine signaling between cell groups\n # ##########################################################################\n h2(tags$i(class=\"bi bi-2-square-fill\"),\n \"Examine signaling between cell groups\"),\n navset_card_tab(\n title = NULL,\n sidebar = NULL,\n nav_panel(\"Heatmap\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"The number of interactions/interaction strength between any two cell groups\",\n class=\"h6\"),\n hr(),\n\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"measure_heatmap\",\n label = \"measurement\",\n choices = list(\"count\" = \"count\", \"weight\" = \"weight\"),\n selected = \"count\"\n ),\n selectInput(\n \"palette_heatmap\",\n label = \"palette (sequential)\",\n choices = choices_palettes_sequential,\n selected = \"Blues\"\n ),\n # Sets the order of colours in the scale. If 1, the default, colours are as output by RColorBrewer::brewer.pal(). If -1, the order of colours is reversed.\n selectInput(\n \"direction_heatmap\",\n label = \"direction\",\n choices = list(\n \"1\"=1,\n \"-1\"=-1\n ),\n selected = 1,\n )\n\n # refer to: https://ggplot2.tidyverse.org/reference/scale_brewer.html\n ),\n ),\n\n # content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"netVisual_heatmap\",width = 664,height = 498)\n )\n )\n ),\n\n # the enriched signaling among one selected pair of cell groups\n nav_panel(\"rankNet\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"The enriched signaling\",\n class=\"h6\"),\n hr(),\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"select1_cell_group\",\n label = \"cell groups for sources.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[1],\n multiple = TRUE\n ),\n selectInput(\n \"select2_cell_group\",\n label = \"cell groups for targets.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[2],\n multiple = TRUE\n ),\n\n # selectInput(\n # \"measure_ranknet\",\n # label = \"measurement\",\n # choices = list(\"count\" = \"count\", \"weight\" = \"weight\"),\n # selected = \"count\"\n # ),\n selectInput(\n \"slot.name_ranknet\",\n label = \"slot.name\",\n choices = list(\"net\" = \"net\", \"netP\" = \"netP\"),\n selected = \"netP\"\n ),\n # selectInput(\n # \"palette_ranknet\",\n # label = \"palette (sequential)\",\n # choices = choices_palettes_sequential,\n # selected = \"Blues\"\n # ),\n ),\n ),\n\n # content\n plotly::plotlyOutput(outputId = \"rankNet\")\n )\n ),\n nav_panel(\"Contribution Plot\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"Contribution of each L-R pair to overall signaling\",\n class = \"h6\"),\n hr(),\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"pathway_contribution_plot\",\n label = \"a pathway to show\",\n choices = choices_pathways,\n selected = choices_pathways[1]\n ),\n selectInput(\n \"select3_cell_group\",\n label = \"a cell group for sources.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[1]\n ),\n selectInput(\n \"select4_cell_group\",\n label = \"a cell group for targets.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[2]\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n sliderInput(\n \"font.size_contribution_plot\",\n label = \"font.size\",\n min = 10,\n max=30,\n step = 5,\n value = 20\n )\n )\n ),\n\n # content\n plotOutput(outputId = \"netAnalysis_contribution\"),\n )\n ),\n ),\n\n # Contribution of each L-R pair to overall signaling\n # width = 3.2inch, height = 1.5inch,\n # height might change dependent on dataset\n\n ## Examine individual signaling pathway\n ## (the following four plots will be appeared based on user's input)\n h2(tags$i(class=\"bi bi-3-square-fill\"),\n \"Examine individual signaling pathway\"),\n navset_card_tab(\n title = h6(\"Plots\",class=\"h6\"),\n sidebar = accordion(\n selectizeInput(\n inputId = 'selectize_pathway',\n label = 'Select a pathway to show',\n choices = NULL,\n multiple = FALSE\n ),\n hr(),\n accordion_panel(\n title = \"Circle plot\",\n icon = tags$i(class=\"bi bi-circle-fill\"),\n # edge.width.max = 5, vertex.size.max = 12, vertex.label.cex = 0.8\n sliderInput(\n \"slider_Circle_plot_edge.width.max\",\n label = \"edge.width.max\",\n min = 5,\n max = 15,\n value = 8,\n step = 1\n ),\n sliderInput(\n \"slider_Circle_plot_vertex.size.max\",\n label = \"vertex.size.max\",\n min = 8,\n max = 16,\n value = 12,\n step = 2),\n sliderInput(\n \"slider_Circle_plot_vertex.label.cex\",\n label = \"vertex.label.cex\",\n min = 1,\n max = 2,\n value = 1,\n step = 0.2\n ),\n ),\n accordion_panel(\n title = \"Spatial plot\",\n icon = tags$i(class=\"bi bi-layers-half\"),\n # edge.width.max = 5, vertex.size.max = 1,\n # point.size = 2.5,\n # alpha.image = 0.2, vertex.label.cex = 5\n sliderInput(\n \"slider_Spatial_plot_edge.width.max\",\n label = \"edge.width.max\",\n min = 2,\n max = 8,\n value = 5,\n step = 1\n ),\n sliderInput(\n \"slider_Spatial_plot_vertex.size.max\",\n label = \"vertex.size.max\",\n min = 2,\n max = 8,\n value = 5,\n step = 1),\n sliderInput(\n \"slider_Spatial_plot_vertex.label.cex\",\n label = \"vertex.label.cex\",\n min = 5,\n max = 10,\n value = 8,\n step = 1\n ),\n\n sliderInput(\n \"slider_Spatial_plot_point.size\",\n label = \"point.size\",\n min = 1,\n max = 3,\n value = 2.4,\n step = 0.2\n ),\n sliderInput(\n \"slider_Spatial_plot_alpha.image\",\n label = \"alpha.image\",\n min = 0,\n max = 1,\n value = 0.2,\n step = 0.05\n ),\n ),\n accordion_panel(\n title = \"Contribution of each L-R pair\",\n icon = tags$i(class=\"bi bi-bar-chart-fill\"),\n ),\n ),\n\n # nav tab\n nav_panel(\n title = \"Circle plot\",\n div(class=\"d-flex justify-content-center\",\n plotOutput(outputId = \"Circle_plot\",\n height = \"780px\",width = \"580px\")\n )\n ),\n nav_panel(\n title = \"Spatial plot\",\n div(class=\"d-flex justify-content-center\",\n plotOutput(outputId = \"Spatial_plot\",\n height = \"780px\",width = \"580px\")\n )\n ),\n nav_panel(\n title = \"Contribution of each L-R pair\",\n plotly::plotlyOutput(outputId = \"LR_pair_contribution\",\n height = \"900px\")\n ),\n\n ),\n # body\n\n ),\n # page\n )\n # ##########################################################################\n # Shiny App's Server\n # ##########################################################################\n server <- function(input, output, session) {\n ############################################################################\n if (object@options$datatype == \"RNA\") {\n output$DimPlot <- plotly::renderPlotly({\n plotly_DimPlot(\n object,\n point.size = input$dimplot_point_size,\n alpha = input$dimplot_alpha,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"DimPlot\",\n width = 800,\n height = 600\n ))\n })\n } else {\n output$spatialDimPlot <- plotly::renderPlotly({\n plotly_spatialDimPlot(\n object,\n point.size = input$dimplot_point_size,\n alpha = input$dimplot_alpha,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialDimPlot\",\n width = 800,\n height = 600\n ))\n })\n }\n\n\n observe({\n updateSelectizeInput(\n session,\n \"selectize_gene_names\",\n # selected = c(\"Wnt10a\", \"Fzd1\", \"Lrp6\"),\n selected = choices_gene_names[1:2],\n # selected = c(\"Wnt10a\", \"Fzd1\", \"Lrp6\",\"Ror2\",\n # \"Nrp1\",\"Nrp2\",\"Bmpr2\",\"Ret\"),\n choices = choices_gene_names,\n server = TRUE\n )\n })\n # output$out6 <- renderPrint(input$selectize_gene_names)\n\n if (object@options$datatype == \"RNA\") {\n output$gene_expression_distribution <- plotly::renderPlotly(plotly_FeaturePlot(\n object,\n features = input$selectize_gene_names,\n plot_nrows = input$nrows_feature_plot1,\n point.size = input$point.size_feature_plot1,\n cutoff = input$cut.off_feature_plot1,\n color.heatmap = input$palette_feature_plot1,\n direction = input$direction_feature_plot1,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"FeaturePlot (use gene names)\",\n width = 600,\n height = 600\n ))\n )\n } else {\n output$gene_expression_distribution <- plotly::renderPlotly(plotly_spatialFeaturePlot(\n object,\n features = input$selectize_gene_names,\n plot_nrows = input$nrows_feature_plot1,\n point.size = input$point.size_feature_plot1,\n cutoff = input$cut.off_feature_plot1,\n color.heatmap = input$palette_feature_plot1,\n direction = input$direction_feature_plot1,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialFeaturePlot (use gene names)\",\n width = 600,\n height = 600\n ))\n )\n }\n\n\n observe({\n updateSelectizeInput(\n session,\n \"selectize_pairLR_use\",\n selected = choices_pairLR_use[1],\n # selected = c(\"WNT10A_FZD1_LRP6\",\"WNT10A_FZD10_LRP6\",\"BMP2_BMPR1A_ACVR2A\"),\n choices = choices_pairLR_use,\n server = TRUE\n )\n })\n # output$out7 <- renderPrint(input$selectize_pairLR_use)\n if (object@options$datatype == \"RNA\") {\n output$gene_expression_distribution2 <- plotly::renderPlotly({\n plotly_FeaturePlot(\n object,\n pairLR.use = input$selectize_pairLR_use,\n point.size = input$point.size_feature_plot2,\n do.binary = input$do.binary_feature_plot,\n cutoff = input$cut.off_feature_plot2,\n enriched.only = F,\n color.heatmap = input$palette_feature_plot2,\n direction = input$direction_feature_plot2,\n plot_nrows = as.numeric(input$nrows_feature_plot2)\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"FeaturePlot(use pairLRs)\",\n width = 600,\n height = 600\n ))\n })\n } else {\n output$gene_expression_distribution2 <- plotly::renderPlotly({\n plotly_spatialFeaturePlot(\n object,\n pairLR.use = input$selectize_pairLR_use,\n point.size = input$point.size_feature_plot2,\n do.binary = input$do.binary_feature_plot,\n cutoff = input$cut.off_feature_plot2,\n enriched.only = F,\n color.heatmap = input$palette_feature_plot2,\n direction = input$direction_feature_plot2,\n plot_nrows = as.numeric(input$nrows_feature_plot2)\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialFeaturePlot(use pairLRs)\",\n width = 600,\n height = 600\n ))\n })\n }\n\n\n ############################################################################\n output$netVisual_heatmap <- plotly::renderPlotly({\n suppressWarnings({\n netVisual_heatmap(object,\n measure = input$measure_heatmap,\n ) %>%\n plotly_netVisual_heatmap(\n palette.heatmap = input$palette_heatmap,\n direction.heatmap = input$direction_heatmap)\n })\n })\n\n output$rankNet <- plotly::renderPlotly({\n rankNet(\n object,\n mode = \"single\",\n measure = \"weight\",\n sources.use = input$select1_cell_group,\n targets.use = input$select2_cell_group,\n slot.name = input$slot.name_ranknet\n ) %>%\n plotly::ggplotly()\n })\n\n output$netAnalysis_contribution <- renderPlot({\n netAnalysis_contribution(\n object,\n signaling = input$pathway_contribution_plot,\n sources.use = input$select3_cell_group,\n targets.use = input$select4_cell_group,\n font.size = input$font.size_contribution_plot,\n font.size.title = input$font.size_contribution_plot,\n )\n },res = 96)\n ############################################################################\n observe({\n updateSelectizeInput(\n session,\n \"selectize_pathway\",\n selected = choices_pathways[1],\n choices = choices_pathways,\n server = TRUE\n )\n })\n output$Circle_plot <- renderPlot({\n netVisual_aggregate(\n object,\n signaling = input$selectize_pathway,\n layout = \"circle\",\n edge.width.max = input$slider_Circle_plot_edge.width.max,\n vertex.size.max = input$slider_Circle_plot_vertex.size.max,\n vertex.label.cex = input$slider_Circle_plot_vertex.label.cex\n )\n },res = 96)\n output$Spatial_plot <- renderPlot({\n netVisual_aggregate(\n object,\n signaling = input$selectize_pathway,\n layout = \"spatial\",\n edge.width.max = input$slider_Spatial_plot_edge.width.max,\n vertex.size.max = input$slider_Spatial_plot_vertex.size.max,\n vertex.label.cex = input$slider_Spatial_plot_vertex.label.cex,\n alpha.image = input$slider_Spatial_plot_alpha.image,\n point.size = input$slider_Spatial_plot_point.size,\n )\n })\n output$LR_pair_contribution <- plotly::renderPlotly({\n netAnalysis_contribution(\n object,\n signaling = input$selectize_pathway,\n font.size = 12,\n font.size.title = 14\n )\n })\n ############################################################################\n }\n\n\n # Running a Shiny app\n shinyApp(ui = ui, server = server,...)\n}\n"], ["/CellChat/R/database.R", "#' Show the description of CellChatDB databse\n#'\n#' @param CellChatDB CellChatDB databse\n#' @param nrow the number of rows in the plot\n#' @importFrom dplyr group_by summarise n %>%\n#'\n#' @return\n#' @export\n#'\nshowDatabaseCategory <- function(CellChatDB, nrow = 1) {\n interaction_input <- CellChatDB$interaction\n geneIfo <- CellChatDB$geneInfo\n df <- interaction_input %>% group_by(annotation) %>% summarise(value=n())\n #df$group <- factor(df$annotation, levels = unique(df$annotation))\n df$group <- factor(df$annotation, levels = c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\"))\n gg1 <- pieChart(df)\n binary <- (interaction_input$ligand %in% geneIfo$Symbol) & (interaction_input$receptor %in% geneIfo$Symbol)\n df <- data.frame(group = rep(\"Heterodimers\", dim(interaction_input)[1]),stringsAsFactors = FALSE)\n df$group[binary] <- rep(\"Others\",sum(binary),1)\n df <- df %>% group_by(group) %>% summarise(value=n())\n df$group <- factor(df$group, levels = c(\"Heterodimers\",\"Others\"))\n gg2 <- pieChart(df)\n\n kegg <- grepl(\"KEGG\", interaction_input$evidence)\n df <- data.frame(group = rep(\"Literature\", dim(interaction_input)[1]),stringsAsFactors = FALSE)\n df$group[kegg] <- rep(\"KEGG\",sum(kegg),1)\n df <- df %>% group_by(group) %>% summarise(value=n())\n df$group <- factor(df$group, levels = c(\"KEGG\",\"Literature\"))\n gg3 <- pieChart(df)\n\n gg <- cowplot::plot_grid(gg1, gg2, gg3, nrow = nrow, align = \"h\", rel_widths = c(1, 1,1))\n return(gg)\n}\n\n\n#' Plot pie chart\n#'\n#' @param df a dataframe\n#' @param label.size a character\n#' @param color.use the name of the variable in CellChatDB interaction_input\n#' @param title the title of plot\n#' @import ggplot2\n#' @importFrom scales percent\n#' @importFrom dplyr arrange desc mutate\n#' @importFrom ggrepel geom_text_repel\n#' @return\n#' @export\n#'\npieChart <- function(df, label.size = 2.5, color.use = NULL, title = \"\") {\n df %>% arrange(dplyr::desc(value)) %>%\n mutate(prop = scales::percent(value/sum(value))) -> df\n\n gg <- ggplot(df, aes(x=\"\", y=value, fill=group)) +\n geom_bar(stat=\"identity\", width=1) +\n coord_polar(\"y\", start=0)+theme_void() +\n ggrepel::geom_text_repel(aes(label = prop), size= label.size, show.legend = F, position = position_stack(vjust=0.5))\n # ggrepel::geom_text_repel(aes(label = prop), size= label.size, show.legend = F, nudge_x = 0)\n gg <- gg + theme(legend.position=\"bottom\", legend.direction = \"vertical\")\n\n if(!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values=color.use)\n # gg <- gg + scale_color_manual(color.use)\n }\n\n if (!is.null(title)) {\n gg <- gg + guides(fill = guide_legend(title = title))\n }\n gg\n}\n\n\n#' Subset the ligand-receptor interactions for given specific signals in CellChatDB\n#'\n#' @param signaling a character vector\n#' @param pairLR.use a dataframe containing ligand-receptor interactions\n#' @param key the keyword to match\n#' @param matching.exact whether perform exact matching\n#' @param pair.only whether only return ligand-receptor pairs without cofactors\n#' @importFrom future.apply future_sapply\n#' @importFrom dplyr select\n#' @return\n#' @export\nsearchPair <- function(signaling = c(), pairLR.use, key = c(\"pathway_name\",\"ligand\"), matching.exact = FALSE, pair.only = TRUE) {\n key <- match.arg(key)\n pairLR = future.apply::future_sapply(\n X = 1:length(signaling),\n FUN = function(x) {\n if (!matching.exact) {\n index <- grep(signaling[x], pairLR.use[[key]])\n } else {\n index <- which(pairLR.use[[key]] %in% signaling[x])\n }\n if (length(index) > 0) {\n if (pair.only) {\n pairLR <- dplyr::select(pairLR.use[index, ], interaction_name, pathway_name, ligand, receptor)\n } else {\n pairLR <- pairLR.use[index, ]\n }\n return(pairLR)\n } else {\n stop(cat(paste(\"Cannot find \", signaling[x], \".\", \"Please input a correct name!\"),'\\n'))\n }\n }\n )\n if (pair.only) {\n pairLR0 <- vector(\"list\", length(signaling))\n for (i in 1:length(signaling)) {\n pairLR0[[i]] <- matrix(unlist(pairLR[c(4*i-3, 4*i-2, 4*i-1, 4*i)]), ncol=4, byrow=F)\n }\n pairLR <- do.call(rbind, pairLR0)\n dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]][1:4]\n rownames(pairLR) <- pairLR[,1]\n } else {\n pairLR0 <- vector(\"list\", length(signaling))\n for (i in 1:length(signaling)) {\n pairLR0[[i]] <- matrix(unlist(pairLR[(i*ncol(pairLR.use)-(ncol(pairLR.use)-1)):(i*ncol(pairLR.use))]), ncol=ncol(pairLR.use), byrow=F)\n }\n pairLR <- do.call(rbind, pairLR0)\n dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]]\n rownames(pairLR) <- pairLR[,1]\n }\n return(as.data.frame(pairLR, stringsAsFactors = FALSE))\n}\n\n#' Subset CellChatDB databse by only including interactions of interest\n#'\n#' @param CellChatDB CellChatDB databse\n#' @param search a character vector, which is a subset of c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\"); Setting search = NULL & non_protein = FALSE will return all signaling except for \"Non-protein Signaling\".\n#'\n#' When `key` is a vector, the `search` should be a list with the size being `length(key)`, where each element is a character vector.\n#' @param key a character vector and each element should be one of the column names of the interaction_input from CellChatDB.\n#' @param non_protein whether to use the non-protein signaling for CellChat analysis. By default, non_protein = FALSE because most of non-protein signaling are the special synaptic signaling interactions that can only be used when inferring neuron-neuron communication.\n#'\n#' @return\n#' @export\n#'\nsubsetDB <- function(CellChatDB, search = c(), key = \"annotation\", non_protein = FALSE) {\n interaction_input <- CellChatDB$interaction\n if (is.null(search) & non_protein == FALSE & any(key == \"annotation\")) {\n search <- c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\")\n } else if (is.null(search) & non_protein == TRUE & any(key == \"annotation\")) {\n search <- c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\")\n }\n\n if (\"Non-protein Signaling\" %in% unlist(search)) {\n non_protein = TRUE\n message(\"The non-protein signaling is now included for CellChat analysis, which is usually used for neuron-neuron and metabolic communication!\")\n }\n if (non_protein == FALSE) {\n interaction_input <- subset(interaction_input, annotation != \"Non-protein Signaling\")\n }\n if (all(key %in% colnames(interaction_input)) == FALSE) {\n stop(\"Each element of the `key` should be one of the column names of the interaction_input from CellChatDB\")\n }\n if (length(key) == 1) {\n interaction_input <- interaction_input[interaction_input[[key]] %in% search, ]\n } else {\n if (!is.list(search)) {\n stop(\"When `key` is a vector, the `search` should be a list. \")\n }\n idx.use <- TRUE\n for (i in 1:length(key)) {\n idx.use <- idx.use & (interaction_input[[key[i]]] %in% search[[i]])\n }\n interaction_input <- interaction_input[idx.use, , drop = FALSE]\n }\n\n CellChatDB$interaction <- interaction_input\n return(CellChatDB)\n}\n\n\n\n#' Extract the genes involved in CellChatDB\n#'\n#' @param CellChatDB CellChatDB databse used in the analysis\n#'\n#' @return\n#' @export\n#' @importFrom dplyr select\n#'\nextractGene <- function(CellChatDB) {\n interaction_input <- CellChatDB$interaction\n complex_input <- CellChatDB$complex\n cofactor_input <- CellChatDB$cofactor\n geneIfo <- CellChatDB$geneInfo\n # check whether all gene names in complex_input and cofactor_input are official gene symbol in geneIfo\n checkGeneSymbol(geneSet = unlist(complex_input), geneIfo)\n checkGeneSymbol(geneSet = unlist(cofactor_input), geneIfo)\n\n geneL <- unique(interaction_input$ligand)\n geneR <- unique(interaction_input$receptor)\n geneLR <- c(geneL, geneR)\n checkGeneSymbol(geneSet = geneLR[geneLR %in% rownames(complex_input) == \"FALSE\"], geneIfo)\n\n geneL <- extractGeneSubset(geneL, complex_input, geneIfo)\n geneR <- extractGeneSubset(geneR, complex_input, geneIfo)\n geneLR <- c(geneL, geneR)\n\n cofactor <- c(interaction_input$agonist, interaction_input$antagonist, interaction_input$co_A_receptor, interaction_input$co_I_receptor)\n cofactor <- unique(cofactor[cofactor != \"\"])\n cofactorsubunits <- select(cofactor_input[match(cofactor, rownames(cofactor_input), nomatch=0),], starts_with(\"cofactor\"))\n cofactorsubunitsV <- unlist(cofactorsubunits)\n geneCofactor <- unique(cofactorsubunitsV[cofactorsubunitsV != \"\"])\n\n gene.use <- unique(c(geneLR, geneCofactor))\n return(gene.use)\n\n}\n\n\n#' Extract the gene name\n#'\n#' @param geneSet gene set\n#' @param complex_input complex in CellChatDB databse\n#' @param geneIfo official gene symbol\n#'\n#' @return\n#' @importFrom dplyr select starts_with\n#' @export\nextractGeneSubset <- function(geneSet, complex_input, geneIfo) {\n complex <- geneSet[which(geneSet %in% geneIfo$Symbol == \"FALSE\")]\n geneSet <- intersect(geneSet, geneIfo$Symbol)\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complex <- intersect(complex, rownames(complexsubunits))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n geneSet <- unique(c(geneSet, complexsubunitsV))\n return(geneSet)\n}\n\n\n#' Extract the signaling gene names from ligand-receptor pairs\n#'\n#' @param pairLR data frame must contain columns named `ligand` and `receptor`\n#' @param object a CellChat object\n#' @param complex_input complex in CellChatDB databse\n#' @param geneInfo official gene symbol\n#' @param combined whether combining the ligand genes and receptor genes\n#'\n#' @return\n#' @export\nextractGeneSubsetFromPair <- function(pairLR, object = NULL, complex_input = NULL, geneInfo = NULL, combined = TRUE) {\n if (!all(c(\"ligand\", \"receptor\") %in% colnames(pairLR))) {\n stop(\"The input data frame must contain columns named `ligand` and `receptor`\")\n }\n if (is.null(object)) {\n if (is.null(complex_input) | is.null(geneInfo)) {\n stop(\"Either `object` or `complex_input` and `geneInfo` should be provided!\")\n } else {\n complex <- complex_input\n }\n } else {\n complex <- object@DB$complex\n geneInfo <- object@DB$geneInfo\n }\n geneL <- unique(pairLR$ligand)\n geneR <- unique(pairLR$receptor)\n geneL <- extractGeneSubset(geneL, complex, geneInfo)\n geneR <- extractGeneSubset(geneR, complex, geneInfo)\n geneLR <- c(geneL, geneR)\n if (combined) {\n return(geneLR)\n } else {\n return(list(geneL = geneL, geneR = geneR))\n }\n}\n\n\n\n#' check the official Gene Symbol\n#'\n#' @param geneSet gene set to check\n#' @param geneIfo official Gene Symbol\n#' @return\n#' @export\n#'\ncheckGeneSymbol <- function(geneSet, geneIfo) {\n geneSet <- unique(geneSet[geneSet != \"\"])\n genes_notOfficial <- geneSet[geneSet %in% geneIfo$Symbol == \"FALSE\"]\n if (length(genes_notOfficial) > 0) {\n cat(\"Issue identified!! Please check the official Gene Symbol of the following genes: \", \"\\n\", genes_notOfficial, \"\\n\")\n }\n return(FALSE)\n}\n\n#' Extract L-R pairs associated with a given gene set\n#'\n#' @param geneSet a vector of genes\n#' @param db one of the CellChatDB databases (e.g., CellChatDB.human, CellChatDB.mouse...)\n#' @export\n#'\nextractLRfromGenes <- function(geneSet, db) {\n interaction_input <- db$interaction\n complex_input <- db$complex\n geneIfo <- db$geneInfo\n geneSet1 <- intersect(geneSet, geneIfo$Symbol)\n idx1 <- which(interaction_input$ligand %in% geneSet1)\n idx2 <- which(interaction_input$receptor %in% geneSet1)\n idx <- unique(c(idx1, idx2)); idx <- setdiff(idx,0)\n LR.use <- interaction_input[idx,,drop = FALSE]\n genes.use <- extractGeneSubsetFromPair(LR.use, complex_input = complex_input, geneInfo = geneIfo)\n return(list(LR.use = LR.use, genes.use=genes.use))\n}\n\n\n#' Update CellChatDB by integrating new L-R pairs from other resources or adding more information\n#'\n#' @param db a data frame of the customized ligand-receptor database with at least two columns named as `ligand` and `receptor`. We highly suggest users to provide a column of pathway information named `pathway_name` associated with each L-R pair.\n#' Other optional columns include `interaction_name` and `interaction_name_2`. The default columns of CellChatDB can be checked via `colnames(CellChatDB.human$interaction)`.\n#' @param gene_info a data frame with at least one column named as `Symbol`. \"When setting gene_info = NULL, the input `species_target` should be provided: either `human` or `mouse`.\n#' @param other_info a list consisting of other information including a dataframe named as `complex` and a dataframe named as `cofactor`. This additional information is not necessary. If other_info is provided, the `complex` and `cofactor` are dataframes with defined rownames.\n#' @param gene_info_columnNew a data frame with at least two columns named as `Symbol` and `AntibodyName`, which will add a new column named `AntibodyName` into `db$geneInfo`.\n#' @param trim.pathway whether to delete the interactions with missing pathway names when the column `pathway_name` is provided in `db`.\n#' @param merged whether merging the input database with the existing CellChatDB. setting merged = TRUE, the input `species_target` should be provided: either `human` or `mouse`.\n#' @param species_target the target species for output: either `human` or `mouse`.\n#' @return a list consisting of the customized L-R database for further CellChat analysis\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # integrating new L-R pairs from other resources or utilizing a custom database `db.user`\n#' db.new <- updateCellChatDB(db = db.user, gene_info = gene_info)\n#' db.new <- updateCellChatDB(db = db.user, gene_info = NULL, species_target = \"human\")\n#' # Alternatively, users can integrate the customized L-R pairs into the built-in CellChatDB\n#' db.new <- updateCellChatDB(db = db.user, merged = TRUE, species_target = \"human\")\n#' # Add new columns (e.g., AntibodyName) into gene_info\n#' db.new.human <- updateCellChatDB(db = CellChatDB.human$interaction, gene_info = CellChatDB.human$geneInfo, other_info=list(complex = CellChatDB.human$complex, cofactor = CellChatDB.human$cofactor),gene_info_columnNew = gene_info_columnNew)\n#'\n#' # Users can now use this new database in CellChat analysis\n#' cellchat@DB <- db.new\n#'}\nupdateCellChatDB <- function(db, gene_info = NULL, other_info = NULL, gene_info_columnNew = NULL, trim.pathway = FALSE, merged = FALSE, species_target = NULL) {\n db <- dplyr::mutate(db, across(everything(), as.character))\n if (all(c(\"ligand\",\"receptor\") %in% colnames(db)) == FALSE) {\n stop(\"The input `db` must contain at least two columns named as ligand,receptor\")\n }\n if (all(c(\"pathway_name\") %in% colnames(db)) == FALSE) {\n warning(\"The pathway_name associated with each L-R pair is not provided in `db`. We suggest to provide this information so that the versatile functionalities of CellChat can be fully used! \\n\")\n db$pathway_name <- rep(\"\", nrow(db))\n } else {\n pathway.missing <- which(db$pathway_name == \"\")\n if (length(pathway.missing) > 0) {\n if (trim.pathway) {\n cat(paste0(\"The pathway names of \", length(pathway.missing) ,\" interactions are missing and the corresponding interactions are now deleted. \\n\"))\n db <- db[-pathway.missing, , drop = FALSE]\n } else {\n warning(paste0(\"The pathway names of \", length(pathway.missing) ,\" interactions are missing and it may cause error in the downstream analysis. Setting `trim.pathway = TRUE` to avoid such possible errors. \\n\"))\n }\n }\n }\n if (all(c(\"interaction_name\") %in% colnames(db)) == FALSE) {\n db$interaction_name <- paste0(toupper(db$ligand), \"_\", toupper(db$receptor))\n }\n if (all(c(\"interaction_name_2\") %in% colnames(db)) == FALSE) {\n db$interaction_name_2 <- paste0(db$ligand, \" - \", db$receptor)\n }\n if (\"agonist\" %in% colnames(db) == FALSE) {\n db$agonist <- rep(\"\", nrow(db))\n }\n if (\"antagonist\" %in% colnames(db) == FALSE) {\n db$antagonist <- rep(\"\", nrow(db))\n }\n if (\"co_A_receptor\" %in% colnames(db) == FALSE) {\n db$co_A_receptor <- rep(\"\", nrow(db))\n }\n if (\"co_I_receptor\" %in% colnames(db) == FALSE) {\n db$co_I_receptor <- rep(\"\", nrow(db))\n }\n ## construct database\n idx.remove <- duplicated(db$interaction_name)\n if (sum(idx.remove) > 0) {\n warning(paste0(sum(idx.remove), \" duplicated interaction_names are identified and the corresponding interactions are now deleted. \\n\"))\n db <- db[-which(idx.remove), ]\n }\n\n # build the interaction file\n interaction_input <- db\n rownames(interaction_input) <- interaction_input$interaction_name\n cols.default <- c(\"interaction_name\",\"pathway_name\",\"ligand\",\"receptor\",\"agonist\",\"antagonist\",\"co_A_receptor\",\"co_I_receptor\",\"annotation\",\"interaction_name_2\")\n cols.common <- intersect(cols.default,colnames(interaction_input))\n cols.specific <- setdiff(colnames(interaction_input), cols.default)\n interaction_input <- dplyr::select(interaction_input, c(cols.common, cols.specific))\n\n # build the complex file\n if (!is.null(other_info)) {\n if (\"complex\" %in% names(other_info) == TRUE) {\n complex_input <- other_info$complex\n if (all(colnames(complex_input) %in% paste0(\"subunit_\", seq_len(100))) == FALSE) {\n stop(\"The colnames of the input `other_info$complex` should be `subunit_1`,`subunit_2`,...\")\n }\n } else {\n complex_input <- data.frame()\n }\n # build the cofactor file\n if (\"cofactor\" %in% names(other_info) == TRUE) {\n cofactor_input <- other_info$cofactor\n if (all(colnames(cofactor_input) %in% paste0(\"cofactor\", seq_len(100))) == FALSE) {\n stop(\"The colnames of the input `other_info$cofactor` should be `cofactor1`,`cofactor2`,...\")\n }\n } else {\n cofactor_input <- data.frame()\n }\n } else {\n complex_input <- data.frame()\n cofactor_input <- data.frame()\n }\n\n # build the geneInfo file\n if (!is.null(gene_info)) {\n if (\"Symbol\" %in% colnames(gene_info) == FALSE) {\n stop(\"The input `gene_info` must contain at least one column named as `Symbol`\")\n }\n } else {\n if (is.null(species_target)) {\n stop(\"When setting gene_info = NULL, the input `species_target` should be provided: either `human` or `mouse`. \")\n }\n if (species_target == \"human\") {\n gene_info <- CellChatDB.human$geneInfo\n } else if (species_target == \"mouse\") {\n gene_info <- CellChatDB.mouse$geneInfo\n }\n }\n geneInfo_input <- gene_info\n\n if (merged == TRUE) {\n if (is.null(species_target)) {\n stop(\"When setting merged = TRUE, the input `species_target` should be provided: either `human` or `mouse`. \")\n }\n if (species_target == \"human\") {\n db.cellchat <- CellChatDB.human\n cat(\"Starting to merge the input database with CellChatDB.human... \\n\")\n } else if (species_target == \"mouse\") {\n db.cellchat <- CellChatDB.mouse\n cat(\"Starting to merge the input database with CellChatDB.mouse... \\n\")\n }\n\n # build the interaction file\n interaction_input.cellchat <- db.cellchat$interaction\n interaction_input.cellchat$source.merged <- \"CellChatDB\"\n interaction_input$source.merged <- \"User\"\n cols.common <- intersect(colnames(interaction_input), colnames(interaction_input.cellchat))\n interaction_input <- interaction_input[, cols.common]\n interaction_input.cellchat <- interaction_input.cellchat[, cols.common]\n interaction_input.merged <- rbind(interaction_input.cellchat, interaction_input)\n idx.remove <- duplicated(interaction_input.merged$interaction_name)\n if (sum(idx.remove) > 0) {\n interaction_input.merged <- interaction_input.merged[-which(idx.remove), ]\n }\n\n # build the complex file\n complex_input.cellchat <- db.cellchat$complex\n num.subunit <- max(ncol(complex_input), ncol(complex_input.cellchat))\n if (ncol(complex_input) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(complex_input)))\n complex_input <- cbind(complex_input, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(complex_input)))))\n colnames(complex_input) <- paste0(\"subunit_\", seq_len(num.subunit))\n }\n if (ncol(complex_input.cellchat) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(complex_input.cellchat)))\n complex_input.cellchat <- cbind(complex_input.cellchat, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(complex_input.cellchat)))))\n colnames(complex_input.cellchat) <- paste0(\"subunit_\", seq_len(num.subunit))\n }\n complex_input.merged <- rbind(complex_input.cellchat, complex_input)\n idx.remove <- duplicated(rownames(complex_input.merged))\n if (sum(idx.remove) > 0) {\n complex_input.merged <- complex_input.merged[-which(idx.remove), ]\n }\n\n # build the cofactor file\n cofactor_input.cellchat <- db.cellchat$cofactor\n num.subunit <- max(ncol(cofactor_input), ncol(cofactor_input.cellchat))\n if (ncol(cofactor_input) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(cofactor_input)))\n cofactor_input <- cbind(cofactor_input, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(cofactor_input)))))\n colnames(cofactor_input) <- paste0(\"cofactor\", seq_len(num.subunit))\n }\n if (ncol(cofactor_input.cellchat) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(cofactor_input.cellchat)))\n cofactor_input.cellchat <- cbind(cofactor_input.cellchat, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(cofactor_input.cellchat)))))\n colnames(cofactor_input.cellchat) <- paste0(\"cofactor\", seq_len(num.subunit))\n }\n cofactor_input.merged <- rbind(cofactor_input.cellchat, cofactor_input)\n idx.remove <- duplicated(rownames(cofactor_input.merged))\n if (sum(idx.remove) > 0) {\n cofactor_input.merged <- cofactor_input.merged[-which(idx.remove), ]\n }\n\n interaction_input <- interaction_input.merged\n complex_input <- complex_input.merged\n cofactor_input <- cofactor_input.merged\n }\n\n if (!is.null(gene_info_columnNew)) {\n checkGeneSymbol(gene_info_columnNew$Symbol, geneInfo_input)\n idx <- match(gene_info_columnNew$Symbol, geneInfo_input$Symbol)\n geneInfo_input$AntibodyName <- NA\n geneInfo_input$AntibodyName[idx[!is.na(idx)]] <- gene_info_columnNew$AntibodyName[!is.na(idx)]\n }\n db.new <- list()\n db.new$interaction <- interaction_input\n db.new$complex <- complex_input\n db.new$cofactor <- cofactor_input\n db.new$geneInfo <- geneInfo_input\n\n return(db.new)\n}\n"], ["/CellChat/R/RcppExports.R", "# Generated by using Rcpp::compileAttributes() -> do not edit by hand\n# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393\n\nComputeSNN <- function(nn_ranked, prune) {\n .Call(`_CellChat_ComputeSNN`, nn_ranked, prune)\n}\n\n"], ["/CellChat/R/data.R", "#' Ligand-receptor interactions in CellChat database for mouse\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.mouse\"\n\n#' Ligand-receptor interactions in CellChat database for human\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.human\"\n\n#' Mouse Protein-Protein interactions\n#'\n#' An adjacency matrix of the high confidence known experimental interactions\n#' between mouse proteins on STRINGdb.\n#'\n#' @format A square matrix where A_{ij}=1 if protein i interacts with protein j\n#' @source \\url{http://www.string-db.org/}\n\"PPI.mouse\"\n\n#' Ligand-receptor interactions in CellChat database for Zebrafish\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.zebrafish\"\n\n#' Human Protein-Protein interactions\n#'\n#' An adjacency matrix of the high confidence known experimental interactions\n#' between human proteins on STRINGdb.\n#'\n#' @format A square matrix where A_{ij}=1 if protein i interacts with protein j\n#' @source \\url{http://www.string-db.org/}\n\"PPI.human\"\n"], ["/CellChat/R/CellChat-package.R", "## usethis namespace: start\n#' @useDynLib CellChat, .registration = TRUE\n## usethis namespace: end\nNULL\n\n## usethis namespace: start\n#' @importFrom Rcpp sourceCpp\n## usethis namespace: end\nNULL\n"]], "task_instance_info": {"created_time": "2025-08-21 00:57:36", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(object, meta = NULL, group.by = NULL,\n datatype = c(\"RNA\", \"spatial\"), coordinates = NULL, spatial.factors = NULL,\n assay = NULL, do.sparse = T) {}", "code_description": "This code segment functions to: Construct a data structure by consolidating input sources into a unified format, validate metadata compatibility with input dimensions, process spatial coordinate data when applicable, and configure initialization parameters for subsequent analytical operations."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction(object, meta = NULL, group.by = NULL,\n datatype = c(\"RNA\", \"spatial\"), coordinates = NULL, spatial.factors = NULL,\n assay = NULL, do.sparse = T) {\n datatype <- match.arg(datatype)\n if (methods::is(object, \"Seurat\") | methods::is(object, \"SingleCellExperiment\")) {\n if (is.null(group.by)) {\n stop(\"Please define the group.by! e.g, group.by = 'ident' for Seurat object\")\n }\n if (methods::is(object, \"Seurat\")) {\n meta <- object@meta.data\n if (is.null(assay)) {\n assay <- \"RNA\"\n }\n data <- as.matrix(Seurat::GetAssayData(object = object, assay = assay, slot = \"data\"))\n } else {\n meta <- SummarizedExperiment::colData(object)\n data <- as.matrix(SingleCellExperiment::logcounts(object))\n }\n } else {\n data <- as.matrix(object)\n if (is.null(meta)) {\n stop(\"Please input the meta data\")\n } else {\n if (is.null(group.by)) {\n if (!(\"labels\" %in% colnames(meta))) {\n stop(\"Please set group.by to specify the cell group labels in meta data\")\n }\n }\n }\n }\n\n if (datatype == \"spatial\") {\n if (is.null(coordinates)) {\n stop(\"Please input the spatial coordinates of cells/spots\")\n }\n if (is.null(spatial.factors)) {\n stop(\"Please input spatial.factors containing ratio and tol parameters\")\n }\n }\n\n if (do.sparse) {\n data <- methods::as(data, \"dgCMatrix\")\n }\n\n if (is.null(group.by)) {\n labels <- meta$labels\n } else {\n labels <- meta[[group.by]]\n }\n names(labels) <- rownames(meta)\n idents <- factor(labels)\n\n cellChat <- methods::new(\n Class = \"CellChat\",\n data = data,\n data.raw = data,\n data.signaling = matrix(nrow = 0, ncol = 0),\n meta = as.data.frame(meta),\n idents = idents,\n options = list(datatype = datatype, mode = \"single\")\n )\n\n if (datatype == \"spatial\") {\n cellChat@images$coordinates <- coordinates\n cellChat@images$spatial.factors <- as.data.frame(spatial.factors)\n }\n\n return(cellChat)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 00-58-41"}, "editdistance_info": {"edit_distance": 16.8701, "calculate_time": "2025-08-21 00:58:41", "true_code_clean": "function(object, meta = NULL, group.by = NULL,\n datatype = c(\"RNA\", \"spatial\"), coordinates = NULL, spatial.factors = NULL,\n assay = NULL, do.sparse = T) {\n datatype <- match.arg(datatype)\n if (inherits(x = object, what = c(\"matrix\", \"Matrix\", \"dgCMatrix\", \"dgRMatrix\",\"CsparseMatrix\"))) {\n print(\"Create a CellChat object from a data matrix\")\n data <- object\n if (is.null(group.by)) {\n group.by <- \"labels\"\n }\n }\n if (is(object,\"Seurat\")) {\n .error_if_no_Seurat()\n print(\"Create a CellChat object from a Seurat object\")\n if (is.null(assay)) {\n assay = Seurat::DefaultAssay(object)\n if (assay == \"integrated\") {\n warning(\"The data in the `integrated` assay is not suitable for CellChat analysis! Please use the `RNA`, `SCT` or `Spatial` assay! \")\n }\n cat(paste0(\"The `data` slot in the default assay is used. The default assay is \", assay),'\\n')\n }\n if (packageVersion(\"Seurat\") < \"5.0.0\") {\n data <- object[[assay]]@data\n } else {\n data <- object[[assay]]$data\n }\n if (min(data) < 0) {\n stop(\"The data matrix contains negative values. Please ensure the normalized data matrix is used.\")\n }\n if (is.null(meta)) {\n cat(\"The `meta.data` slot in the Seurat object is used as cell meta information\",'\\n')\n meta <- object@meta.data\n meta$ident <- Seurat::Idents(object)\n }\n if (is.null(group.by)) {\n group.by <- \"ident\"\n }\n if (datatype %in% c(\"spatial\")) {\n if (is.null(coordinates)) {\n coordinates <- Seurat::GetTissueCoordinates(object, scale = NULL, cols = c(\"imagerow\", \"imagecol\"))\n }\n }\n }\n if (is(object,\"SingleCellExperiment\")) {\n print(\"Create a CellChat object from a SingleCellExperiment object\")\n if (is.null(assay)) {\n assay = \"logcounts\"\n }\n if (assay %in% SummarizedExperiment::assayNames(object)) {\n cat(paste0(\"The data in the \", assay, \" assay is used! \"),'\\n')\n data <- SummarizedExperiment::assay(object, assay)\n } else {\n stop(\"SingleCellExperiment object must contain an assay named `logcounts` or the input assay name! Please check the available assaynames via `assayNames(object)`. \\n\")\n }\n if (is.null(meta)) {\n cat(\"The `colData` assay in the SingleCellExperiment object is used as cell meta information\",'\\n')\n meta <- as.data.frame(SingleCellExperiment::colData(object))\n }\n if (is.null(group.by)) {\n stop(\"`group.by` should be defined!\")\n }\n }\n if (!inherits(x = data, what = c(\"dgCMatrix\")) & do.sparse) {\n if (inherits(x = data, what = c(\"dgRMatrix\"))) {\n data <- as(data, \"CsparseMatrix\")\n }\n data <- as(data, \"dgCMatrix\")\n }\n if (!is.null(meta)) {\n if (inherits(x = meta, what = c(\"matrix\", \"Matrix\",\"DataFrame\"))) {\n meta <- as.data.frame(x = meta)\n }\n if (!is.data.frame(meta)) {\n stop(\"The input `meta` should be a data frame\")\n }\n if (!identical(rownames(meta), colnames(data))) {\n cat(\"The cell barcodes in 'meta' is \", head(rownames(meta)),'\\n')\n warning(\"The cell barcodes in 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of 'mata'!\")\n rownames(meta) <- colnames(data)\n }\n } else {\n meta <- data.frame()\n }\n if (datatype %in% c(\"spatial\")) {\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n if (is.null(spatial.factors) | !(\"ratio\" %in% names(spatial.factors)) | !(\"tol\" %in% names(spatial.factors))) {\n stop(\"spatial.factors with colnames `ratio` and `tol` should be provided!\")\n } else {\n images = list(\"coordinates\" = coordinates,\n \"spatial.factors\" = spatial.factors)\n }\n cat(\"Create a CellChat object from spatial transcriptomics data...\",'\\n')\n } else {\n images <- list()\n }\n object <- methods::new(Class = \"CellChat\",\n data = data,\n images = images,\n meta = meta)\n if (!is.null(meta) & nrow(meta) > 0) {\n if (!(\"samples\" %in% colnames(meta))) {\n warning(\"The 'meta' data does not have a column named `samples`. We now add this column and all cells are assumed to belong to `sample1`! \\n\")\n meta$samples <- \"sample1\"\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n } else if (is.factor(meta$samples) == FALSE) {\n warning(\"The 'meta$samples' is not a factor. We now force it as a factor! \\n\")\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n }\n cat(\"Set cell identities for the new CellChat object\", '\\n')\n if (!(group.by %in% colnames(meta))) {\n stop(\"The 'group.by' is not a column name in the `meta`, which will be used for cell grouping.\")\n }\n object <- setIdent(object, ident.use = group.by) \n cat(\"The cell groups used for CellChat analysis are \", toString(levels(object@idents)), '\\n')\n }\n object@options$mode <- \"single\"\n object@options$datatype <- datatype\n return(object)\n}", "predict_code_clean": "function(object, meta = NULL, group.by = NULL,\n datatype = c(\"RNA\", \"spatial\"), coordinates = NULL, spatial.factors = NULL,\n assay = NULL, do.sparse = T) {\n datatype <- match.arg(datatype)\n if (methods::is(object, \"Seurat\") | methods::is(object, \"SingleCellExperiment\")) {\n if (is.null(group.by)) {\n stop(\"Please define the group.by! e.g, group.by = 'ident' for Seurat object\")\n }\n if (methods::is(object, \"Seurat\")) {\n meta <- object@meta.data\n if (is.null(assay)) {\n assay <- \"RNA\"\n }\n data <- as.matrix(Seurat::GetAssayData(object = object, assay = assay, slot = \"data\"))\n } else {\n meta <- SummarizedExperiment::colData(object)\n data <- as.matrix(SingleCellExperiment::logcounts(object))\n }\n } else {\n data <- as.matrix(object)\n if (is.null(meta)) {\n stop(\"Please input the meta data\")\n } else {\n if (is.null(group.by)) {\n if (!(\"labels\" %in% colnames(meta))) {\n stop(\"Please set group.by to specify the cell group labels in meta data\")\n }\n }\n }\n }\n if (datatype == \"spatial\") {\n if (is.null(coordinates)) {\n stop(\"Please input the spatial coordinates of cells/spots\")\n }\n if (is.null(spatial.factors)) {\n stop(\"Please input spatial.factors containing ratio and tol parameters\")\n }\n }\n if (do.sparse) {\n data <- methods::as(data, \"dgCMatrix\")\n }\n if (is.null(group.by)) {\n labels <- meta$labels\n } else {\n labels <- meta[[group.by]]\n }\n names(labels) <- rownames(meta)\n idents <- factor(labels)\n cellChat <- methods::new(\n Class = \"CellChat\",\n data = data,\n data.raw = data,\n data.signaling = matrix(nrow = 0, ncol = 0),\n meta = as.data.frame(meta),\n idents = idents,\n options = list(datatype = datatype, mode = \"single\")\n )\n if (datatype == \"spatial\") {\n cellChat@images$coordinates <- coordinates\n cellChat@images$spatial.factors <- as.data.frame(spatial.factors)\n }\n return(cellChat)\n}"}} {"repo_name": "CellChat", "file_name": "/CellChat/R/visualization.R", "inference_info": {"prefix_code": "#' ggplot theme in CellChat\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#' @importFrom ggplot2 theme_classic element_rect theme element_blank element_line element_text\nCellChat_theme_opts <- function() {\n theme(strip.background = element_rect(colour = \"white\", fill = \"white\")) +\n theme_classic() +\n theme(panel.border = element_blank()) +\n theme(axis.line.x = element_line(color = \"black\")) +\n theme(axis.line.y = element_line(color = \"black\")) +\n theme(panel.grid.minor.x = element_blank(), panel.grid.minor.y = element_blank()) +\n theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_blank()) +\n theme(panel.background = element_rect(fill = \"white\")) +\n theme(legend.key = element_blank()) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))\n}\n\n\n#' Generate ggplot2 colors\n#'\n#' @param n number of colors to generate\n#' @importFrom grDevices hcl\n#' @export\n#'\nggPalette <- function(n) {\n hues = seq(15, 375, length = n + 1)\n grDevices::hcl(h = hues, l = 65, c = 100)[1:n]\n}\n\n#' Generate colors from a customed color palette\n#'\n#' @param n number of colors\n#'\n#' @return A color palette for plotting\n#' @importFrom grDevices colorRampPalette\n#'\n#' @export\n#'\nscPalette <- function(n) {\n colorSpace <- c('#E41A1C','#377EB8','#4DAF4A','#984EA3','#F29403','#F781BF','#BC9DCC','#A65628','#54B0E4','#222F75','#1B9E77','#B2DF8A',\n '#E3BE00','#FB9A99','#E7298A','#910241','#00CDD1','#A6CEE3','#CE1261','#5E4FA2','#8CA77B','#00441B','#DEDC00','#DCF0B9','#8DD3C7','#999999')\n if (n <= length(colorSpace)) {\n colors <- colorSpace[1:n]\n } else {\n colors <- grDevices::colorRampPalette(colorSpace)(n)\n }\n return(colors)\n}\n\n#' Visualize the inferred cell-cell communication network\n#'\n#' Automatically save plots in the current working directory.\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param top the fraction of interactions to show (0 < top <= 1)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max.individual the maximum weight of edge when plotting the individual L-R netwrok; defualt = max(net)\n#' @param edge.weight.max.aggregate the maximum weight of edge when plotting the aggregated signaling pathway network\n#' @param edge.width.max The maximum edge width for visualization\n#' @param layout \"hierarchy\", \"circle\" or \"chord\"\n#' @param height height of plot\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param pt.title font size of the text\n#' @param title.space the space between the title and plot\n#' @param vertex.label.cex The label size of vertex in the network\n#' @param out.format the format of output figures: svg, png and pdf\n#'\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the network mediated by ligand-receptor using \"circle\" or \"chord\"\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x, text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`. NB: some parameters might be not supported\n#' @importFrom svglite svglite\n#' @importFrom grDevices dev.off pdf\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#'\nnetVisual <- function(object, signaling, signaling.name = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max.individual = NULL, edge.weight.max.aggregate = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, pt.title = 12, title.space = 6, vertex.label.cex = 0.8,from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n out.format = c(\"svg\",\"png\"),\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n if (is.null(edge.weight.max.individual)) {\n edge.weight.max.individual = max(prob)\n }\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.null(edge.weight.max.aggregate)) {\n edge.weight.max.aggregate = max(prob.sum)\n }\n\n if (layout == \"hierarchy\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_individual.svg\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_individual.png\"), width = 8, height = nRow*height, units = \"in\",res = 300)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name, \"_hierarchy_individual.pdf\"), width = 8, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_individual.pdf\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n\n\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_aggregate.svg\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_aggregate.png\"), width = 7, height = 1*height, units = \"in\",res = 300)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name, \"_hierarchy_aggregate.pdf\"), width = 7, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_aggregate.pdf\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n\n } else if (layout == \"circle\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"spatial\") {\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"chord\") {\n if (is.element(\"svg\", out.format)) {\n\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n }\n\n}\n\n\n#' Visualize the inferred signaling network of signaling pathways by aggregating all L-R pairs\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param layout \"hierarchy\", \"circle\", \"chord\" or \"spatial\"\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param pt.title font size of the text\n#' @param title.space the space between the title and plot\n#' @param vertex.label.cex The label size of vertex in the network\n#'\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x,text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`,`netVisual_spatial`. NB: some parameters might be not supported\n#' @importFrom grDevices recordPlot\n#'\n#' @return an object of class \"recordedplot\" or ggplot\n#' @export\n#'\n#'\nnetVisual_aggregate <- function(object, signaling, signaling.name = NULL, color.use = NULL, thresh = 0.05, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"),\n pt.title = 12, title.space = 6, vertex.label.cex = 0.8,\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20,\n ...) {\n layout <- match.arg(layout)\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n\n if (layout == \"hierarchy\") {\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.null(edge.weight.max)) {\n edge.weight.max = max(prob.sum)\n }\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n } else if (layout == \"circle\") {\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n gg <- netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n } else if (layout == \"spatial\") {\n prob.sum <- apply(prob, c(1,2), sum)\n if (vertex.weight == \"incoming\"){\n if (length(slot(object, \"netP\")$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n vertex.weight = object@netP$centr[[signaling]]$indeg\n } else if (vertex.weight == \"outgoing\"){\n if (length(slot(object, \"netP\")$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n vertex.weight = object@netP$centr[[signaling]]$outdeg\n }\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n\n } else if (layout == \"chord\") {\n prob.sum <- apply(prob, c(1,2), sum)\n gg <- netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y= legend.pos.y)\n }\n\n return(gg)\n\n}\n\n\n\n#' Visualize the inferred signaling network of individual L-R pairs\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param pairLR.use a char vector or a data frame consisting of one column named \"interaction_name\", defining the L-R pairs of interest\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector.\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex in the network\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param graphics.init whether do graphics initiation using par(...). If graphics.init=FALSE, USERS can use par() in a more fexible way\n#' @param layout \"hierarchy\", \"circle\" or \"chord\"\n#' @param height height of plot\n#' @param thresh threshold of the p-value for determining significant interaction\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n# #' @param vertex.size Deprecated. Use `vertex.weight`\n\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the figures using \"circle\" or \"chord\"\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x, text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`. NB: some parameters might be not supported\n#' @importFrom grDevices dev.off pdf\n#'\n#' @return an object of class \"recordedplot\"\n#' @export\n#'\n#'\nnetVisual_individual <- function(object, signaling, signaling.name = NULL, pairLR.use = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex = 0.8,\n weight.scale = TRUE, edge.weight.max = NULL, edge.width.max=8, graphics.init = TRUE,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, #from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n # if (!is.null(vertex.size)) {\n # warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n # }\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n if (!is.null(pairLR.use)) {\n if (is.data.frame(pairLR.use)) {\n pairLR.name <- intersect(pairLR.name, as.character(pairLR.use$interaction_name))\n } else {\n pairLR.name <- intersect(pairLR.name, as.character(pairLR.use))\n }\n\n if (length(pairLR.name) == 0) {\n stop(\"There is no significant communication for the input L-R pairs!\")\n }\n }\n\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n if (is.null(edge.weight.max)) {\n edge.weight.max = max(prob)\n }\n\n if (layout == \"hierarchy\") {\n if (graphics.init) {\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n }\n\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i,...)\n }\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n\n } else if (layout == \"circle\") {\n # par(mfrow=c(nRow,1))\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n gg[[i]] <- netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n } else if (layout == \"spatial\") {\n # par(mfrow=c(nRow,1))\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n gg[[i]] <- netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n } else if (layout == \"chord\") {\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n gg[[i]] <- netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y)\n }\n }\n return(gg)\n}\n\n\n\n#' Hierarchy plot of cell-cell communications sending to cell groups in vertex.receiver\n#'\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net a weighted matrix defining the signaling network\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether rescale the edge weights\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.dist the distance between labels and dot position\n#' @param space.v the space between different columns in the plot\n#' @param space.h the space between different rows in the plot\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param alpha.edge the transprency of edge\n#' @param label.edge whether label edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_\n#' @importFrom grDevices adjustcolor recordPlot\n#' @importFrom shape Arrows\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_hierarchy1 <- function(net, vertex.receiver, color.use = NULL, title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight=20, vertex.weight.max = NULL, vertex.size.max = NULL,\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6,\n label.dist = 2.8, space.v = 1.5, space.h = 1.6, shape= NULL, label.edge=FALSE,edge.curved=0, margin=0.2,\n vertex.label.cex=0.6,vertex.label.color= \"black\",arrow.width=1,arrow.size = 0.2,edge.label.color='black',edge.label.cex=0.5, vertex.size = NULL){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n cells.level <- rownames(net)\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n if (is.null(color.use)) {\n color.use <- scPalette(nrow(net))\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+6\n\n m <- length(vertex.receiver)\n net2 <- net\n reorder.row <- c(vertex.receiver, setdiff(1:nrow(net),vertex.receiver))\n net2 <- net2[reorder.row,vertex.receiver]\n # Expand out to symmetric (M+N)x(M+N) matrix\n m1 <- nrow(net2); n1 <- ncol(net2)\n net3 <- rbind(cbind(matrix(0, m1, m1), net2), matrix(0, n1, m1+n1))\n\n row.names(net3) <- c(row.names(net)[vertex.receiver], row.names(net)[setdiff(1:m1,vertex.receiver)], rep(\"\",m))\n colnames(net3) <- row.names(net3)\n color.use3 <- c(color.use[vertex.receiver], color.use[setdiff(1:m1,vertex.receiver)], rep(\"#FFFFFF\",length(vertex.receiver)))\n color.use3.frame <- c(color.use[vertex.receiver], color.use[setdiff(1:m1,vertex.receiver)], color.use[vertex.receiver])\n\n if (length(vertex.weight) != 1) {\n vertex.weight = c(vertex.weight[vertex.receiver], vertex.weight[setdiff(1:m1,vertex.receiver)],vertex.weight[vertex.receiver])\n }\n if (is.null(shape)) {\n shape <- c(rep(\"circle\",m), rep(\"circle\", m1-m), rep(\"circle\",m))\n }\n\n g <- graph_from_adjacency_matrix(net3, mode = \"directed\", weighted = T)\n edge.start <- ends(g, es=E(g), names=FALSE)\n coords <- matrix(NA, nrow(net3), 2)\n coords[1:m,1] <- 0; coords[(m+1):m1,1] <- space.h; coords[(m1+1):nrow(net3),1] <- space.h/2;\n coords[1:m,2] <- seq(space.v, 0, by = -space.v/(m-1)); coords[(m+1):m1,2] <- seq(space.v, 0, by = -space.v/(m1-m-1));coords[(m1+1):nrow(net3),2] <- seq(space.v, 0, by = -space.v/(n1-1));\n coords_scale<-coords\n\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use3[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use3.frame[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n E(g)$label<-E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n # E(g)$width<-0.3+edge.max.width/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n E(g)$width<- 0.3+E(g)$weight/edge.weight.max*edge.width.max\n }else{\n E(g)$width<-0.3+edge.width.max*E(g)$weight\n }\n\n E(g)$arrow.width<-arrow.width\n E(g)$arrow.size<-arrow.size\n E(g)$label.color<-edge.label.color\n E(g)$label.cex<-edge.label.cex\n E(g)$color<-adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n\n label.dist <- c(rep(space.h*label.dist,m), rep(space.h*label.dist, m1-m),rep(0, nrow(net3)-m1))\n label.locs <- c(rep(-pi, m), rep(0, m1-m),rep(-pi, nrow(net3)-m1))\n # text.pos <- cbind(c(-space.h/1.5, space.h/10, space.h/1.2), space.v-space.v/10)\n text.pos <- cbind(c(-space.h/1.5, space.h/22, space.h/1.5), space.v-space.v/7)\n igraph::add.vertex.shape(\"fcircle\", clip=igraph::igraph.shape.noclip,plot=mycircle, parameters=list(vertex.frame.color=1, vertex.frame.width=1))\n plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin,rescale=T,vertex.shape=\"fcircle\", vertex.frame.width = c(rep(1,m1), rep(2,nrow(net3)-m1)),\n vertex.label.degree=label.locs, vertex.label.dist=label.dist, vertex.label.family=\"Helvetica\")\n text(text.pos, c(\"Source\",\"Target\",\"Source\"), cex = 0.8, col = c(\"#c51b7d\",\"#c51b7d\",\"#2f6661\"))\n arrow.pos1 <- c(-space.h/1.5, space.v-space.v/4, space.h/100000, space.v-space.v/4)\n arrow.pos2 <- c(space.h/1.5, space.v-space.v/4, space.h/20, space.v-space.v/4)\n shape::Arrows(arrow.pos1[1], arrow.pos1[2], arrow.pos1[3], arrow.pos1[4], col = \"#c51b7d\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n shape::Arrows(arrow.pos2[1], arrow.pos2[2], arrow.pos2[3], arrow.pos2[4], col = \"#2f6661\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n if (!is.null(title.name)) {\n title.pos = c(space.h/8, space.v)\n text(title.pos[1],title.pos[2],paste0(title.name, \" signaling network\"), cex = 1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Hierarchy plot of cell-cell communication sending to cell groups not in vertex.receiver\n#'\n#' This function loads the significant interactions as a weighted matrix, and colors\n#' represent different types of cells as a structure. The width of edges represent the strength of the communication.\n#'\n#' @param net a weighted matrix defining the signaling network\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether rescale the edge weights\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.dist the distance between labels and dot position\n#' @param space.v the space between different columns in the plot\n#' @param space.h the space between different rows in the plot\n#' @param label.edge Whether or not shows the label of edges (number of connections between different cell types)\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_\n#' @importFrom grDevices adjustcolor recordPlot\n#' @importFrom shape Arrows\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_hierarchy2 <-function(net, vertex.receiver, color.use = NULL, title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight=20, vertex.weight.max = NULL, vertex.size.max = NULL,\n edge.weight.max = NULL, edge.width.max=8,alpha.edge = 0.6,\n label.dist = 2.8, space.v = 1.5, space.h = 1.6, shape= NULL, label.edge=FALSE,edge.curved=0, margin=0.2,\n vertex.label.cex=0.6,vertex.label.color= \"black\",arrow.width=1,arrow.size = 0.2,edge.label.color='black',edge.label.cex=0.5, vertex.size = NULL){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- levels(object@idents)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- levels(object@idents)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- levels(object@idents)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n\n if (is.null(color.use)) {\n color.use <- scPalette(nrow(net))\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+6\n\n m <- length(vertex.receiver)\n m0 <- nrow(net)-length(vertex.receiver)\n net2 <- net\n reorder.row <- c(setdiff(1:nrow(net),vertex.receiver), vertex.receiver)\n net2 <- net2[reorder.row,vertex.receiver]\n # Expand out to symmetric (M+N)x(M+N) matrix\n m1 <- nrow(net2); n1 <- ncol(net2)\n net3 <- rbind(cbind(matrix(0, m1, m1), net2), matrix(0, n1, m1+n1))\n row.names(net3) <- c(row.names(net)[setdiff(1:m1,vertex.receiver)],row.names(net)[vertex.receiver], rep(\"\",m))\n colnames(net3) <- row.names(net3)\n color.use3 <- c(color.use[setdiff(1:m1,vertex.receiver)],color.use[vertex.receiver], rep(\"#FFFFFF\",length(vertex.receiver)))\n color.use3.frame <- c(color.use[setdiff(1:m1,vertex.receiver)], color.use[vertex.receiver], color.use[vertex.receiver])\n\n\n if (length(vertex.weight) != 1) {\n vertex.weight = c(vertex.weight[setdiff(1:m1,vertex.receiver)], vertex.weight[vertex.receiver], vertex.weight[vertex.receiver])\n }\n if (is.null(shape)) {\n shape <- rep(\"circle\",nrow(net3))\n }\n\n g <- graph_from_adjacency_matrix(net3, mode = \"directed\", weighted = T)\n edge.start <- ends(g, es=igraph::E(g), names=FALSE)\n coords <- matrix(NA, nrow(net3), 2)\n coords[1:m0,1] <- 0; coords[(m0+1):m1,1] <- space.h; coords[(m1+1):nrow(net3),1] <- space.h/2;\n coords[1:m0,2] <- seq(space.v, 0, by = -space.v/(m0-1)); coords[(m0+1):m1,2] <- seq(space.v, 0, by = -space.v/(m1-m0-1));coords[(m1+1):nrow(net3),2] <- seq(space.v, 0, by = -space.v/(n1-1));\n coords_scale<-coords\n\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use3[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use3.frame[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n # E(g)$width<-0.3+edge.max.width/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n igraph::E(g)$color<-adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n\n label.dist <- c(rep(space.h*label.dist,m), rep(space.h*label.dist, m1-m),rep(0, nrow(net3)-m1))\n label.locs <- c(rep(-pi, m0), rep(0, m1-m0),rep(-pi, nrow(net3)-m1))\n #text.pos <- cbind(c(-space.h/1.5, space.h/10, space.h/1.2), space.v-space.v/10)\n text.pos <- cbind(c(-space.h/1.5, space.h/22, space.h/1.5), space.v-space.v/7)\n igraph::add.vertex.shape(\"fcircle\", clip=igraph::igraph.shape.noclip,plot=mycircle, parameters=list(vertex.frame.color=1, vertex.frame.width=1))\n plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin,rescale=T,vertex.shape=\"fcircle\", vertex.frame.width = c(rep(1,m1), rep(2,nrow(net3)-m1)),\n vertex.label.degree=label.locs, vertex.label.dist=label.dist, vertex.label.family=\"Helvetica\")\n text(text.pos, c(\"Source\",\"Target\",\"Source\"), cex = 0.8, col = c(\"#c51b7d\",\"#2f6661\",\"#2f6661\"))\n\n arrow.pos1 <- c(-space.h/1.5, space.v-space.v/4, space.h/100000, space.v-space.v/4)\n arrow.pos2 <- c(space.h/1.5, space.v-space.v/4, space.h/20, space.v-space.v/4)\n shape::Arrows(arrow.pos1[1], arrow.pos1[2], arrow.pos1[3], arrow.pos1[4], col = \"#c51b7d\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n shape::Arrows(arrow.pos2[1], arrow.pos2[2], arrow.pos2[3], arrow.pos2[4], col = \"#2f6661\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n\n if (!is.null(title.name)) {\n title.pos = c(space.h/8, space.v)\n text(title.pos[1],title.pos[2],paste0(title.name, \" signaling network\"), cex = 1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Circle plot of cell-cell communication network\n#'\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net A weighted matrix representing the connections\n#' @param color.use Colors represent different cell groups\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.edge Whether or not shows the label of edges\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param layout The layout specification. It must be a call to a layout\n#' specification function.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param text.x,text.y the x- and y-coordinates to add the text\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_ in_circle\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_circle <-function(net, color.use = NULL,title.name = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex=1,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6, label.edge = FALSE,edge.label.color='black',edge.label.cex=0.8,\n edge.curved=0.2,shape='circle',layout=in_circle(), margin=0.2, vertex.size = NULL,\n arrow.width=1,arrow.size = 0.2,\n text.x = 0, text.y = 1.5){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use)) | (!is.null(idents.use)) ) {\n if (is.null(rownames(net))) {\n stop(\"The input weighted matrix should have rownames!\")\n }\n cells.level <- rownames(net)\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n df.net <- filter(df.net, (source %in% idents.use) | (target %in% idents.use))\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (is.null(color.use)) {\n color.use = scPalette(nrow(net))\n names(color.use) <- rownames(net)\n } else {\n if (is.null(names(color.use))) {\n stop(\"The input `color.use` should be a named vector! \\n\")\n }\n }\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx.isolate <- intersect(idx1, idx2)\n if (length(idx.isolate) > 0) {\n net <- net[-idx.isolate, ]\n net <- net[, -idx.isolate]\n color.use = color.use[-idx.isolate]\n if (length(unique(vertex.weight)) > 1) {\n vertex.weight <- vertex.weight[-idx.isolate]\n }\n }\n }\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edge.start <- igraph::ends(g, es=igraph::E(g), names=FALSE)\n coords<-layout_(g,layout)\n if(nrow(coords)!=1){\n coords_scale=scale(coords)\n }else{\n coords_scale<-coords\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n\n loop.angle<-ifelse(coords_scale[igraph::V(g),1]>0,-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]),pi-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]))\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n #E(g)$width<-0.3+edge.width.max/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n igraph::E(g)$color<- grDevices::adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n igraph::E(g)$loop.angle <- rep(0, length(igraph::E(g)))\n\n if(sum(edge.start[,2]==edge.start[,1])!=0){\n igraph::E(g)$loop.angle[which(edge.start[,2]==edge.start[,1])]<-loop.angle[edge.start[which(edge.start[,2]==edge.start[,1]),1]]\n }\n radian.rescale <- function(x, start=0, direction=1) {\n c.rotate <- function(x) (x + start) %% (2 * pi) * direction\n c.rotate(scales::rescale(x, c(0, 2 * pi), range(x)))\n }\n label.locs <- radian.rescale(x=1:length(igraph::V(g)), direction=-1, start=0)\n label.dist <- vertex.weight/max(vertex.weight)+2\n plot(g,edge.curved=edge.curved,vertex.shape=shape,layout=coords_scale,margin=margin, vertex.label.dist=label.dist,\n vertex.label.degree=label.locs, vertex.label.family=\"Helvetica\", edge.label.family=\"Helvetica\") # \"sans\"\n if (!is.null(title.name)) {\n text(text.x,text.y,title.name, cex = 1.1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n\n#' generate circle symbol\n#'\n#' @param coords coordinates of points\n#' @param v vetex\n#' @param params parameters\n#' @importFrom graphics symbols\n#' @return\nmycircle <- function(coords, v=NULL, params) {\n vertex.color <- params(\"vertex\", \"color\")\n if (length(vertex.color) != 1 && !is.null(v)) {\n vertex.color <- vertex.color[v]\n }\n vertex.size <- 1/200 * params(\"vertex\", \"size\")\n if (length(vertex.size) != 1 && !is.null(v)) {\n vertex.size <- vertex.size[v]\n }\n vertex.frame.color <- params(\"vertex\", \"frame.color\")\n if (length(vertex.frame.color) != 1 && !is.null(v)) {\n vertex.frame.color <- vertex.frame.color[v]\n }\n vertex.frame.width <- params(\"vertex\", \"frame.width\")\n if (length(vertex.frame.width) != 1 && !is.null(v)) {\n vertex.frame.width <- vertex.frame.width[v]\n }\n\n mapply(coords[,1], coords[,2], vertex.color, vertex.frame.color,\n vertex.size, vertex.frame.width,\n FUN=function(x, y, bg, fg, size, lwd) {\n symbols(x=x, y=y, bg=bg, fg=fg, lwd=lwd,\n circles=size, add=TRUE, inches=FALSE)\n })\n}\n\n\n#' Spatial plot of cell-cell communication network\n#'\n#' Autocrine interactions are omitted on this plot. Group centroids may be not accurate for some data due to complex geometry.\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net A weighted matrix representing the connections\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param meta a data frame with at least two columns named `labels` and `samples`.\n#' `meta$labels` is a vector giving the group label of each cell/spot. `meta$samples` is a factor vector defining the sample labels of each dataset. The length should be the same as the number of rows in `coordinates`.\n#' @param sample.use the sample used for visualization, which should be the element in `meta$samples`.\n#' @param color.use Colors represent different cell groups\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param remove.loop whether remove the self-loop in the communication network. Default: TRUE\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param alpha.edge the transprency of edge\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param arrow.angle The width of arrows\n#' @param alpha.image the transparency of individual spots\n# #' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param point.size the size of spots\n#' @param legend.size the size of legend\n#' @importFrom igraph graph_from_adjacency_matrix get.edgelist ends E V\n#' @import ggplot2\n#' @importFrom ggnetwork geom_nodetext_repel\n#' @return an object of ggplot\n#' @export\nnetVisual_spatial <-function(net, coordinates, meta, sample.use = NULL, color.use = NULL,title.name = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE, remove.loop = TRUE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex = 5,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, edge.curved=0.2, alpha.edge = 0.6, arrow.angle = 5, arrow.size = 0.2, alpha.image = 0.15, point.size = 1.5, legend.size = 5){\n cells.level <- rownames(net)\n labels <- meta$labels\n samples <- meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n num_cluster <- length(cells.level)\n node_coords <- matrix(0, nrow = num_cluster, ncol = 2)\n for (i in c(1:num_cluster)) {\n node_coords[i,1] <- median(coordinates[as.character(labels) == cells.level[i], 1])\n node_coords[i,2] <- median(coordinates[as.character(labels) == cells.level[i], 2])\n }\n rownames(node_coords) <- cells.level\n\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use)) | (!is.null(idents.use)) ) {\n if (is.null(rownames(net))) {\n stop(\"The input weighted matrix should have rownames!\")\n }\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n df.net <- filter(df.net, (source %in% idents.use) | (target %in% idents.use))\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n\n if (remove.loop) {\n diag(net) <- 0\n }\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n node_coords <- node_coords[-idx, ]\n cells.level <- cells.level[-idx]\n }\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edgelist <- get.edgelist(g)\n # loop_curve = c()\n # for (i in c(1:nrow(edgelist))) {\n # if (edgelist[i,1] == edgelist[i,2]){\n # loop_curve = c(loop_curve ,i)\n # }\n # }\n # edgelist <- edgelist[-loop_curve,]\n\n edges <- data.frame(node_coords[edgelist[,1],,drop =FALSE], node_coords[edgelist[,2],,drop =FALSE])\n colnames(edges) <- c(\"X1\",\"Y1\",\"X2\",\"Y2\")\n node_coords = data.frame(node_coords)\n node_idents = factor(cells.level, levels = cells.level)\n node_family = data.frame(node_coords,node_idents)\n if (is.null(color.use)) {\n color.use = scPalette(length(igraph::V(g)))\n names(color.use) <- cells.level\n }\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n # width of edge\n if (weight.scale == TRUE) {\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n gg <- ggplot(data=node_family,aes(X1, X2)) +\n geom_curve(aes(x=X1, y=Y1, xend = X2, yend = Y2), data=edges, size = igraph::E(g)$width, curvature = edge.curved, alpha = alpha.edge, arrow = arrow(angle = arrow.angle, type = \"closed\",length = unit(arrow.size, \"inches\")),colour=color.use[edgelist[,1]]) +\n geom_point(aes(X1, X2,colour = node_idents), data=node_family, size = vertex.weight,show.legend = TRUE) +scale_color_manual(values = color.use) +\n guides(color = guide_legend(override.aes = list(size=legend.size))) +\n xlab(NULL) + ylab(NULL) +\n coord_fixed() + theme(aspect.ratio = 1)+ theme(legend.key = element_blank()) +\n theme(panel.background = element_blank(),axis.ticks = element_blank(), panel.border = element_blank(),axis.text=element_blank(),legend.title = element_blank())\n\n gg <- gg + geom_point(aes(x_cent, y_cent), data = coordinates,colour = color.use[labels],alpha = alpha.image, size = point.size, show.legend = FALSE)\n gg <- gg + scale_y_reverse()\n if (vertex.label.cex > 0){\n gg <- gg + ggnetwork::geom_nodetext_repel(aes(label = node_idents), color=\"black\", size = vertex.label.cex)\n }\n if (!is.null(title.name)){\n gg <- gg + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0))\n }\n\n gg\n return(gg)\n\n}\n\n\n\n\n\n\n#' Circle plot showing differential cell-cell communication network between two datasets\n#'\n#' The width of edges represent the relative number of interactions or interaction strength.\n#' Red (or blue) colored edges represent increased (or decreased) signaling in the second dataset compared to the first one.\n#'\n#' @param object A merged CellChat objects\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param color.use Colors represent different cell groups\n#' @param color.edge Colors for indicating whether the signaling is increased (`color.edge[1]`) or decreased (`color.edge[2]`)\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.edge Whether or not shows the label of edges\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param layout The layout specification. It must be a call to a layout\n#' specification function.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n# #' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_ in_circle\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_diffInteraction <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\", \"count.merged\", \"weight.merged\"), color.use = NULL, color.edge = c('#b2182b','#2166ac'), title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = 15, vertex.label.cex=1,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6, label.edge = FALSE,edge.label.color='black',edge.label.cex=0.8,\n edge.curved=0.2,shape='circle',layout=in_circle(), margin=0.2,\n arrow.width=1,arrow.size = 0.2){\n options(warn = -1)\n measure <- match.arg(measure)\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n if (measure %in% c(\"count\", \"count.merged\")) {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure %in% c(\"weight\", \"weight.merged\")) {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n net <- net.diff\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- rownames(net.diff)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n net[is.na(net)] <- 0\n }\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n net[abs(net) < stats::quantile(abs(net), probs = 1-top, na.rm= T)] <- 0\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edge.start <- igraph::ends(g, es=igraph::E(g), names=FALSE)\n coords<-layout_(g,layout)\n if(nrow(coords)!=1){\n coords_scale=scale(coords)\n }else{\n coords_scale<-coords\n }\n if (is.null(color.use)) {\n color.use = scPalette(length(igraph::V(g)))\n }\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n\n loop.angle<-ifelse(coords_scale[igraph::V(g),1]>0,-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]),pi-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]))\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n #igraph::E(g)$color<- grDevices::adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n igraph::E(g)$color <- ifelse(igraph::E(g)$weight > 0, color.edge[1],color.edge[2])\n igraph::E(g)$color <- grDevices::adjustcolor(igraph::E(g)$color, alpha.edge)\n\n igraph::E(g)$weight <- abs(igraph::E(g)$weight)\n\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n #E(g)$width<-0.3+edge.width.max/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n igraph::E(g)$loop.angle <- 0\n if(sum(edge.start[,2]==edge.start[,1])!=0){\n igraph::E(g)$loop.angle[which(edge.start[,2]==edge.start[,1])]<-loop.angle[edge.start[which(edge.start[,2]==edge.start[,1]),1]]\n }\n radian.rescale <- function(x, start=0, direction=1) {\n c.rotate <- function(x) (x + start) %% (2 * pi) * direction\n c.rotate(scales::rescale(x, c(0, 2 * pi), range(x)))\n }\n label.locs <- radian.rescale(x=1:length(igraph::V(g)), direction=-1, start=0)\n label.dist <- vertex.weight/max(vertex.weight)+2\n plot(g,edge.curved=edge.curved,vertex.shape=shape,layout=coords_scale,margin=margin, vertex.label.dist=label.dist,\n vertex.label.degree=label.locs, vertex.label.family=\"Helvetica\", edge.label.family=\"Helvetica\") # \"sans\"\n if (!is.null(title.name)) {\n text(0,1.5,title.name, cex = 1.1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Visualization of network using heatmap\n#'\n#' This heatmap can be used to 1) show differential number of interactions or interaction strength in the cell-cell communication network between two datasets;\n#' 2) the number of interactions or interaction strength in a single dataset;\n#' 3) the inferred cell-cell communication network in a single dataset, defined by `signaling`. Please see @Details below for detailed explanations of this heatmap plot.\n#'\n#' When show differential number of interactions or interaction strength in the cell-cell communication network between two datasets, the width of edges represent the relative number of interactions or interaction strength.\n#' Red (or blue) colored edges represent increased (or decreased) signaling in the second dataset compared to the first one.\n#'\n#' The top colored bar plot represents the sum of absolute values displayed in each column of the heatmap. The right colored bar plot represents the sum of absolute values in each row.\n#'\n#'\n#' @param object A merged CellChat object or a single CellChat object\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param signaling a character vector giving the name of signaling networks in a single CellChat object\n#' @param slot.name the slot name of object. Set is to be \"netP\" if input signaling is a pathway name; Set is to be \"net\" if input signaling is a ligand-receptor pair\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap A vector of two colors corresponding to max/min values, or a color name in brewer.pal only when the data in the heatmap do not contain negative values.\n#' By default, color.heatmap = c('#2166ac','#b2182b') when taking a merged CellChat object as input; color.heatmap = \"Reds\" when taking a single CellChat object as input.\n#' @param title.name the name of the title\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param row.show,col.show a vector giving the index or the name of row or columns to show in the heatmap\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation anno_barplot rowAnnotation\n#' @return an object of ComplexHeatmap\n#' @export\nnetVisual_heatmap <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\"), signaling = NULL, slot.name = c(\"netP\", \"net\"), color.use = NULL, color.heatmap = NULL,\n title.name = NULL, width = NULL, height = NULL, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE,\n sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, row.show = NULL, col.show = NULL){\n if (!is.null(measure)) {\n measure <- match.arg(measure)\n }\n slot.name <- match.arg(slot.name)\n if (class(object@net[[1]]) == \"list\") {\n message(\"Do heatmap based on a merged object \\n\")\n if (is.null(color.heatmap)) {\n color.heatmap <- c('#2166ac','#b2182b')\n }\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n legend.name = \"Relative values\"\n } else {\n message(\"Do heatmap based on a single object \\n\")\n if (is.null(color.heatmap)) {\n color.heatmap <- \"Reds\"\n }\n if (!is.null(signaling)) {\n prob <- slot(object, slot.name)$prob\n if (slot.name == \"net\") {\n prob[object@net$pval > thresh] <- 0\n }\n net.diff <- prob[,,signaling]\n if (is.null(title.name)) {\n title.name = paste0(signaling, \" signaling network\")\n }\n legend.name <- \"Communication Prob.\"\n } else if (!is.null(measure)) {\n net.diff <- object@net[[measure]]\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Interaction strength\"\n }\n }\n legend.name <- title.name\n }\n }\n\n net <- net.diff\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- rownames(net.diff)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (is.null(color.use)) {\n color.use <- scPalette(ncol(net))\n }\n names(color.use) <- colnames(net)\n color.use.row <- color.use\n color.use.col <- color.use\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n #idx <- intersect(idx1, idx2)\n # if (length(idx) > 0) {\n # net <- net[-idx, ]\n # net <- net[, -idx]\n # }\n if (length(idx1) > 0) {\n net <- net[-idx1, ]\n color.use.row <- color.use.row[-idx1]\n }\n if (length(idx2) > 0) {\n net <- net[, -idx2]\n color.use.col <- color.use.col[-idx2]\n }\n }\n\n mat <- net\n if (!is.null(row.show)) {\n mat <- mat[row.show, , drop=FALSE]\n color.use.row <- color.use.row[row.show]\n }\n if (!is.null(col.show)) {\n mat <- mat[ ,col.show, drop=FALSE]\n color.use.col <- color.use.col[col.show]\n }\n\n\n if (min(mat) < 0) {\n color.heatmap.use = colorRamp3(c(min(mat), 0, max(mat)), c(color.heatmap[1], \"#f7f7f7\", color.heatmap[2]))\n colorbar.break <- c(round(min(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",min(mat, na.rm = T)))+1), 0, round(max(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",max(mat, na.rm = T)))+1))\n # color.heatmap.use = colorRamp3(c(seq(min(mat), -(max(mat)-min(max(mat)))/9, length.out = 4), 0, seq((max(mat)-min(max(mat)))/9, max(mat), length.out = 4)), RColorBrewer::brewer.pal(n = 9, name = color.heatmap))\n } else {\n if (length(color.heatmap) == 3) {\n color.heatmap.use = colorRamp3(c(0, min(mat), max(mat)), color.heatmap)\n } else if (length(color.heatmap) == 2) {\n color.heatmap.use = colorRamp3(c(min(mat), max(mat)), color.heatmap)\n } else if (length(color.heatmap) == 1) {\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n }\n colorbar.break <- c(round(min(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",min(mat, na.rm = T)))+1), round(max(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",max(mat, na.rm = T)))+1))\n }\n # col_fun(as.vector(mat))\n\n df.col<- data.frame(group = colnames(mat)); rownames(df.col) <- colnames(mat)\n df.row<- data.frame(group = rownames(mat)); rownames(df.row) <- rownames(mat)\n col_annotation <- HeatmapAnnotation(df = df.col, col = list(group = color.use.col),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n row_annotation <- HeatmapAnnotation(df = df.row, col = list(group = color.use.row), which = \"row\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ha1 = rowAnnotation(Strength = anno_barplot(rowSums(abs(mat)), border = FALSE,gp = gpar(fill = color.use.row, col=color.use.row)), show_annotation_name = FALSE)\n ha2 = HeatmapAnnotation(Strength = anno_barplot(colSums(abs(mat)), border = FALSE,gp = gpar(fill = color.use.col, col=color.use.col)), show_annotation_name = FALSE)\n\n if (sum(abs(mat) > 0) == 1) {\n color.heatmap.use = c(\"white\", color.heatmap.use)\n } else {\n mat[mat == 0] <- NA\n }\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = legend.name,\n bottom_annotation = col_annotation, left_annotation =row_annotation, top_annotation = ha2, right_annotation = ha1,\n cluster_rows = cluster.rows,cluster_columns = cluster.rows,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n # width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = title.name,column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 90,\n row_title = \"Sources (Sender)\",row_title_gp = gpar(fontsize = font.size.title),row_title_rot = 90,\n heatmap_legend_param = list(title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, #at = colorbar.break,\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n # draw(ht1)\n return(ht1)\n}\n\n\n#' Visualization of (differential) number of interactions\n#'\n#' @param object A merged CellChat object or a single CellChat object\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param invert.source,invert.target retain the complementary set\n#' @param signaling a character vector giving the name of signaling networks in a single CellChat object\n#' @param slot.name the slot name of object. Set is to be \"netP\" if input signaling is a pathway name; Set is to be \"net\" if input signaling is a ligand-receptor pair\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name the name of the title\n#' @param x.lab.rot do rotation for the x-ticklabels\n#' @param ... Parameters passing to `barplot_internal`\n#' @importFrom methods slot\n#' @return an object of ggplot\n#' @export\nnetVisual_barplot <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\"), sources.use = NULL, targets.use = NULL, invert.source = FALSE, invert.target = FALSE,signaling = NULL, slot.name = c(\"netP\", \"net\"), color.use = NULL,\n title.name = NULL,x.lab.rot = FALSE,...){\n if (!is.null(measure)) {\n measure <- match.arg(measure)\n }\n slot.name <- match.arg(slot.name)\n if (is.list(object@net[[1]])) {\n message(\"Show differential number of interactions based on a merged object \\n\")\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n } else {\n message(\"Show number of interactions based on a single object \\n\")\n if (!is.null(signaling)) {\n net.diff <- slot(object, slot.name)$prob[,,signaling]\n if (is.null(title.name)) {\n title.name = paste0(signaling, \" signaling network\")\n }\n } else if (!is.null(measure)) {\n net.diff <- object@net[[measure]]\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Interaction strength\"\n }\n }\n }\n }\n\n net <- net.diff\n cells.level <- rownames(net.diff)\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n if (invert.source == TRUE) {\n sources.use <- setdiff(rownames(net.diff), sources.use)\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n if (invert.target == TRUE) {\n targets.use <- setdiff(rownames(net.diff), targets.use)\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n }\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(cells.level))\n }\n names(color.use) <- cells.level\n color.use <- color.use[cells.level %in% unique(df.net$target)]\n\n gg <- barplot_internal(df.net, x = \"target\", y = \"value\", fill = \"target\", color.use = color.use, title.name = title.name,x.lab.rot = x.lab.rot,...)\n\n return(gg)\n\n}\n\n\n#' Show all the significant interactions (L-R pairs) from some cell groups to other cell groups\n#'\n#' The dot color and size represent the calculated communication probability and p-values.\n#'\n#' @param object CellChat object\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest and the order of L-R on y-axis\n#' @param sort.by.source,sort.by.target,sort.by.source.priority set the order of interacting cell pairs on x-axis; please check examples for details\n#' @param color.heatmap A character string or vector indicating the colormap option to use. It can be the avaibale color palette in viridis_pal() or brewer.pal()\n#' @param direction Sets the order of colors in the scale. If 1, the default colors are used. If -1, the order of colors is reversed.\n#' @param n.colors number of basic colors to generate from color palette\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param comparison a numerical vector giving the datasets for comparison in the merged object; e.g., comparison = c(1,2)\n#' @param group a numerical vector giving the group information of different datasets; e.g., group = c(1,2,2)\n#' @param remove.isolate whether to remove the entire empty columns, i.e., communication between certain cell groups\n#' @param max.dataset a scale, keeping the communications with highest probability in max.dataset (i.e., certrain condition)\n#' @param min.dataset a scale, keeping the communications with lowest probability in min.dataset (i.e., certrain condition)\n#' @param min.quantile,max.quantile minimum and maximum quantile cutoff values for the colorbar, may specify quantile in [0,1]\n#' @param line.on whether to add vertical line when doing comparison analysis for the merged object\n#' @param line.size size of vertical line if added\n#' @param color.text.use whether to color the xtick labels according to the dataset origin when doing comparison analysis\n#' @param color.text the colors for xtick labels according to the dataset origin when doing comparison analysis\n#' @param dot.size.min,dot.size.max Size of smallest and largest points\n#' @param title.name main title of the plot\n#' @param font.size,font.size.title font size of all the text and the title name\n#' @param show.legend whether to show legend\n#' @param grid.on,color.grid whether to add grid\n#' @param angle.x,vjust.x,hjust.x parameters for adjusting the rotation of xtick labels\n#' @param return.data whether to return the data.frame for replotting\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # show all the significant interactions (L-R pairs) from some cell groups (defined by 'sources.use') to other cell groups (defined by 'targets.use')\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), remove.isolate = FALSE)\n#'\n#' # show all the significant interactions (L-R pairs) associated with certain signaling pathways\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), signaling = c(\"CCL\",\"CXCL\"))\n#'\n#' # show all the significant interactions (L-R pairs) based on user's input (defined by `pairLR.use`; the order of L-R is also based on user's input)\n#' pairLR.use <- extractEnrichedLR(cellchat, signaling = c(\"CCL\",\"CXCL\",\"FGF\"))\n#' netVisual_bubble(cellchat, sources.use = c(3,4), targets.use = c(5:8), pairLR.use = pairLR.use, remove.isolate = TRUE)\n#'\n#' # set the order of interacting cell pairs on x-axis\n#' # (1) Default: first sort cell pairs based on the appearance of sources in levels(object@idents), and then based on the appearance of targets in levels(object@idents)\n#' # (2) sort cell pairs based on the targets.use defined by users\n#' netVisual_bubble(cellchat, targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.target = T)\n#' # (3) sort cell pairs based on the sources.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T)\n#' # (4) sort cell pairs based on the sources.use and then targets.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T, sort.by.target = T)\n#' # (5) sort cell pairs based on the targets.use and then sources.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T, sort.by.target = T, sort.by.source.priority = FALSE)\n#'\n#'# show all the increased interactions in the second dataset compared to the first dataset\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:8), remove.isolate = TRUE, max.dataset = 2)\n#'\n#'# show all the decreased interactions in the second dataset compared to the first dataset\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:8), remove.isolate = TRUE, max.dataset = 1)\n#'}\nnetVisual_bubble <- function(object, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR.use = NULL, sort.by.source = FALSE, sort.by.target = FALSE, sort.by.source.priority = TRUE, color.heatmap = c(\"Spectral\",\"viridis\"), n.colors = 10, direction = -1, thresh = 0.05,\n comparison = NULL, group = NULL, remove.isolate = FALSE, max.dataset = NULL, min.dataset = NULL,\n min.quantile = 0, max.quantile = 1, line.on = TRUE, line.size = 0.2, color.text.use = TRUE, color.text = NULL, dot.size.min = NULL, dot.size.max = NULL,\n title.name = NULL, font.size = 10, font.size.title = 10, show.legend = TRUE,\n grid.on = TRUE, color.grid = \"grey90\", angle.x = 90, vjust.x = NULL, hjust.x = NULL,\n return.data = FALSE){\n color.heatmap <- match.arg(color.heatmap)\n if (is.list(object@net[[1]])) {\n message(\"Comparing communications on a merged object \\n\")\n } else {\n message(\"Comparing communications on a single object \\n\")\n }\n if (is.null(vjust.x) | is.null(hjust.x)) {\n angle=c(0, 45, 90)\n hjust=c(0, 1, 1)\n vjust=c(0, 1, 0.5)\n vjust.x = vjust[angle == angle.x]\n hjust.x = hjust[angle == angle.x]\n }\n if (length(color.heatmap) == 1) {\n color.use <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n scales::viridis_pal(option = color.heatmap, direction = -1)(n.colors)\n })\n } else {\n color.use <- color.heatmap\n }\n if (direction == -1) {\n color.use <- rev(color.use)\n }\n\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n pairLR.use$pathway_name <- as.character(pairLR.use$pathway_name)\n } else if (\"interaction_name\" %in% colnames(pairLR.use)) {\n pairLR.use$interaction_name <- as.character(pairLR.use$interaction_name)\n }\n }\n\n if (is.null(comparison)) {\n cells.level <- levels(object@idents)\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.net$source.target <- paste(df.net$source, df.net$target, sep = \" -> \")\n source.target <- paste(rep(sources.use, each = length(targets.use)), targets.use, sep = \" -> \")\n source.target.isolate <- setdiff(source.target, unique(df.net$source.target))\n if (length(source.target.isolate) > 0) {\n df.net.isolate <- as.data.frame(matrix(NA, nrow = length(source.target.isolate), ncol = ncol(df.net)))\n colnames(df.net.isolate) <- colnames(df.net)\n df.net.isolate$source.target <- source.target.isolate\n df.net.isolate$interaction_name_2 <- df.net$interaction_name_2[1]\n df.net.isolate$pval <- 1\n a <- stringr::str_split(df.net.isolate$source.target, \" -> \", simplify = T)\n df.net.isolate$source <- as.character(a[, 1])\n df.net.isolate$target <- as.character(a[, 2])\n df.net <- rbind(df.net, df.net.isolate)\n }\n\n df.net$pval[df.net$pval > 0.05] = 1\n df.net$pval[df.net$pval > 0.01 & df.net$pval <= 0.05] = 2\n df.net$pval[df.net$pval <= 0.01] = 3\n df.net$prob[df.net$prob == 0] <- NA\n df.net$prob.original <- df.net$prob\n df.net$prob <- -1/log(df.net$prob)\n\n idx1 <- which(is.infinite(df.net$prob) | df.net$prob < 0)\n if (sum(idx1) > 0) {\n values.assign <- seq(max(df.net$prob, na.rm = T)*1.1, max(df.net$prob, na.rm = T)*1.5, length.out = length(idx1))\n position <- sort(prob.original[idx1], index.return = TRUE)$ix\n df.net$prob[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n # rownames(df.net) <- df.net$interaction_name_2\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n group.names <- paste(rep(levels(df.net$source), each = length(levels(df.net$target))), levels(df.net$target), sep = \" -> \")\n\n df.net$interaction_name_2 <- as.character(df.net$interaction_name_2)\n df.net <- with(df.net, df.net[order(interaction_name_2),])\n df.net$interaction_name_2 <- factor(df.net$interaction_name_2, levels = unique(df.net$interaction_name_2))\n cells.order <- group.names\n df.net$source.target <- factor(df.net$source.target, levels = cells.order)\n df <- df.net\n } else {\n dataset.name <- names(object@net)\n df.net.all <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.all <- data.frame()\n for (ii in 1:length(comparison)) {\n cells.level <- levels(object@idents[[comparison[ii]]])\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n\n df.net <- df.net.all[[comparison[ii]]]\n df.net$interaction_name_2 <- as.character(df.net$interaction_name_2)\n df.net$source.target <- paste(df.net$source, df.net$target, sep = \" -> \")\n source.target <- paste(rep(sources.use, each = length(targets.use)), targets.use, sep = \" -> \")\n source.target.isolate <- setdiff(source.target, unique(df.net$source.target))\n if (length(source.target.isolate) > 0) {\n df.net.isolate <- as.data.frame(matrix(NA, nrow = length(source.target.isolate), ncol = ncol(df.net)))\n colnames(df.net.isolate) <- colnames(df.net)\n df.net.isolate$source.target <- source.target.isolate\n df.net.isolate$interaction_name_2 <- df.net$interaction_name_2[1]\n df.net.isolate$pval <- 1\n a <- stringr::str_split(df.net.isolate$source.target, \" -> \", simplify = T)\n df.net.isolate$source <- as.character(a[, 1])\n df.net.isolate$target <- as.character(a[, 2])\n df.net <- rbind(df.net, df.net.isolate)\n }\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n group.names <- paste(rep(levels(df.net$source), each = length(levels(df.net$target))), levels(df.net$target), sep = \" -> \")\n group.names0 <- group.names\n group.names <- paste0(group.names0, \" (\", dataset.name[comparison[ii]], \")\")\n\n if (nrow(df.net) > 0) {\n df.net$pval[df.net$pval > 0.05] = 1\n df.net$pval[df.net$pval > 0.01 & df.net$pval <= 0.05] = 2\n df.net$pval[df.net$pval <= 0.01] = 3\n df.net$prob[df.net$prob == 0] <- NA\n df.net$prob.original <- df.net$prob\n df.net$prob <- -1/log(df.net$prob)\n } else {\n df.net <- as.data.frame(matrix(NA, nrow = length(group.names), ncol = 5))\n colnames(df.net) <- c(\"interaction_name_2\",\"source.target\",\"prob\",\"pval\",\"prob.original\")\n df.net$source.target <- group.names0\n }\n # df.net$group.names <- sub(paste0(' \\\\(',dataset.name[comparison[ii]],'\\\\)'),'',as.character(df.net$source.target))\n df.net$group.names <- as.character(df.net$source.target)\n df.net$source.target <- paste0(df.net$source.target, \" (\", dataset.name[comparison[ii]], \")\")\n df.net$dataset <- dataset.name[comparison[ii]]\n df.all <- rbind(df.all, df.net)\n }\n if (nrow(df.all) == 0) {\n stop(\"No interactions are detected. Please consider changing the cell groups for analysis. \")\n }\n\n idx1 <- which(is.infinite(df.all$prob) | df.all$prob < 0)\n if (sum(idx1) > 0) {\n values.assign <- seq(max(df.all$prob, na.rm = T)*1.1, max(df.all$prob, na.rm = T)*1.5, length.out = length(idx1))\n position <- sort(df.all$prob.original[idx1], index.return = TRUE)$ix\n df.all$prob[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n\n df.all$interaction_name_2[is.na(df.all$interaction_name_2)] <- df.all$interaction_name_2[!is.na(df.all$interaction_name_2)][1]\n\n df <- df.all\n df <- with(df, df[order(interaction_name_2),])\n df$interaction_name_2 <- factor(df$interaction_name_2, levels = unique(df$interaction_name_2))\n\n cells.order <- c()\n dataset.name.order <- c()\n for (i in 1:length(group.names0)) {\n for (j in 1:length(comparison)) {\n cells.order <- c(cells.order, paste0(group.names0[i], \" (\", dataset.name[comparison[j]], \")\"))\n dataset.name.order <- c(dataset.name.order, dataset.name[comparison[j]])\n }\n }\n df$source.target <- factor(df$source.target, levels = cells.order)\n }\n\n min.cutoff <- quantile(df$prob, min.quantile,na.rm= T)\n max.cutoff <- quantile(df$prob, max.quantile,na.rm= T)\n df$prob[df$prob < min.cutoff] <- min.cutoff\n df$prob[df$prob > max.cutoff] <- max.cutoff\n\n\n if (remove.isolate) {\n df <- df[!is.na(df$prob), ]\n line.on <- FALSE\n }\n if (!is.null(max.dataset)) {\n # line.on <- FALSE\n # df <- df[!is.na(df$prob),]\n signaling <- as.character(unique(df$interaction_name_2))\n for (i in signaling) {\n df.i <- df[df$interaction_name_2 == i, ,drop = FALSE]\n cell <- as.character(unique(df.i$group.names))\n for (j in cell) {\n df.i.j <- df.i[df.i$group.names == j, , drop = FALSE]\n values <- df.i.j$prob\n idx.max <- which(values == max(values, na.rm = T))\n idx.min <- which(values == min(values, na.rm = T))\n #idx.na <- c(which(is.na(values)), which(!(dataset.name[comparison] %in% df.i.j$dataset)))\n dataset.na <- c(df.i.j$dataset[is.na(values)], setdiff(dataset.name[comparison], df.i.j$dataset))\n if (length(idx.max) > 0) {\n if (all(!(df.i.j$dataset[idx.max] %in% dataset.name[max.dataset]))) {\n df.i.j$prob <- NA\n } else if (all((idx.max != idx.min) & !is.null(min.dataset))) {\n if (all(!(df.i.j$dataset[idx.min] %in% dataset.name[min.dataset]))) {\n df.i.j$prob <- NA\n } else if (length(dataset.na) > 0 & sum(!(dataset.name[min.dataset] %in% dataset.na)) > 0) {\n df.i.j$prob <- NA\n }\n }\n }\n df.i[df.i$group.names == j, \"prob\"] <- df.i.j$prob\n }\n df[df$interaction_name_2 == i, \"prob\"] <- df.i$prob\n }\n #df <- df[!is.na(df$prob), ]\n }\n if (remove.isolate) {\n df <- df[!is.na(df$prob), ]\n line.on <- FALSE\n }\n if (nrow(df) == 0) {\n stop(\"No interactions are detected. Please consider changing the cell groups for analysis. \")\n }\n # Re-order y-axis\n if (!is.null(pairLR.use)) {\n interaction_name_2.order <- intersect(object@DB$interaction[pairLR.use$interaction_name, ]$interaction_name_2, unique(df$interaction_name_2))\n df$interaction_name_2 <- factor(df$interaction_name_2, levels = interaction_name_2.order)\n }\n\n # Re-order x-axis\n df$source.target = droplevels(df$source.target, exclude = setdiff(levels(df$source.target),unique(df$source.target)))\n if (sort.by.target & !sort.by.source) {\n if (!is.null(targets.use)) {\n df$target <- factor(df$target, levels = intersect(targets.use, df$target))\n df <- with(df, df[order(target, source),])\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n if (sort.by.source & !sort.by.target) {\n if (!is.null(sources.use)) {\n df$source <- factor(df$source, levels = intersect(sources.use, df$source))\n df <- with(df, df[order(source, target),])\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n if (sort.by.source & sort.by.target) {\n if (!is.null(sources.use)) {\n df$source <- factor(df$source, levels = intersect(sources.use, df$source))\n if (!is.null(targets.use)) {\n df$target <- factor(df$target, levels = intersect(targets.use, df$target))\n }\n if (sort.by.source.priority) {\n df <- with(df, df[order(source, target),])\n } else {\n df <- with(df, df[order(target, source),])\n }\n\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n\n g <- ggplot(df, aes(x = source.target, y = interaction_name_2, color = prob, size = pval)) +\n geom_point(pch = 16) +\n theme_linedraw() + theme(panel.grid.major = element_blank()) +\n theme(axis.text.x = element_text(angle = angle.x, hjust= hjust.x, vjust = vjust.x),\n axis.title.x = element_blank(),\n axis.title.y = element_blank()) +\n scale_x_discrete(position = \"bottom\")\n\n values <- c(1,2,3); names(values) <- c(\"p > 0.05\", \"0.01 < p < 0.05\",\"p < 0.01\")\n if (is.null(dot.size.max)) {\n dot.size.max = max(df$pval)\n }\n if (is.null(dot.size.min)) {\n dot.size.min = min(df$pval)\n }\n g <- g + scale_radius(range = c(dot.size.min, dot.size.max), breaks = sort(unique(df$pval)),labels = names(values)[values %in% sort(unique(df$pval))], name = \"p-value\")\n #g <- g + scale_radius(range = c(1,3), breaks = values,labels = names(values), name = \"p-value\")\n if (min(df$prob, na.rm = T) != max(df$prob, na.rm = T)) {\n g <- g + scale_colour_gradientn(colors = colorRampPalette(color.use)(99), na.value = \"white\", limits=c(quantile(df$prob, 0,na.rm= T), quantile(df$prob, 1,na.rm= T)),\n breaks = c(quantile(df$prob, 0,na.rm= T), quantile(df$prob, 1,na.rm= T)), labels = c(\"min\",\"max\")) +\n guides(color = guide_colourbar(barwidth = 0.5, title = \"Commun. Prob.\"))\n } else {\n g <- g + scale_colour_gradientn(colors = colorRampPalette(color.use)(99), na.value = \"white\") +\n guides(color = guide_colourbar(barwidth = 0.5, title = \"Commun. Prob.\"))\n }\n\n g <- g + theme(text = element_text(size = font.size),plot.title = element_text(size=font.size.title)) +\n theme(legend.title = element_text(size = 8), legend.text = element_text(size = 6))\n\n if (grid.on) {\n if (length(unique(df$source.target)) > 1) {\n g <- g + geom_vline(xintercept=seq(1.5, length(unique(df$source.target))-0.5, 1),lwd=0.1,colour=color.grid)\n }\n if (length(unique(df$interaction_name_2)) > 1) {\n g <- g + geom_hline(yintercept=seq(1.5, length(unique(df$interaction_name_2))-0.5, 1),lwd=0.1,colour=color.grid)\n }\n }\n if (!is.null(title.name)) {\n g <- g + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5))\n }\n\n if (!is.null(comparison)) {\n if (line.on) {\n xintercept = seq(0.5+length(dataset.name[comparison]), length(group.names0)*length(dataset.name[comparison]), by = length(dataset.name[comparison]))\n g <- g + geom_vline(xintercept = xintercept, linetype=\"dashed\", color = \"grey60\", size = line.size)\n }\n if (color.text.use) {\n if (is.null(group)) {\n group <- 1:length(comparison)\n names(group) <- dataset.name[comparison]\n }\n if (is.null(color.text)) {\n color <- ggPalette(length(unique(group)))\n } else {\n color <- color.text\n }\n names(color) <- names(group[!duplicated(group)])\n color <- color[group]\n #names(color) <- dataset.name[comparison]\n dataset.name.order <- levels(df$source.target)\n dataset.name.order <- stringr::str_match(dataset.name.order, \"\\\\(.*\\\\)\")\n dataset.name.order <- stringr::str_sub(dataset.name.order, 2, stringr::str_length(dataset.name.order)-1)\n xtick.color <- color[dataset.name.order]\n g <- g + theme(axis.text.x = element_text(colour = xtick.color))\n }\n }\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (return.data) {\n return(list(communication = df, gg.obj = g))\n } else {\n return(g)\n }\n\n}\n\n\n\n\n#' Chord diagram for visualizing cell-cell communication for a signaling pathway\n#'\n#' Names of cell states will be displayed in this chord diagram\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the name of signaling networks\n#' @param net a weighted matrix or a data frame with three columns defining the cell-cell communication network\n#' @param slot.name the slot name of object: slot.name = \"net\" when visualizing cell-cell communication network per each ligand-receptor pair associated with a given signaling pathway;\n#' slot.name = \"netP\" when visualizing cell-cell communication network at the level of signaling pathways\n#' @param color.use colors for the cell groups\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param remove.isolate whether remove sectors without any links\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the figures\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param ... other parameters passing to chordDiagram\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_cell <- function(object, signaling = NULL, net = NULL, slot.name = \"netP\",\n color.use = NULL,group = NULL,cell.order = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n remove.isolate = FALSE, link.visible = TRUE, scale = FALSE, directional = 1,link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20, nCol = NULL,\n thresh = 0.05,...){\n\n if (!is.null(signaling)) {\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n }\n\n if (slot.name == \"netP\") {\n message(\"Plot the aggregated cell-cell communication network at the signaling pathway level\")\n net <- apply(prob, c(1,2), sum)\n if (is.null(title.name)) {\n title.name <- paste0(signaling, \" signaling pathway network\")\n }\n # par(mfrow = c(1,1), xpd=TRUE)\n # par(mar = c(5, 4, 4, 2))\n gg <- netVisual_chord_cell_internal(net, color.use = color.use, group = group, cell.order = cell.order, sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap, big.gap = big.gap,annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y, ...)\n } else if (slot.name == \"net\") {\n message(\"Plot the cell-cell communication network per each ligand-receptor pair associated with a given signaling pathway\")\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n # layout(matrix(1:length(pairLR.name.use), ncol = nCol))\n # par(xpd=TRUE)\n # par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE, mar = c(5, 4, 4, 2) +0.1)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n #par(mar = c(5, 4, 4, 2))\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n gg[[i]] <- netVisual_chord_cell_internal(net, color.use = color.use, group = group,cell.order = cell.order,sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap,big.gap = big.gap, annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y, ...)\n }\n }\n\n } else if (!is.null(net)) {\n gg <- netVisual_chord_cell_internal(net, color.use = color.use, group = group,cell.order = cell.order,sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap, big.gap = big.gap,annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y, ...)\n } else {\n stop(\"Please assign values to either `signaling` or `net`\")\n }\n\n return(gg)\n}\n\n\n#' Chord diagram for visualizing cell-cell communication from a weighted adjacency matrix or a data frame\n#'\n#' Names of cell states/groups will be displayed in this chord diagram\n#'\n#' @param net a weighted matrix or a data frame with three columns defining the cell-cell communication network\n#' @param color.use colors for the cell groups\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param remove.isolate whether remove sectors without any links\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name of the plot\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param ... other parameters passing to chordDiagram\n#' @importFrom circlize circos.clear chordDiagram circos.track circos.text get.cell.meta.data\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_cell_internal <- function(net, color.use = NULL, group = NULL, cell.order = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n remove.isolate = FALSE, link.visible = TRUE, scale = FALSE, directional = 1, link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20,...){\n if (inherits(x = net, what = c(\"matrix\", \"Matrix\"))) {\n cell.levels <- union(rownames(net), colnames(net))\n net <- reshape2::melt(net, value.name = \"prob\")\n colnames(net)[1:2] <- c(\"source\",\"target\")\n } else if (is.data.frame(net)) {\n if (all(c(\"source\",\"target\", \"prob\") %in% colnames(net)) == FALSE) {\n stop(\"The input data frame must contain three columns named as source, target, prob\")\n }\n cell.levels <- as.character(union(net$source,net$target))\n }\n if (!is.null(cell.order)) {\n cell.levels <- cell.order\n }\n net$source <- as.character(net$source)\n net$target <- as.character(net$target)\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cell.levels[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cell.levels[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n }\n # remove the interactions with zero values\n net <- subset(net, prob > 0)\n if(dim(net)[1]<=0){message(\"No interaction between those cells\")}\n # create a fake data if keeping the cell types (i.e., sectors) without any interactions\n if (!remove.isolate) {\n cells.removed <- setdiff(cell.levels, as.character(union(net$source,net$target)))\n if (length(cells.removed) > 0) {\n net.fake <- data.frame(cells.removed, cells.removed, 1e-10*sample(length(cells.removed), length(cells.removed)))\n colnames(net.fake) <- colnames(net)\n net <- rbind(net, net.fake)\n link.visible <- net[, 1:2]\n link.visible$plot <- FALSE\n if(nrow(net) > nrow(net.fake)){\n link.visible$plot[1:(nrow(net) - nrow(net.fake))] <- TRUE\n }\n # directional <- net[, 1:2]\n # directional$plot <- 0\n # directional$plot[1:(nrow(net) - nrow(net.fake))] <- 1\n # link.arr.type = \"big.arrow\"\n # message(\"Set scale = TRUE when remove.isolate = FALSE\")\n scale = TRUE\n }\n }\n\n df <- net\n cells.use <- union(df$source,df$target)\n\n # define grid order\n order.sector <- cell.levels[cell.levels %in% cells.use]\n\n # define grid color\n if (is.null(color.use)){\n color.use = scPalette(length(cell.levels))\n names(color.use) <- cell.levels\n } else if (is.null(names(color.use))) {\n names(color.use) <- cell.levels\n }\n grid.col <- color.use[order.sector]\n names(grid.col) <- order.sector\n\n # set grouping information\n if (!is.null(group)) {\n group <- group[names(group) %in% order.sector]\n }\n\n # define edge color\n edge.color <- color.use[as.character(df$source)]\n\n if (directional == 0 | directional == 2) {\n link.arr.type = \"triangle\"\n } else {\n link.arr.type = \"big.arrow\"\n }\n\n circos.clear()\n chordDiagram(df,\n order = order.sector,\n col = edge.color,\n grid.col = grid.col,\n transparency = transparency,\n link.border = link.border,\n directional = directional,\n direction.type = c(\"diffHeight\",\"arrows\"),\n link.arr.type = link.arr.type, # link.border = \"white\",\n annotationTrack = \"grid\",\n annotationTrackHeight = annotationTrackHeight,\n preAllocateTracks = list(track.height = max(strwidth(order.sector))),\n small.gap = small.gap,\n big.gap = big.gap,\n link.visible = link.visible,\n scale = scale,\n group = group,\n link.target.prop = link.target.prop,\n reduce = reduce,\n ...)\n circos.track(track.index = 1, panel.fun = function(x, y) {\n xlim = get.cell.meta.data(\"xlim\")\n xplot = get.cell.meta.data(\"xplot\")\n ylim = get.cell.meta.data(\"ylim\")\n sector.name = get.cell.meta.data(\"sector.index\")\n circos.text(mean(xlim), ylim[1], sector.name, facing = \"clockwise\", niceFacing = TRUE, adj = c(0, 0.5),cex = lab.cex)\n }, bg.border = NA)\n\n # https://jokergoo.github.io/circlize_book/book/legends.html\n if (show.legend) {\n lgd <- ComplexHeatmap::Legend(at = names(grid.col), type = \"grid\", legend_gp = grid::gpar(fill = grid.col), title = \"Cell State\")\n ComplexHeatmap::draw(lgd, x = unit(1, \"npc\")-unit(legend.pos.x, \"mm\"), y = unit(legend.pos.y, \"mm\"), just = c(\"right\", \"bottom\"))\n }\n\n if(!is.null(title.name)){\n # title(title.name, cex = 1)\n text(-0, 1.02, title.name, cex=1)\n }\n circos.clear()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Chord diagram for visualizing cell-cell communication for a set of ligands/receptors or signaling pathways\n#'\n#' Names of ligands/receptors or signaling pathways will be displayed in this chord diagram\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object: slot.name = \"net\" when visualizing links at the level of ligands/receptors; slot.name = \"netP\" when visualizing links at the level of signaling pathways\n#' @param signaling a character vector giving the name of signaling networks\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param net A data frame consisting of the interactions of interest.\n#' net should have at least three columns: \"source\",\"target\" and \"interaction_name\" when visualizing links at the level of ligands/receptors;\n#' \"source\",\"target\" and \"pathway_name\" when visualizing links at the level of signaling pathway; \"interaction_name\" and \"pathway_name\" must be the matched names in CellChatDB$interaction.\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param color.use colors for the cell groups\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name of the plot\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param ... other parameters to chordDiagram\n#' @importFrom circlize circos.clear chordDiagram circos.track circos.text get.cell.meta.data\n#' @importFrom dplyr select %>% group_by summarize\n#' @importFrom grDevices recordPlot\n#' @importFrom stringr str_split\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_gene <- function(object, slot.name = \"net\", color.use = NULL,\n signaling = NULL, pairLR.use = NULL, net = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n link.visible = TRUE, scale = FALSE, directional = 1, link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, legend.pos.x = 20, legend.pos.y = 20, show.legend = TRUE,\n thresh = 0.05,\n ...){\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use) | sum(c(\"interaction_name\",\"pathway_name\") %in% colnames(pairLR.use) == 0)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n message(\"slot.name is set to be 'netP' when pairLR.use contains signaling pathways\")\n slot.name = \"netP\"\n }\n }\n\n if (!is.null(pairLR.use) & !is.null(signaling)) {\n stop(\"Please do not assign values to 'signaling' when using 'pairLR.use'\")\n }\n\n if (is.null(net)) {\n prob <- slot(object, \"net\")$prob\n pval <- slot(object, \"net\")$pval\n prob[pval > thresh] <- 0\n net <- reshape2::melt(prob, value.name = \"prob\")\n colnames(net)[1:3] <- c(\"source\",\"target\",\"interaction_name\")\n cols.default <- c(\"interaction_name_2\", \"pathway_name\", \"ligand\", \"receptor\" ,\"annotation\",\"evidence\")\n cols.common <- intersect(cols.default,colnames(object@LR$LRsig))\n pairLR = dplyr::select(object@LR$LRsig, cols.common)\n idx <- match(net$interaction_name, rownames(pairLR))\n temp <- pairLR[idx,]\n net <- cbind(net, temp)\n }\n\n if (!is.null(signaling)) {\n pairLR.use <- data.frame()\n for (i in 1:length(signaling)) {\n pairLR.use.i <- searchPair(signaling = signaling[i], pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.use <- rbind(pairLR.use, pairLR.use.i)\n }\n }\n\n if (!is.null(pairLR.use)){\n if (\"interaction_name\" %in% colnames(pairLR.use)) {\n net <- subset(net,interaction_name %in% pairLR.use$interaction_name)\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n net <- subset(net, pathway_name %in% as.character(pairLR.use$pathway_name))\n }\n }\n\n if (slot.name == \"netP\") {\n net <- dplyr::select(net, c(\"source\",\"target\",\"pathway_name\",\"prob\"))\n net$source_target <- paste(net$source, net$target, sep = \"sourceTotarget\")\n net <- net %>% dplyr::group_by(source_target, pathway_name) %>% dplyr::summarize(prob = sum(prob))\n a <- stringr::str_split(net$source_target, \"sourceTotarget\", simplify = T)\n net$source <- as.character(a[, 1])\n net$target <- as.character(a[, 2])\n net$ligand <- net$pathway_name\n net$receptor <- \" \"\n }\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- levels(object@idents)[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n } else {\n sources.use <- levels(object@idents)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- levels(object@idents)[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n } else {\n targets.use <- levels(object@idents)\n }\n # remove the interactions with zero values\n df <- subset(net, prob > 0)\n\n if (nrow(df) == 0) {\n stop(\"No signaling links are inferred! \")\n }\n\n if (length(unique(net$ligand)) == 1) {\n message(\"You may try the function `netVisual_chord_cell` for visualizing individual signaling pathway\")\n }\n\n df$id <- 1:nrow(df)\n # deal with duplicated sector names\n ligand.uni <- unique(df$ligand)\n for (i in 1:length(ligand.uni)) {\n df.i <- df[df$ligand == ligand.uni[i], ]\n source.uni <- unique(df.i$source)\n for (j in 1:length(source.uni)) {\n df.i.j <- df.i[df.i$source == source.uni[j], ]\n df.i.j$ligand <- paste0(df.i.j$ligand, paste(rep(' ',j-1),collapse = ''))\n df$ligand[df$id %in% df.i.j$id] <- df.i.j$ligand\n }\n }\n receptor.uni <- unique(df$receptor)\n for (i in 1:length(receptor.uni)) {\n df.i <- df[df$receptor == receptor.uni[i], ]\n target.uni <- unique(df.i$target)\n for (j in 1:length(target.uni)) {\n df.i.j <- df.i[df.i$target == target.uni[j], ]\n df.i.j$receptor <- paste0(df.i.j$receptor, paste(rep(' ',j-1),collapse = ''))\n df$receptor[df$id %in% df.i.j$id] <- df.i.j$receptor\n }\n }\n\n cell.order.sources <- levels(object@idents)[levels(object@idents) %in% sources.use]\n cell.order.targets <- levels(object@idents)[levels(object@idents) %in% targets.use]\n\n df$source <- factor(df$source, levels = cell.order.sources)\n df$target <- factor(df$target, levels = cell.order.targets)\n # df.ordered.source <- df[with(df, order(source, target, -prob)), ]\n # df.ordered.target <- df[with(df, order(target, source, -prob)), ]\n df.ordered.source <- df[with(df, order(source, -prob)), ]\n df.ordered.target <- df[with(df, order(target, -prob)), ]\n\n order.source <- unique(df.ordered.source[ ,c('ligand','source')])\n order.target <- unique(df.ordered.target[ ,c('receptor','target')])\n\n # define sector order\n order.sector <- c(order.source$ligand, order.target$receptor)\n\n # define cell type color\n if (is.null(color.use)){\n color.use = scPalette(nlevels(object@idents))\n names(color.use) <- levels(object@idents)\n color.use <- color.use[levels(object@idents) %in% as.character(union(df$source,df$target))]\n } else if (is.null(names(color.use))) {\n names(color.use) <- levels(object@idents)\n color.use <- color.use[levels(object@idents) %in% as.character(union(df$source,df$target))]\n }\n\n # define edge color\n edge.color <- color.use[as.character(df.ordered.source$source)]\n names(edge.color) <- as.character(df.ordered.source$source)\n\n # define grid colors\n grid.col.ligand <- color.use[as.character(order.source$source)]\n names(grid.col.ligand) <- as.character(order.source$source)\n grid.col.receptor <- color.use[as.character(order.target$target)]\n names(grid.col.receptor) <- as.character(order.target$target)\n grid.col <- c(as.character(grid.col.ligand), as.character(grid.col.receptor))\n names(grid.col) <- order.sector\n\n df.plot <- df.ordered.source[ ,c('ligand','receptor','prob')]\n\n if (directional == 2) {\n link.arr.type = \"triangle\"\n } else {\n link.arr.type = \"big.arrow\"\n }\n circos.clear()\n chordDiagram(df.plot,\n order = order.sector,\n col = edge.color,\n grid.col = grid.col,\n transparency = transparency,\n link.border = link.border,\n directional = directional,\n direction.type = c(\"diffHeight\",\"arrows\"),\n link.arr.type = link.arr.type,\n annotationTrack = \"grid\",\n annotationTrackHeight = annotationTrackHeight,\n preAllocateTracks = list(track.height = max(strwidth(order.sector))),\n small.gap = small.gap,\n big.gap = big.gap,\n link.visible = link.visible,\n scale = scale,\n link.target.prop = link.target.prop,\n reduce = reduce,\n ...)\n\n circos.track(track.index = 1, panel.fun = function(x, y) {\n xlim = get.cell.meta.data(\"xlim\")\n xplot = get.cell.meta.data(\"xplot\")\n ylim = get.cell.meta.data(\"ylim\")\n sector.name = get.cell.meta.data(\"sector.index\")\n circos.text(mean(xlim), ylim[1], sector.name, facing = \"clockwise\", niceFacing = TRUE, adj = c(0, 0.5),cex = lab.cex)\n }, bg.border = NA)\n\n # https://jokergoo.github.io/circlize_book/book/legends.html\n if (show.legend) {\n lgd <- ComplexHeatmap::Legend(at = names(color.use), type = \"grid\", legend_gp = grid::gpar(fill = color.use), title = \"Cell State\")\n ComplexHeatmap::draw(lgd, x = unit(1, \"npc\")-unit(legend.pos.x, \"mm\"), y = unit(legend.pos.y, \"mm\"), just = c(\"right\", \"bottom\"))\n }\n\n circos.clear()\n if(!is.null(title.name)){\n text(-0, 1.02, title.name, cex=1)\n }\n gg <- recordPlot()\n return(gg)\n}\n\n\n\n\n#' River plot showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways\n#'\n#' River (alluvial) plot shows the correspondence between the inferred latent patterns and cell groups as well as ligand-receptor pairs or signaling pathways.\n#'\n#' The thickness of the flow indicates the contribution of the cell group or signaling pathway to each latent pattern. The height of each pattern is proportional to the number of its associated cell groups or signaling pathways.\n#'\n#' Outgoing patterns reveal how the sender cells coordinate with each other as well as how they coordinate with certain signaling pathways to drive communication.\n#'\n#' Incoming patterns show how the target cells coordinate with each other as well as how they coordinate with certain signaling pathways to respond to incoming signaling.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object: “netP” or “net”. Use “netP” to analyze cell-cell communication at the level of signaling pathways, and “net” to analyze cell-cell communication at the level of ligand-receptor pairs.\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param cutoff the threshold for filtering out weak links\n#' @param sources.use a vector giving the index or the name of source cell groups of interest\n#' @param targets.use a vector giving the index or the name of target cell groups of interest\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.use.pattern the character vector defining the color of each pattern\n#' @param color.use.signaling the character vector defining the color of each signaling\n#' @param do.order whether reorder the cell groups or signaling according to their similarity\n#' @param main.title the title of plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom methods slot\n#' @importFrom stats cutree dist hclust\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @import ggalluvial\n# #' @importFrom ggalluvial geom_stratum geom_flow to_lodes_form\n#' @importFrom ggplot2 geom_text scale_x_discrete scale_fill_manual theme ggtitle\n#' @importFrom cowplot plot_grid ggdraw draw_label\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_river <- ", "suffix_code": "\n\n#' Dot plots showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways\n#'\n#' Using a contribution score of each cell group to each signaling pathway computed by multiplying W by H obtained from `identifyCommunicationPatterns`, we constructed a dot plot in which the dot size is proportion to the contribution score to show association between cell group and their enriched signaling pathways.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param cutoff the threshold for filtering out weak links. Default is 1/R where R is the number of latent patterns. We set the elements in W and H to be zero if they are less than `cutoff`.\n#' @param color.use the character vector defining the color of each cell group\n#' @param pathway.show the character vector defining the signaling to show\n#' @param group.show the character vector defining the cell group to show\n#' @param shape the shape of the symbol: 21 for circle and 22 for square\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param main.title the title of plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom methods slot\n#' @import ggplot2\n#' @importFrom dplyr group_by top_n\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_dot <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = NULL, color.use = NULL,\n pathway.show = NULL, group.show = NULL,\n shape = 21, dot.size = c(1, 3), dot.alpha = 1, main.title = NULL,\n font.size = 10, font.size.title = 12){\n pattern <- match.arg(pattern)\n patternSignaling <- methods::slot(object, slot.name)$pattern[[pattern]]\n data1 = patternSignaling$pattern$cell\n data2 = patternSignaling$pattern$signaling\n data = patternSignaling$data\n if (is.null(main.title)) {\n if (pattern == \"outgoing\") {\n main.title = \"Outgoing communication patterns of secreting cells\"\n } else if (pattern == \"incoming\") {\n main.title = \"Incoming communication patterns of target cells\"\n }\n }\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(data1$CellGroup))\n }\n if (is.null(cutoff)) {\n cutoff <- 1/length(unique(data1$Pattern))\n }\n options(warn = -1)\n data1$Contribution[data1$Contribution < cutoff] <- 0\n data2$Contribution[data2$Contribution < cutoff] <- 0\n data3 = merge(data1, data2, by.x=\"Pattern\", by.y=\"Pattern\")\n data3$Contribution <- data3$Contribution.x * data3$Contribution.y\n data3 <- data3[,colnames(data3) %in% c(\"CellGroup\",\"Signaling\",\"Contribution\")]\n if (!is.null(pathway.show)) {\n data3 <- data3[data3$Signaling %in% pathway.show, ]\n pathway.add <- pathway.show[which(pathway.show %in% data3$Signaling == 0)]\n if (length(pathway.add) > 1) {\n data.add <- expand.grid(CellGroup = levels(data1$CellGroup), Signaling = pathway.add)\n data.add$Contribution <- 0\n data3 <- rbind(data3, data.add)\n }\n data3$Signaling <- factor(data3$Signaling, levels = pathway.show)\n }\n if (!is.null(group.show)) {\n data3$CellGroup <- as.character(data3$CellGroup)\n data3 <- data3[data3$CellGroup %in% group.show, ]\n data3$CellGroup <- factor(data3$CellGroup, levels = group.show)\n }\n\n data <- as.data.frame(as.table(data));\n data <- data[data[,3] != 0, ]\n data12 <- paste0(data[,1],data[,2])\n data312 <- paste0(data3[,1],data3[,2])\n idx1 <- which(match(data312, data12, nomatch = 0) ==0)\n data3$Contribution[idx1] <- 0\n data3$id <- data312\n data3 <- data3 %>% group_by(id) %>% top_n(1, Contribution)\n\n data3$Contribution[which(data3$Contribution == 0)] <- NA\n\n df <- data3\n gg <- ggplot(data = df, aes(x = Signaling, y = CellGroup)) +\n geom_point(aes(size = Contribution, fill = CellGroup, colour = CellGroup), shape = shape) +\n scale_size_continuous(range = dot.size) +\n theme_linedraw() +\n scale_x_discrete(position = \"bottom\") +\n ggtitle(main.title) +\n theme(plot.title = element_text(hjust = 0.5)) +\n theme(text = element_text(size = font.size),plot.title = element_text(size=font.size.title, face=\"plain\"),\n axis.text.x = element_text(angle = 45, hjust=1),\n axis.text.y = element_text(angle = 0, hjust=1),\n axis.title.x = element_blank(),\n axis.title.y = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25)) +\n theme(panel.grid.major = element_line(colour=\"grey90\", size = (0.1)))\n gg <- gg + scale_y_discrete(limits = rev(levels(data3$CellGroup)))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE, na.value = \"white\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, na.value = \"white\")\n gg <- gg + guides(colour=\"none\") + guides(fill=\"none\")\n gg <- gg + theme(legend.title = element_text(size = 10), legend.text = element_text(size = 8))\n gg\n return(gg)\n}\n\n\n#' 2D visualization of the learned manifold of signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param pathway.labeled a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param pathway.remove.show whether show the removed signaling names\n#' @param color.use defining the color for each cell group\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embedding <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), color.use = NULL, pathway.labeled = NULL, top.label = 1, pathway.remove = NULL, pathway.remove.show = TRUE, dot.size = c(2, 6), label.size = 2, dot.alpha = 0.5,\n xlabel = \"Dim 1\", ylabel = \"Dim 2\", title = NULL,\n font.size = 10, font.size.title = 12, do.label = T, show.legend = T, show.axes = T) {\n type <- match.arg(type)\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n Groups <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n prob <- methods::slot(object, slot.name)$prob\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n }\n\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(dimnames(prob)[[3]] %in% pathway.remove)\n prob <- prob[ , , -pathway.remove.idx]\n }\n\n prob_sum <- apply(prob, 3, sum)\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum), labels = as.character(unlist(dimnames(prob)[3])), Groups = as.factor(Groups))\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(Groups)))\n }\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.,fill = Groups, colour = Groups), shape = 21) +\n CellChat_theme_opts() +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\"))+\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE)\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n if (do.label) {\n if (is.null(pathway.labeled)) {\n if (top.label < 1) {\n if (length(comparison) == 2) {\n g.t <- rankSimilarity(object, slot.name = slot.name, type = type, comparison1 = comparison)\n pathway.labeled <- as.character(g.t$data$name[(nrow(g.t$data)-ceiling(top.label * nrow(g.t$data))+1):nrow(g.t$data) ])\n data.label <- df[df$labels %in% pathway.labeled, , drop = FALSE]\n }\n } else {\n data.label <- df\n }\n\n } else {\n data.label <- df[df$labels %in% pathway.labeled, , drop = FALSE]\n }\n gg <- gg + ggrepel::geom_text_repel(data = data.label, mapping = aes(label = labels, colour = Groups), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n\n # gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = Groups), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (length(pathway.remove) > 0 & pathway.remove.show) {\n gg <- gg + annotate(geom = 'text', label = paste(\"Isolate pathways: \", paste(pathway.remove, collapse = ', ')), x = -Inf, y = Inf, hjust = 0, vjust = 1, size = label.size,fontface=\"italic\")\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n gg\n}\n\n\n#' Zoom into the 2D visualization of the learned manifold learning of the signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param color.use defining the color for each cell group\n#' @param nCol the number of columns of the plot\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom cowplot plot_grid\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingZoomIn <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), color.use = NULL, pathway.remove = NULL, nCol = 1, dot.size = c(2, 6), label.size = 2.8, dot.alpha = 0.5,\n xlabel = NULL, ylabel = NULL, do.label = T, show.legend = F, show.axes = T) {\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n prob <- methods::slot(object, slot.name)$prob\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n }\n\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(dimnames(prob)[[3]] %in% pathway.remove)\n prob <- prob[ , , -pathway.remove.idx]\n }\n\n prob_sum <- apply(prob, 3, sum)\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum), labels = as.character(unlist(dimnames(prob)[3])), clusters = as.factor(clusters))\n\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n\n # zoom into each cluster and do labels\n ggAll <- vector(\"list\", length(unique(clusters)))\n for (i in 1:length(unique(clusters))) {\n clusterID = i\n title <- paste0(\"Group \", clusterID)\n df2 <- df[df$clusters %in% clusterID,]\n gg <- ggplot(data = df2, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.), shape = 21, colour = alpha(color.use[clusterID], alpha = 1), fill = alpha(color.use[clusterID], alpha = dot.alpha)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size=12))+\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels), colour = color.use[clusterID], size = label.size, segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n ggAll[[i]] <- gg\n }\n gg.combined <- cowplot::plot_grid(plotlist = ggAll, ncol = nCol)\n\n gg.combined\n\n}\n\n\n\n#' 2D visualization of the joint manifold learning of signaling networks from two datasets\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object\n#' @param pathway.labeled a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param pathway.remove.show whether show the removed signaling names\n#' @param color.use defining the color for each cell group\n#' @param point.shape a numeric vector giving the point shapes. By default point.shape <- c(21, 0, 24, 23, 25, 10, 12), see available shapes at http://www.sthda.com/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingPairwise <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, color.use = NULL, point.shape = NULL, pathway.labeled = NULL, top.label = 1, pathway.remove = NULL, pathway.remove.show = TRUE, dot.size = c(2, 6), label.size = 2.5, dot.alpha = 0.5,\n xlabel = \"Dim 1\", ylabel = \"Dim 2\", title = NULL,do.label = T, show.legend = T, show.axes = T) {\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"2D visualization of signaling networks from datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n object.names <- setdiff(names(methods::slot(object, slot.name)), \"similarity\")[comparison]\n prob <- list()\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n prob[[i]] = object.net$prob\n }\n\n if (is.null(point.shape)) {\n point.shape <- c(21, 0, 24, 23, 25, 10, 12)\n }\n\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove <- sub(\"--.*\", \"\", pathway.remove)\n }\n\n if (length(pathway.remove) > 0) {\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n pathway.remove.idx <- which(paste0(dimnames(probi)[[3]],\"--\",object.names[i]) %in% pathway.remove)\n # pathway.remove.idx <- which(dimnames(probi)[[3]] %in% pathway.remove)\n if (length(pathway.remove.idx) > 0) {\n probi <- probi[ , , -pathway.remove.idx]\n }\n prob[[i]] <- probi\n }\n }\n prob_sum.each <- list()\n signalingAll <- c()\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n prob_sum.each[[i]] <- apply(probi, 3, sum)\n signalingAll <- c(signalingAll, paste0(names(prob_sum.each[[i]]),\"--\",object.names[i]))\n }\n prob_sum <- unlist(prob_sum.each)\n names(prob_sum) <- signalingAll\n\n group <- sub(\".*--\", \"\", names(prob_sum))\n labels = sub(\"--.*\", \"\", names(prob_sum))\n\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum),\n labels = as.character(labels), clusters = as.factor(clusters), group = factor(group, levels = unique(group)))\n # color dots (light inside color and dark border) based on clustering and no labels\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.,fill = clusters, colour = clusters, shape = group)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) +\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) #+ scale_alpha(group, range = c(0.1, 1))\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n gg <- gg + scale_shape_manual(values = point.shape[1:length(prob)])\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = clusters, alpha=group), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n }\n\n if (length(pathway.remove) > 0 & pathway.remove.show) {\n gg <- gg + annotate(geom = 'text', label = paste(\"Isolate pathways: \", paste(pathway.remove, collapse = ', ')), x = -Inf, y = Inf, hjust = 0, vjust = 1, size = label.size,fontface=\"italic\")\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n gg\n}\n\n\n\n#' Zoom into the 2D visualization of the joint manifold learning of signaling networks from two datasets\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param color.use defining the color for each cell group\n#' @param nCol number of columns in the plot\n#' @param point.shape a numeric vector giving the point shapes. By default point.shape <- c(21, 0, 24, 23, 25, 10, 12), see available shapes at http://www.sthda.com/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingPairwiseZoomIn <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, color.use = NULL, nCol = 1, point.shape = NULL, pathway.remove = NULL, dot.size = c(2, 6), label.size = 2.8, dot.alpha = 0.5,\n xlabel = NULL, ylabel = NULL, do.label = T, show.legend = F, show.axes = T) {\n\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"2D visualization of signaling networks from datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n object.names <- setdiff(names(methods::slot(object, slot.name)), \"similarity\")[comparison]\n prob <- list()\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n prob[[i]] = object.net$prob\n }\n\n if (is.null(point.shape)) {\n point.shape <- c(21, 0, 24, 23, 25, 10, 12)\n }\n\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove <- sub(\"--.*\", \"\", pathway.remove)\n }\n\n if (length(pathway.remove) > 0) {\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n pathway.remove.idx <- which(paste0(dimnames(probi)[[3]],\"--\",object.names[i]) %in% pathway.remove)\n # pathway.remove.idx <- which(dimnames(probi)[[3]] %in% pathway.remove)\n if (length(pathway.remove.idx) > 0) {\n probi <- probi[ , , -pathway.remove.idx]\n }\n prob[[i]] <- probi\n }\n }\n\n prob_sum.each <- list()\n signalingAll <- c()\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n prob_sum.each[[i]] <- apply(probi, 3, sum)\n signalingAll <- c(signalingAll, paste0(names(prob_sum.each[[i]]),\"--\",object.names[i]))\n }\n prob_sum <- unlist(prob_sum.each)\n names(prob_sum) <- signalingAll\n\n group <- sub(\".*--\", \"\", names(prob_sum))\n labels = sub(\"--.*\", \"\", names(prob_sum))\n\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum),\n labels = as.character(labels), clusters = as.factor(clusters), group = factor(group, levels = unique(group)))\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n\n # zoom into each cluster and do labels\n ggAll <- vector(\"list\", length(unique(clusters)))\n for (i in 1:length(unique(clusters))) {\n clusterID = i\n title <- paste0(\"Cluster \", clusterID)\n df2 <- df[df$clusters %in% clusterID,]\n gg <- ggplot(data = df2, aes(x, y)) +\n geom_point(aes(size = Commun.Prob., shape = group),fill = alpha(color.use[clusterID], alpha = dot.alpha), colour = alpha(color.use[clusterID], alpha = 1)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) +\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n idx <- match(unique(df2$group), levels(df$group), nomatch = 0)\n gg <- gg + scale_shape_manual(values= point.shape[idx])\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels), colour = color.use[clusterID], size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n ggAll[[i]] <- gg\n }\n gg.combined <- cowplot::plot_grid(plotlist = ggAll, ncol = nCol)\n\n gg.combined\n\n}\n\n\n#' A Seurat wrapper function for plotting gene expression using violin plot, dot plot or bar plot\n#'\n#' This function create a Seurat object from an input CellChat object, and then plot gene expression distribution using a modified violin plot or dot plot based on Seurat's function or a bar plot.\n#' Please check \\code{\\link{StackedVlnPlot}},\\code{\\link{dotPlot}} and \\code{\\link{barPlot}}for detailed description of the arguments.\n#'\n#' USER can extract the signaling genes related to the inferred L-R pairs or signaling pathway using \\code{\\link{extractEnrichedLR}}, and then plot gene expression using Seurat package.\n#'\n#' @param object CellChat object\n#' @param features Features to plot gene expression\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param type violin plot or dot plot\n#' @param color.use defining the color for each cell group\n#' @param group.by Name of one metadata columns to group (color) cells. Default is the defined cell groups in CellChat object\n#' @param ... other arguments passing to either VlnPlot or DotPlot from Seurat package\n#' @return\n#' @export\n#'\n#' @examples\n\nplotGeneExpression <- function(object, features = NULL, signaling = NULL, enriched.only = TRUE, type = c(\"violin\", \"dot\",\"bar\"), color.use = NULL, group.by = NULL, ...) {\n type <- match.arg(type)\n meta <- object@meta\n if (is.list(object@idents)) {\n meta$group.cellchat <- object@idents$joint\n } else {\n meta$group.cellchat <- object@idents\n }\n if (!identical(rownames(meta), colnames(object@data.signaling))) {\n cat(\"The cell barcodes in 'meta' is \", head(rownames(meta)),'\\n')\n warning(\"The cell barcodes in 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of 'mata'!\")\n rownames(meta) <- colnames(object@data.signaling)\n }\n\n w10x <- Seurat::CreateSeuratObject(counts = object@data.signaling, meta.data = meta)\n if (is.null(group.by)) {\n group.by <- \"group.cellchat\"\n }\n Seurat::Idents(w10x) <- group.by\n if (!is.null(features) & !is.null(signaling)) {\n warning(\"`features` will be used when inputing both `features` and `signaling`!\")\n }\n if (!is.null(features)) {\n feature.use <- features\n } else if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, enriched.only = enriched.only)\n feature.use <- res$geneLR\n }\n if (type == \"violin\") {\n gg <- StackedVlnPlot(w10x, features = feature.use, color.use = color.use, ...)\n } else if (type == \"dot\") {\n gg <- dotPlot(w10x, features = feature.use, color.use = color.use, ...)\n } else if (type == \"bar\") {\n gg <- barPlot(w10x, features = feature.use, color.use = color.use, ...)\n }\n return(gg)\n}\n\n\n#' Dot plot\n#'\n#'The size of the dot encodes the percentage of cells within a class, while the color encodes the AverageExpression level across all cells within a class\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param rotation whether rotate the plot\n#' @param colormap RColorbrewer palette to use (check available palette using RColorBrewer::display.brewer.all()). default will use customed color palette\n#' @param color.direction Sets the order of colours in the scale. If 1, the default, colours are as output by RColorBrewer::brewer.pal(). If -1, the order of colours is reversed.\n#' @param color.use defining the color for each condition/dataset\n#' @param idents Which classes to include in the plot (default is all)\n#' @param group.by Name of one or more metadata columns to group (color) cells by\n#' (for example, orig.ident); pass 'ident' to group by identity class\n#' @param split.by Name of a metadata column to split plot by;\n#' @param legend.width legend width\n#' @param scale whther show x-axis text\n#' @param col.min Minimum scaled average expression threshold (everything smaller will be set to this)\n#' @param col.max Maximum scaled average expression threshold (everything larger will be set to this)\n#' @param dot.scale Scale the size of the points, similar to cex\n#' @param assay Name of assay to use, defaults to the active assay\n#' @param angle.x angle for x-axis text rotation\n#' @param hjust.x adjust x axis text\n#' @param angle.y angle for y-axis text rotation\n#' @param hjust.y adjust y axis text\n#' @param show.legend whether show the legend\n#' @param ... Extra parameters passed to DotPlot from Seurat package\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\ndotPlot <- function(object, features, rotation = TRUE, colormap = \"OrRd\", color.direction = 1, color.use = c(\"#F8766D\",\"#00BFC4\"), scale = TRUE, col.min = -2.5, col.max = 2.5, dot.scale = 6, assay = \"RNA\",\n idents = NULL, group.by = NULL, split.by = NULL, legend.width = 0.5,\n angle.x = 45, hjust.x = 1, angle.y = 0, hjust.y = 0.5, show.legend = TRUE, ...) {\n\n gg <- Seurat::DotPlot(object, features = features, assay = assay, cols = color.use,\n scale = scale, col.min = col.min, col.max = col.max, dot.scale = dot.scale,\n idents = idents, group.by = group.by, split.by = split.by,...)\n gg <- gg + theme(axis.title.x=element_blank(), axis.title.y=element_blank()) +\n theme(axis.text.x = element_text(size = 10), axis.text.y = element_text(size = 10), axis.line = element_line(colour = 'black')) +\n theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))+\n theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x), axis.text.y = element_text(angle = angle.y, hjust = hjust.y))\n\n gg <- gg + theme(legend.title = element_text(size = 10), legend.text = element_text(size = 8))\n if (is.null(split.by)) {\n gg <- gg + guides(color = guide_colorbar(barwidth = legend.width, title = \"Scaled expression\"),size = guide_legend(title = 'Percent expressed'))\n }\n\n if (rotation) {\n gg <- gg + coord_flip()\n }\n if (!is.null(colormap)) {\n if (is.null(split.by)) {\n gg <- gg + scale_color_distiller(palette = colormap, direction = color.direction, guide = guide_colorbar(title = \"Scaled Expression\", ticks = T, label = T, barwidth = legend.width), na.value = \"lightgrey\")\n }\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n return(gg)\n}\n\n\n\n#' Stacked Violin plot\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param color.use defining the color for each cell group\n#' @param colors.ggplot whether use ggplot color scheme; default: colors.ggplot = FALSE\n#' @param split.by Name of a metadata column to split plot by;\n#' @param idents Which classes to include in the plot (default is all)\n#' @param show.text.y whther show y-axis text\n#' @param line.size line width in the violin plot\n#' @param pt.size size of the dots\n#' @param plot.margin adjust the white space between each plot\n#' @param angle.x angle for x-axis text rotation\n#' @param vjust.x adjust x axis text\n#' @param hjust.x adjust x axis text\n#' @param ... Extra parameters passed to VlnPlot from Seurat package\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\n#' @importFrom patchwork wrap_plots\n# #' @importFrom Seurat VlnPlot\nStackedVlnPlot<- function(object, features, idents = NULL, split.by = NULL,\n color.use = NULL, colors.ggplot = FALSE,\n angle.x = 90, vjust.x = NULL, hjust.x = NULL, show.text.y = TRUE, line.size = NULL,\n pt.size = 0,\n plot.margin = margin(0, 0, 0, 0, \"cm\"),\n ...) {\n options(warn=-1)\n if (is.null(color.use)) {\n numCluster <- length(levels(Seurat::Idents(object)))\n if (colors.ggplot) {\n color.use <- NULL\n } else {\n color.use <- scPalette(numCluster)\n }\n }\n if (is.null(vjust.x) | is.null(hjust.x)) {\n angle=c(0, 45, 90)\n hjust=c(0, 1, 1)\n vjust=c(0, 1, 0.5)\n vjust.x = vjust[angle == angle.x]\n hjust.x = hjust[angle == angle.x]\n }\n\n plot_list<- purrr::map(features, function(x) modify_vlnplot(object = object, features = x, idents = idents, split.by = split.by, cols = color.use, pt.size = pt.size,\n show.text.y = show.text.y, line.size = line.size, ...))\n\n # Add back x-axis title to bottom plot. patchwork is going to support this?\n plot_list[[length(plot_list)]]<- plot_list[[length(plot_list)]] +\n theme(axis.text.x=element_text(), axis.ticks.x = element_line()) +\n theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x, vjust = vjust.x)) +\n theme(axis.text.x = element_text(size = 10))\n\n p<- patchwork::wrap_plots(plotlist = plot_list, ncol = 1)\n return(p)\n}\n\n#' modified vlnplot\n#' @param object Seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param split.by Name of a metadata column to split plot by;\n#' @param idents Which classes to include in the plot (default is all)\n#' @param cols defining the color for each cell group\n#' @param show.text.y whther show y-axis text\n#' @param line.size line width in the violin plot\n#' @param pt.size size of the dots\n#' @param plot.margin adjust the white space between each plot\n#' @param ... pass any arguments to VlnPlot in Seurat\n#' @import ggplot2\n# #' @importFrom Seurat VlnPlot\n#'\nmodify_vlnplot<- function(object,\n features,\n idents = NULL,\n split.by = NULL,\n cols = NULL,\n show.text.y = TRUE,\n line.size = NULL,\n pt.size = 0,\n plot.margin = margin(0, 0, 0, 0, \"cm\"),\n ...) {\n options(warn=-1)\n p<- Seurat::VlnPlot(object, features = features, cols = cols, pt.size = pt.size, idents = idents, split.by = split.by, ... ) +\n xlab(\"\") + ylab(features) + ggtitle(\"\")\n p <- p + theme(text = element_text(size = 10)) + theme(axis.line = element_line(size=line.size)) +\n theme(axis.text.x = element_text(size = 10), axis.text.y = element_text(size = 8), axis.line.x = element_line(colour = 'black', size=line.size),axis.line.y = element_line(colour = 'black', size= line.size))\n # theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))\n p <- p + theme(legend.position = \"none\",\n plot.title= element_blank(),\n axis.title.x = element_blank(),\n axis.text.x = element_blank(),\n axis.ticks.x = element_blank(),\n axis.title.y = element_text(size = rel(1), angle = 0),\n axis.text.y = element_text(size = rel(1)),\n plot.margin = plot.margin ) +\n theme(axis.text.y = element_text(size = 8))\n\n p <- p + scale_y_continuous(labels = function(x) {\n idx0 = which(x == 0)\n if (length(idx0) > 0) {\n if (idx0 > 1) {\n c(rep(x = \"\", times = idx0-1), \"0\",rep(x = \"\", times = length(x) -2-idx0), x[length(x) - 1], \"\")\n } else {\n c(\"0\", rep(x = \"\", times = length(x)-3), x[length(x) - 1], \"\")\n }\n } else {\n c(as.character(min(x)), rep(x = \"\", times = length(x)-3), x[length(x) - 1], \"\")\n }\n })\n # #c(rep(x = \"\", times = length(x)-2), x[length(x) - 1], \"\"))\n\n p <- p + theme(element_line(size=line.size))\n\n if (!show.text.y) {\n p <- p + theme(axis.ticks.y=element_blank(), axis.text.y=element_blank())\n }\n return(p)\n}\n\n#' extract the max value of the y axis\n#' @param p ggplot object\n#' @importFrom ggplot2 ggplot_build\nextract_max<- function(p){\n ymax<- max(ggplot_build(p)$layout$panel_scales_y[[1]]$range$range)\n return(signif(ymax,2))\n}\n\n\n#' Bar plot for average gene expression\n#'\n#' Please check \\code{\\link{barplot_internal}}for detailed description of the arguments.\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param color.use defining the color for each condition/dataset\n#' @param group.by Name of one or more metadata columns to group (color) cells by\n#' (for example, orig.ident); pass 'ident' to group by identity class\n#' @param method methods for computing the average gene expression per cell group. By default = \"truncatedMean\", where a value should be assigned to 'trim;\n#' @param trim the fraction (0 to 0.5) of observations to be trimmed from each end of x before the mean is computed.\n#' @param split.by Name of a metadata column to split plot by;\n#' @param assay Name of assay to use, defaults to the active assay\n#' @param x.lab.rot whether do rotation for the x.tick.label\n#' @param ncol number of columns to show in the plot\n#' @param ... Extra parameters passed to barplot_internal\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\nbarPlot <- function(object, features, group.by = NULL, split.by = NULL, color.use = NULL, method = c(\"truncatedMean\", \"triMean\",\"median\"),trim = 0.1, assay = \"RNA\",\n x.lab.rot = FALSE, ncol = 1, ...) {\n method <- match.arg(method)\n if (is.null(group.by)) {\n labels = Seurat::Idents(object)\n } else {\n labels = object@meta.data[,group.by]\n }\n FunMean <- switch(method,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n triMean = triMean,\n median = function(x) median(x, na.rm = TRUE))\n if (packageVersion(\"Seurat\") < \"5.0.0\") {\n data.all <- object[[assay]]@data\n } else {\n data.all <- object[[assay]]$data\n }\n if (!is.null(split.by)) {\n group = object@meta.data[,split.by]\n group.levels <- levels(group)\n df <- data.frame()\n for (i in 1:length(group.levels)) {\n data = data.all[, group == group.levels[i], drop = FALSE]\n labels.use <- labels[group == group.levels[i]]\n dataavg <- aggregate(t(data[features, ]), list(labels.use) , FUN = FunMean)\n dataavg <- t(dataavg[,-1])\n colnames(dataavg) <- levels(labels.use)\n dataavg <- as.data.frame(dataavg)\n dataavg$gene = rownames(dataavg)\n df1 = reshape2::melt(dataavg, id.vars = c(\"gene\"))\n colnames(df1) <- c(\"gene\",\"labels\",\"value\")\n df1$condition = group.levels[i]\n df = rbind(df, df1)\n }\n df$labels <- factor(df$labels, levels = levels(labels))\n df$condition <- factor(df$condition, levels = group.levels)\n\n } else {\n data = data.all\n dataavg <- aggregate(t(data[features, ]), list(labels) , FUN = FunMean)\n dataavg <- t(dataavg[,-1])\n colnames(dataavg) <- levels(labels)\n dataavg$gene = rownames(dataavg)\n df1 = reshape2::melt(dataavg, id.vars = c(\"gene\"))\n colnames(df1) <- c(\"gene\",\"labels\",\"value\")\n df1$condition = df1[,\"labels\"]\n df = df1\n }\n gg <- list()\n for (i in 1:length(features)) {\n if (i < length(features)) {\n df.use = subset(df, gene == features[i])\n gg[[i]] <- barplot_internal(df.use, x = \"labels\", y = \"value\", fill = \"condition\",color.use = color.use,ylabel = features[i],remove.xtick = TRUE,x.lab.rot = x.lab.rot,...)\n }else {\n gg[[i]] <- barplot_internal(df.use, x = \"labels\", y = \"value\", fill = \"condition\",color.use = color.use,ylabel = features[i],remove.xtick = FALSE,x.lab.rot = x.lab.rot,...)\n }\n }\n\n p<- patchwork::wrap_plots(plotlist = gg, ncol = ncol)+ patchwork::plot_layout(guides = \"collect\")\n return(p)\n\n}\n\n#' Bar plot for dataframe\n#'\n#' @param df a dataframe\n#' @param x Name of one column to show on the x-axis\n#' @param y Name of one column to show on the y-axis\n#' @param fill Name of one column to compare the values\n#' @param color.use defining the color of bar plot;\n#' @param percent.y whether showing y-values as percentage\n#' @param width bar width\n#' @param legend.title Name of legend\n#' @param xlabel Name of x label\n#' @param ylabel Name of y label\n#' @param remove.xtick whether remove x tick\n#' @param title.name Name of the main title\n#' @param stat.add whether adding statistical test\n#' @param stat.method,label.x parameters for ggpubr::stat_compare_means\n#' @param show.legend Whether show the legend\n#' @param x.lab.rot Whether rorate the xtick labels\n#' @param size.text font size\n\n#' @import ggplot2\n#' @importFrom ggpubr stat_compare_means\n#'\n#' @return ggplot2 object\n#' @export\nbarplot_internal <- function(df, x = \"cellType\", y = \"value\", fill = \"condition\", legend.title = NULL, width=0.6, title.name = NULL,\n xlabel = NULL, ylabel = NULL, color.use = NULL,remove.xtick = FALSE,\n stat.add = FALSE, stat.method = \"wilcox.test\", percent.y = FALSE, label.x = 1.5,\n show.legend = TRUE, x.lab.rot = FALSE, size.text = 10) {\n\n gg <- ggplot(df, aes_string(x=x, y=y, fill = fill, color = fill)) + geom_bar(stat=\"identity\", width=width, position=position_dodge()) +\n theme_classic() + scale_x_discrete(limits = (levels(df$x))) + theme(axis.text.x = element_text(angle = 45, hjust = 1,size=10))\n\n gg <- gg + ylab(ylabel) + xlab(xlabel) + theme_classic() +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = size.text), axis.text = element_text(colour=\"black\"))\n if (!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values = alpha(color.use, alpha = 1), drop = FALSE)\n gg <- gg + scale_color_manual(values = alpha(color.use, alpha = 1), drop = FALSE) + guides(colour = FALSE)\n }\n if (stat.add) {\n gg <- gg + ggpubr::stat_compare_means(mapping = aes_string(group = fill), method = stat.method, label.x = label.x,\n label = \"p.format\", size = 3)\n }\n # if (show.mean) {\n # gg <- gg + stat_summary(fun.y=mean, geom=\"point\", shape=20, size=10, color=\"red\", fill=\"red\")\n # }\n if (remove.xtick) {\n gg <- gg + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.title.x=element_blank())\n }\n if (percent.y) {\n gg <- gg + scale_y_continuous(labels = scales::percent_format(accuracy = 1))\n }\n if (is.null(legend.title)) {\n gg <- gg + theme(legend.title = element_blank())\n } else {\n gg <- gg + guides(fill=guide_legend(legend.title))\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n if (x.lab.rot) {\n gg <- gg + theme(axis.text.x = element_text(angle = 45, hjust = 1, size=size.text))\n }\n gg\n return(gg)\n}\n\n\n########################################\n# spatial plot #\n########################################\n#' Visualize spatial cell groups\n#'\n#' This function takes a CellChat object as input, and then plot cell groups of interest.\n#'\n#' @param object cellchat object\n#' @param color.use defining the color for each cell group\n#' @param group.by Name of one metadata columns to group (color) cells. Default is the defined cell groups in CellChat object\n#' @param sample.use the sample name used for visualization, which should be the element in `object@meta$samples`.\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups\n#' @param idents.use a vector giving the index or the name of cell groups of interest\n#' @param alpha the transparency of individual spot\n#' @param shape.by the shape of individual spot\n#' @param title.name title name\n#' @param point.size the size of spots\n#' @param legend.size the size of legend\n#' @param legend.text.size the text size on the legend\n#' @param legend.position legend position\n#' @param ncol number of columns of the legend text\n#' @param byrow arrange the legend text byrow or not\n#' @return\n#' @export\n#'\n#' @examples\nspatialDimPlot <- function(object, color.use = NULL, group.by = NULL, sample.use = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL,\n alpha = 1, shape.by = 16, title.name = NULL, point.size = 2.4,\n legend.size = 5, legend.text.size = 8, legend.position = \"right\", ncol = 1, byrow = FALSE){\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[,group.by]\n labels <- factor(labels)\n }\n cells.level <- levels(labels)\n\n coordinates <- object@images$coordinates\n samples <- object@meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n\n if (is.null(sources.use) & is.null(targets.use)){\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n } else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use, \"Others\"))\n\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use, targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n\n gg <- ggplot(data = coordinates,aes(x=x_cent,y=y_cent,colour = labels))+\n geom_point(alpha = alpha, size = point.size, shape=shape.by) +\n scale_color_manual(values = color.use, na.value = \"grey90\") + theme(legend.position = legend.position) +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size)) + # , legend.key.size = unit(0.4, \"inches\")\n guides(color = guide_legend(override.aes = list(size=legend.size), ncol = ncol, byrow = byrow)) +\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n coord_fixed() + theme(aspect.ratio = 1)+ theme(legend.key = element_blank())\n gg <- gg + scale_y_reverse()\n\n if (!is.null(title.name)){\n gg <- gg + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))\n }\n return(gg)\n\n}\n\n\n#' A spatial feature plots\n#'\n#' This function takes a CellChat object as input, and then plot gene expression distribution over spots/cells on the image.\n#'\n#' @param object cellchat object\n#' @param features a char vector containing features to visualize. `features` can be genes or column names of `object@meta`.\n#' @param signaling signalling names to visualize\n#' @param pairLR.use a data frame consisting of one column named \"interaction_name\", defining the L-R pairs of interest\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param do.group set `do.group = TRUE` when only showing enriched signaling based on cell group-level communication; set `do.group = FALSE` when only showing enriched signaling based on individual cell-level communication\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param color.heatmap A character string or vector indicating the colormap option to use. It can be the avaibale color palette in brewer.pal() or viridis_pal() (e.g., \"Spectral\",\"viridis\")\n#' @param n.colors,direction n.colors: number of basic colors to generate from color palette; direction: Sets the order of colors in the scale. If 1, the default colors are used. If -1, the order of colors is reversed.\n#' @param do.binary,cutoff whether binarizing the expression using a given cutoff\n#' @param color.use defining the color for cells/spots expressing ligand only, expressing receptor only, expressing both ligand & receptor and cells/spots without expression of given ligands and receptors\n#' @param alpha the transparency of individual spot\n#' @param point.size the size of cell slot\n#' @param shape.by the shape of individual spot\n#' @param legend.size the size of legend\n#' @param legend.text.size the text size on the legend\n#' @param ncol number of columns if plotting multiple plots\n#' @param show.legend whether show each figure legend\n#' @param show.legend.combined whether show the figure legend for the last plot\n#' @return\n#' @export\n#'\n#' @examples\n\nspatialFeaturePlot <- function(object, features = NULL, signaling = NULL, pairLR.use = NULL, sample.use = NULL, enriched.only = TRUE,thresh = 0.05, do.group = TRUE,\n color.heatmap = \"Spectral\", n.colors = 8, direction = -1,\n do.binary = FALSE, cutoff = NULL, color.use = NULL, alpha = 1,\n point.size = 0.8, legend.size = 3, legend.text.size = 8, shape.by = 16, ncol = NULL,\n show.legend = TRUE, show.legend.combined = FALSE){\n data <- object@data\n meta <- object@meta\n coords <- object@images$coordinates\n samples <- meta$samples\n if (ncol(coords) == 2) {\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coords = coords\n coords[,1] = temp_coords[,2]\n coords[,2] = temp_coords[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n scales::viridis_pal(option = color.heatmap, direction = -1)(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n } else {\n colormap <- color.heatmap\n }\n\n if (is.null(features) & is.null(signaling) & is.null(pairLR.use)){\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)){\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)){\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)){\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n\n df <- data.frame(x = coords[, 1], y = coords[, 2])\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, enriched.only = enriched.only, thresh = thresh)\n feature.use <- res$geneLR\n } else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n } else {\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(paste0('There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.'))\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\",\"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex, object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex, object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n } else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) > 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n } else if (length(intersect(feature.use, colnames(meta))) > 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[ ,feature.use, drop = FALSE])\n } else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \",cutoff,\"to the values...\", '\\n')\n data.use[data.use <= cutoff] <- 0\n }\n\n\n if (is.null(ncol)) {\n if (length(feature.use) > 9) {\n ncol <- 4\n } else {\n ncol <- min(length(feature.use), 4)\n }\n }\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i, ]\n g <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = feature.data), alpha = alpha, size=point.size, shape=shape.by) +\n scale_colour_gradientn(colours = colormap, guide = guide_colorbar(title = NULL, ticks = T, label = T, barwidth = 0.5), na.value = \"grey90\") +\n theme(legend.position = \"right\") +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size), legend.key.size = unit(0.15, \"inches\")) + # , legend.key.size = unit(0.4, \"inches\")\n ggtitle(feature.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))+\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n theme(legend.key = element_blank())\n g <- g + coord_fixed() + theme(aspect.ratio = 1) + scale_y_reverse()\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (show.legend.combined & i == numFeature) {\n g <- g + theme(legend.position = \"right\", legend.key.height = grid::unit(0.15, \"in\"), legend.key.width = grid::unit(0.5, \"in\"), legend.title = element_blank(),legend.key = element_blank())\n }\n gg[[i]] <- g\n }\n if (ncol > 1) {\n gg <- patchwork::wrap_plots(gg, ncol = ncol)\n } else {\n gg <- gg[[1]]\n }\n\n } else {\n\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, enriched.only = enriched.only, thresh = thresh)\n # gene.pair = searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n # LR.pair <- gene.pair[res$interaction_name, c(\"ligand\",\"receptor\")]\n LR.pair <- object@LR$LRsig[res$interaction_name, c(\"ligand\",\"receptor\")]\n } else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n } else {\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(paste0('There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.'))\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\",\"receptor\")]\n } else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n # compute the expression of ligand or receptor\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL; rownames(dataR) <- geneR;\n # data.use <- matrix(0, nrow = nrow(dataL)*2, ncol = ncol(dataL))\n # data.use[seq_len(nrow(data.use)) %% 2 == 1, ] <- dataL\n # data.use[seq_len(nrow(data.use)) %% 2 == 0, ] <- dataR\n # rownames(data.use)[seq_len(nrow(data.use)) %% 2 == 1] <- geneL\n # rownames(data.use)[seq_len(nrow(data.use)) %% 2 == 0] <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n if (is.null(ncol)) {\n if (length(feature.use) > 9) {\n ncol <- 4\n } else {\n ncol <- min(length(feature.use), 4)\n }\n }\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \" )\n }\n gg <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i, ] > cutoff\n idx2 = dataR[i, ] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\",ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i],geneR[i],\"Both\",\"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i],geneR[i],\"Both\",\"None\")\n\n if (length(setdiff(levels(group), unique(group))) > 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group), unique(group)))\n }\n\n df$feature.data <- group\n g <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = feature.data), alpha = alpha, size=point.size, shape=shape.by) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size), legend.key.size = unit(0.15, \"inches\")) + # , legend.key.size = unit(0.4, \"inches\")\n guides(color = guide_legend(override.aes = list(size=legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))+\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n theme(legend.key = element_blank())\n g <- g + coord_fixed() + theme(aspect.ratio = 1) + scale_y_reverse()\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (show.legend.combined & i == numFeature) {\n g <- g + theme(legend.position = \"right\", legend.key.height = grid::unit(0.15, \"in\"), legend.key.width = grid::unit(0.5, \"in\"), legend.title = element_blank(),legend.key = element_blank())\n }\n gg[[i]] <- g\n }\n if (ncol > 1) {\n gg <- patchwork::wrap_plots(gg, ncol = ncol)\n } else {\n gg <- gg[[1]]\n }\n\n }\n return(gg)\n}\n", "middle_code": "function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = 0.5,\n sources.use = NULL, targets.use = NULL, signaling = NULL,\n color.use = NULL, color.use.pattern = NULL, color.use.signaling = \"grey50\",\n do.order = FALSE, main.title = NULL,\n font.size = 2.5, font.size.title = 12){\n message(\"Please make sure you have load `library(ggalluvial)` when running this function\")\n requireNamespace(\"ggalluvial\")\n res.pattern <- methods::slot(object, slot.name)$pattern[[pattern]]\n data1 = res.pattern$pattern$cell\n data2 = res.pattern$pattern$signaling\n if (is.null(color.use.pattern)) {\n nPatterns <- length(unique(data1$Pattern))\n if (pattern == \"outgoing\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(1,nPatterns*2, by = 2)]\n } else if (pattern == \"incoming\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(2,nPatterns*2, by = 2)]\n }\n }\n if (is.null(main.title)) {\n if (pattern == \"outgoing\") {\n main.title = \"Outgoing communication patterns of secreting cells\"\n } else if (pattern == \"incoming\") {\n main.title = \"Incoming communication patterns of target cells\"\n }\n }\n if (is.null(data2)) {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n if (is.null(color.use)) {\n color.use <- scPalette(nCellGroup)\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n gg <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10))+\n ggtitle(main.title)\n } else {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n cells.level = levels(object@idents)\n if (is.null(color.use)) {\n color.use <- scPalette(length(cells.level))[cells.level %in% unique(plot.data$CellGroup)]\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n if (!is.null(sources.use)) {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% sources.use)\n }\n if (!is.null(targets.use)) {\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% targets.use)\n }\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n StatStratum <- ggalluvial::StatStratum\n gg1 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10)) +\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n data2$Contribution[data2$Contribution < cutoff] <- 0\n plot.data <- data2\n nPatterns<-length(unique(plot.data$Pattern))\n nSignaling<-length(unique(plot.data$Signaling))\n if (length(color.use.signaling) == 1) {\n color.use.all <- c(color.use.pattern, rep(color.use.signaling, nSignaling))\n } else {\n color.use.all <- c(color.use.pattern, color.use.signaling)\n }\n if (!is.null(signaling)) {\n plot.data <- plot.data[plot.data$Signaling %in% signaling, ]\n }\n plot.data.long <- ggalluvial::to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"Signaling\"]], plot.data[[\"Pattern\"]]), sum)\n mat[is.na(mat)] <- 0; mat <- mat[-which(rowSums(mat) == 0), ]\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(colnames(mat),names(cluster)[order.name]))\n }\n gg2 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"Pattern\", \"Signaling\")),y= Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"forward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) + \n scale_x_discrete(limits = c(), labels=c(\"Patterns\", \"Signaling\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size= 10))+\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n gg <- cowplot::plot_grid(gg1, gg2,align = \"h\", nrow = 1)\n title <- cowplot::ggdraw() + cowplot::draw_label(main.title,size = font.size.title)\n gg <- cowplot::plot_grid(title, gg, ncol=1, rel_heights=c(0.1, 1))\n }\n return(gg)\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/CellChat/R/analysis.R", "\n#' Compute and visualize the contribution of each ligand-receptor pair in the overall signaling pathways\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param width the width of individual bar\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param return.data whether return the data.frame consisting of the predicted L-R pairs and their contribution\n#' @param x.rotation rotation of x-label\n#' @param title the title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom dplyr select\n#' @importFrom ggplot2 ggplot geom_bar aes coord_flip scale_x_discrete element_text theme ggtitle\n#' @importFrom cowplot ggdraw draw_label plot_grid\n#'\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_contribution <- function(object, signaling, signaling.name = NULL, sources.use = NULL, targets.use = NULL,\n width = 0.1, vertex.receiver = NULL, thresh = 0.05, return.data = FALSE,\n x.rotation = 0, title = \"Contribution of each L-R pair\",\n font.size = 10, font.size.title = 10) {\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pair.name.use = select(object@DB$interaction[rownames(pairLR),],\"interaction_name_2\")\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n\n prob <- prob[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n dimnames(prob)[3] <- pairLR.name.use\n }\n prob <-(prob-min(prob))/(max(prob)-min(prob))\n\n if (is.null(vertex.receiver)) {\n pSum <- apply(prob, 3, sum)\n pSum.max <- sum(prob)\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n y.lim <- max(pSum)\n\n pair.name <- unlist(dimnames(prob)[3])\n pair.name <- factor(pair.name, levels = unique(pair.name))\n if (!is.null(pairLR.name.use)) {\n pair.name <- pair.name.use[as.character(pair.name),1]\n pair.name <- factor(pair.name, levels = unique(pair.name))\n }\n mat <- pSum\n df1 <- data.frame(name = pair.name, contribution = mat)\n if(nrow(df1) < 10) {\n df2 <- data.frame(name = as.character(1:(10-nrow(df1))), contribution = rep(0, 10-nrow(df1)))\n df <- rbind(df1, df2)\n } else {\n df <- df1\n }\n df <- df[order(df$contribution, decreasing = TRUE), ]\n # df$name <- factor(df$name, levels = unique(df$name))\n df$name <- factor(df$name,levels=df$name[order(df$contribution, decreasing = TRUE)])\n df1$name <- factor(df1$name,levels=df1$name[order(df1$contribution, decreasing = TRUE)])\n gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\", width = 0.7) +\n theme_classic() + theme(axis.text.y = element_text(angle = x.rotation, hjust = 1,size=font.size, colour = 'black'), axis.text=element_text(size=font.size),\n axis.title.y = element_text(size= font.size), axis.text.x = element_blank(), axis.ticks = element_blank()) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim) + coord_flip() + theme(legend.position=\"none\") +\n scale_x_discrete(limits = rev(levels(df$name)), labels = c(rep(\"\", max(0, 10-nlevels(df1$name))),rev(levels(df1$name))))\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5, size = font.size.title))\n }\n gg\n\n } else {\n pair.name <- factor(unlist(dimnames(prob)[3]), levels = unique(unlist(dimnames(prob)[3])))\n # show all the communications\n pSum <- apply(prob, 3, sum)\n pSum.max <- sum(prob)\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n y.lim <- max(pSum)\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\",width = 0.2) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8),\n axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"All\")+ theme(plot.title = element_text(hjust = 0.5))#+\n\n # show the communications in Hierarchy1\n if (dim(prob)[3] > 1) {\n pSum <- apply(prob[,vertex.receiver,], 3, sum)\n } else {\n pSum <- sum(prob[,vertex.receiver,])\n }\n\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg1 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\",width = 0.2) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"Hierarchy1\") + theme(plot.title = element_text(hjust = 0.5))#+\n #scale_x_discrete(limits = c(0,1))\n\n # show the communications in Hierarchy2\n\n if (dim(prob)[3] > 1) {\n pSum <- apply(prob[,setdiff(1:dim(prob)[1],vertex.receiver),], 3, sum)\n } else {\n pSum <- sum(prob[,setdiff(1:dim(prob)[1],vertex.receiver),])\n }\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg2 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\", width=0.9) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"Hierarchy2\")+ theme(plot.title = element_text(hjust = 0.5))#+\n #scale_x_discrete(limits = c(0,1))\n title <- cowplot::ggdraw() + cowplot::draw_label(paste0(\"Contribution of each signaling in \", signaling.name, \" pathway\"), fontface='bold', size = 10)\n gg.combined <- cowplot::plot_grid(gg, gg1, gg2, nrow = 1)\n gg.combined <- cowplot::plot_grid(title, gg.combined, ncol = 1, rel_heights=c(0.1, 1))\n gg <- gg.combined\n gg\n }\n if (return.data) {\n df <- subset(df, contribution > 0)\n return(list(LR.contribution = df, gg.obj = gg))\n } else {\n return(gg)\n }\n}\n\n\n#' Compute the network centrality scores allowing identification of dominant senders, receivers, mediators and influencers in all inferred communication networks\n#'\n#' NB: This function was previously named as `netAnalysis_signalingRole`. The previous function `netVisual_signalingRole` is now named as `netAnalysis_signalingRole_network`.\n#'\n#' @param object CellChat object; If object = NULL, USER must provide `net`\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks. Setting slot.name = \"netP\" to compute the network centrality scores at the level of signaling pathways, and setting slot.name = \"net\" to compute the network centrality scores at the level of ligand-receptor pairs\n#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net\n#' @param net.name a character vector giving the name of signaling networks\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom future nbrOfWorkers\n#' @importFrom methods slot\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#'\n#' @return\n#' @export\n#'\nnetAnalysis_computeCentrality <- function(object = NULL, slot.name = \"netP\", net = NULL, net.name = NULL, thresh = 0.05) {\n if (is.null(net)) {\n prob <- methods::slot(object, slot.name)$prob\n pval <- methods::slot(object, slot.name)$pval\n pval[prob == 0] <- 1\n prob[pval >= thresh] <- 0\n net = prob\n }\n if (is.null(net.name)) {\n net.name <- dimnames(net)[[3]]\n }\n if (length(dim(net)) == 3) {\n nrun <- dim(net)[3]\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n centr.all = my.sapply(\n X = 1:nrun,\n FUN = function(x) {\n net0 <- net[ , , x]\n return(computeCentralityLocal(net0))\n },\n simplify = FALSE\n )\n } else {\n centr.all <- as.list(computeCentralityLocal(net))\n }\n names(centr.all) <- net.name\n if (is.null(object)) {\n return(centr.all)\n } else {\n slot(object, slot.name)$centr <- centr.all\n return(object)\n }\n}\n\n\n\n#' Compute Centrality measures for a signaling network\n#'\n#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net\n#' @importFrom igraph graph_from_adjacency_matrix strength hub_score authority_score eigen_centrality page_rank betweenness E\n#' @importFrom sna flowbet infocent\n#'\n#' @return\ncomputeCentralityLocal <- function(net) {\n centr <- vector(\"list\")\n G <- igraph::graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n centr$outdeg_unweighted <- rowSums(net > 0)\n centr$indeg_unweighted <- colSums(net > 0)\n centr$outdeg <- igraph::strength(G, mode=\"out\")\n centr$indeg <- igraph::strength(G, mode=\"in\")\n centr$hub <- igraph::hub_score(G)$vector\n centr$authority <- igraph::authority_score(G)$vector # A node has high authority when it is linked by many other nodes that are linking many other nodes.\n centr$eigen <- igraph::eigen_centrality(G)$vector # A measure of influence in the network that takes into account second-order connections\n centr$page_rank <- igraph::page_rank(G)$vector\n igraph::E(G)$weight <- 1/igraph::E(G)$weight\n centr$betweenness <- igraph::betweenness(G)\n #centr$flowbet <- try(sna::flowbet(net)) # a measure of its role as a gatekeeper for the flow of communication between any two cells; the total maximum flow (aggregated across all pairs of third parties) mediated by v.\n #centr$info <- try(sna::infocent(net)) # actors with higher information centrality are predicted to have greater control over the flow of information within a network; highly information-central individuals tend to have a large number of short paths to many others within the social structure.\n centr$flowbet <- tryCatch({\n sna::flowbet(net)\n }, error = function(e) {\n as.vector(matrix(0, nrow = nrow(net), ncol = 1))\n })\n centr$info <- tryCatch({\n sna::infocent(net, diag = T, rescale = T, cmode = \"lower\")\n # sna::infocent(net, diag = T, rescale = T, cmode = \"weak\")\n }, error = function(e) {\n as.vector(matrix(0, nrow = nrow(net), ncol = 1))\n })\n return(centr)\n}\n\n\n#' Select the number of the patterns for running `identifyCommunicationPatterns`\n#'\n#' We infer the number of patterns based on two metrics that have been implemented in the NMF R package, including Cophenetic and Silhouette. Both metrics measure the stability for a particular number of patterns based on a hierarchical clustering of the consensus matrix. For a range of the number of patterns, a suitable number of patterns is the one at which Cophenetic and Silhouette values begin to drop suddenly.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param k.range a range of the number of patterns\n#' @param title.name title of plot\n#' @param do.facet whether use facet plot showing the two measures\n#' @param nrun number of runs when performing NMF\n#' @param seed.use seed when performing NMF\n#' @importFrom methods slot\n# #' @importFrom NMF nmfEstimateRank\n#' @import NMF\n# #' @importFrom ggplot2 scale_color_brewer\n#' @import ggplot2\n#' @return a ggplot object\n#' @export\n#'\n#' @examples\nselectK <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), title.name = NULL, do.facet = TRUE, k.range = seq(2,10), nrun = 30, seed.use = 10) {\n pattern <- match.arg(pattern)\n prob <- methods::slot(object, slot.name)$prob\n if (pattern == \"outgoing\") {\n data_sender <- apply(prob, c(1,3), sum)\n data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_sender)\n } else if (pattern == \"incoming\") {\n data_receiver <- apply(prob, c(2,3), sum)\n data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_receiver)\n }\n options(warn = -1)\n data <- data0\n data <- data[rowSums(data)!=0,]\n\n if (is.null(title.name)) {\n title.name <- paste0(pattern, \" signaling \\n\")\n # title.name <- paste0(pattern, \" signaling \\n (nrun = \", nrun, \", seed = \", seed.use, \")\")\n }\n\n res <- NMF::nmfEstimateRank(data, range = k.range, method = 'lee', nrun=nrun, seed = seed.use)\n df1 <- data.frame(k = res$measures$rank, score = res$measures$cophenetic, Measure = \"Cophenetic\")\n df2 <- data.frame(k = res$measures$rank, score = res$measures$silhouette.consensus, Measure = \"Silhouette\")\n # df3 <- data.frame(k = res$measures$rank, score = res$measures$dispersion, Measure = \"Dispersion\")\n df <- rbind(df1, df2)\n #df <- rbind(df1, df2, df3)\n gg <- ggplot(df, aes(x = k, y = score, group = Measure, color = Measure)) + geom_line(size=1) +\n geom_point() +\n theme_classic() + labs(x = 'Number of patterns', y='Measure score') +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(legend.position = \"right\") + theme(text = element_text(size = 10)) + scale_x_discrete(limits = (unique(df$k))) +\n scale_color_brewer(palette=\"Set2\") + guides(color=guide_legend(\"Measure type\"))\n if (do.facet) {\n gg <- gg + facet_wrap(~ Measure, scales='free')\n }\n gg\n return(gg)\n}\n\n\n\n#' Identification of major signals for specific cell groups and general communication patterns\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param k the number of patterns\n#' @param k.range a range of the number of patterns\n#' @param heatmap.show whether showing heatmap\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param title.legend the title of legend in heatmap\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @importFrom methods slot\n#' @importFrom NMF nmfEstimateRank nmf\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation draw\n#' @importFrom stats setNames\n#' @importFrom grid grid.grabExpr grid.newpage pushViewport grid.draw unit gpar viewport popViewport\n#'\n#' @return\n#' @export\n#'\n#' @examples\n\nidentifyCommunicationPatterns <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), k = NULL, k.range = seq(2,10), heatmap.show = TRUE,\n color.use = NULL, color.heatmap = \"Spectral\", title.legend = \"Contributions\",\n width = 4, height = 6, font.size = 8) {\n pattern <- match.arg(pattern)\n prob <- methods::slot(object, slot.name)$prob\n if (pattern == \"outgoing\") {\n data_sender <- apply(prob, c(1,3), sum)\n data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_sender)\n } else if (pattern == \"incoming\") {\n data_receiver <- apply(prob, c(2,3), sum)\n data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_receiver)\n }\n options(warn = -1)\n data <- data0\n data <- data[rowSums(data)!=0,]\n if (is.null(k)) {\n stop(\"Please run the function `selectK` for selecting a suitable k!\")\n }\n\n outs_NMF <- NMF::nmf(data, rank = k, method = 'lee', seed = 'nndsvd')\n W <- scaleMat(outs_NMF@fit@W, 'r1')\n H <- scaleMat(outs_NMF@fit@H, 'c1')\n colnames(W) <- paste0(\"Pattern \", seq(1,ncol(W))); rownames(H) <- paste0(\"Pattern \", seq(1,nrow(H)));\n if (heatmap.show) {\n net <- W\n if (is.null(color.use)) {\n color.use <- scPalette(length(rownames(net)))\n }\n color.heatmap = grDevices::colorRampPalette(rev(RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(255)\n\n df<- data.frame(group = rownames(net)); rownames(df) <- rownames(net)\n cell.cols.assigned <- setNames(color.use, unique(as.character(df$group)))\n row_annotation <- HeatmapAnnotation(df = df, col = list(group = cell.cols.assigned),which = \"row\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ht1 = Heatmap(net, col = color.heatmap, na_col = \"white\", name = \"Contribution\",\n left_annotation = row_annotation,\n cluster_rows = T,cluster_columns = F,clustering_method_rows = \"average\",\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n show_heatmap_legend = F,\n column_title = \"Cell patterns\",column_title_gp = gpar(fontsize = 10)\n )\n\n\n net <- t(H)\n\n ht2 = Heatmap(net, col = color.heatmap, na_col = \"white\", name = \"Contribution\",\n cluster_rows = T,cluster_columns = F,clustering_method_rows = \"average\",\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = \"Communication patterns\",column_title_gp = gpar(fontsize = 10),\n heatmap_legend_param = list(title = title.legend, title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = c(round(min(net, na.rm = T), digits = 1), round(max(net, na.rm = T), digits = 1)),\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 6),grid_width = unit(2, \"mm\"))\n )\n\n gb_ht1 = grid.grabExpr(draw(ht1))\n gb_ht2 = grid.grabExpr(draw(ht2))\n #grid.newpage()\n pushViewport(viewport(x = 0.1, y = 0.1, width = 0.2, height = 0.5, just = c(\"left\", \"bottom\")))\n grid.draw(gb_ht1)\n popViewport()\n\n pushViewport(viewport(x = 0.6, y = 0.1, width = 0.2, height = 0.5, just = c(\"left\", \"bottom\")))\n grid.draw(gb_ht2)\n popViewport()\n\n }\n\n data_W <- as.data.frame(as.table(W)); colnames(data_W) <- c(\"CellGroup\",\"Pattern\",\"Contribution\")\n data_H <- as.data.frame(as.table(H)); colnames(data_H) <- c(\"Pattern\",\"Signaling\",\"Contribution\")\n\n res.pattern = list(\"cell\" = data_W, \"signaling\" = data_H)\n methods::slot(object, slot.name)$pattern[[pattern]] <- list(data = data0, pattern = res.pattern)\n return(object)\n}\n\n\n#' Compute signaling network similarity for any pair of signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param k the number of nearest neighbors\n#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity\n#' @importFrom methods slot\n\n#'\n#' @return\n#' @export\n#'\n#' @examples\ncomputeNetSimilarity <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), k = NULL, thresh = NULL) {\n type <- match.arg(type)\n prob = methods::slot(object, slot.name)$prob\n if (is.null(k)) {\n if (dim(prob)[3] <= 25) {\n k <- ceiling(sqrt(dim(prob)[3]))\n } else {\n k <- ceiling(sqrt(dim(prob)[3])) + 1\n }\n\n }\n if (!is.null(thresh)) {\n prob[prob < quantile(c(prob[prob != 0]), thresh)] <- 0\n }\n if (type == \"functional\") {\n # compute the functional similarity\n D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])\n S2 <- D_signalings; S3 <- D_signalings;\n for (i in 1:(dim(prob)[3]-1)) {\n for (j in (i+1):dim(prob)[3]) {\n Gi <- (prob[ , ,i] > 0)*1\n Gj <- (prob[ , ,j] > 0)*1\n S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)\n }\n }\n # define the similarity matrix\n S3[is.na(S3)] <- 0; S3 <- S3 + t(S3); diag(S3) <- 1\n # S_signalings <- S1 *S2\n S_signalings <- S3\n } else if (type == \"structural\") {\n # compute the structure distance\n D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])\n for (i in 1:(dim(prob)[3]-1)) {\n for (j in (i+1):dim(prob)[3]) {\n Gi <- (prob[ , ,i] > 0)*1\n Gj <- (prob[ , ,j] > 0)*1\n D_signalings[i,j] <- computeNetD_structure(Gi,Gj)\n }\n }\n # define the structure similarity matrix\n D_signalings[is.infinite(D_signalings)] <- 0\n D_signalings[is.na(D_signalings)] <- 0\n D_signalings <- D_signalings + t(D_signalings)\n S_signalings <- 1-D_signalings\n }\n\n # smooth the similarity matrix using SNN\n SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)\n Similarity <- as.matrix(S_signalings*SNN)\n rownames(Similarity) <- dimnames(prob)[[3]]\n colnames(Similarity) <- dimnames(prob)[[3]]\n\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {\n methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity\n return(object)\n}\n\n\n\n#' Compute signaling network similarity for any pair of datasets\n#'\n#' @param object A merged CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison\n#' @param k the number of nearest neighbors\n#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity\n#' @importFrom methods slot\n#'\n#' @return\n#' @export\n#'\ncomputeNetSimilarityPairwise <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, k = NULL, thresh = NULL) {\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Compute signaling network similarity for datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n net <- list()\n signalingAll <- c()\n object.net.nameAll <- c()\n # 1:length(setdiff(names(methods::slot(object, slot.name)), \"similarity\"))\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n object.net.name <- names(methods::slot(object, slot.name))[comparison[i]]\n object.net.nameAll <- c(object.net.nameAll, object.net.name)\n net[[i]] = object.net$prob\n signalingAll <- c(signalingAll, paste0(dimnames(net[[i]])[[3]], \"--\", object.net.name))\n # signalingAll <- c(signalingAll, dimnames(net[[i]])[[3]])\n }\n names(net) <- object.net.nameAll\n net.dim <- sapply(net, dim)[3,]\n nnet <- sum(net.dim)\n position <- cumsum(net.dim); position <- c(0,position)\n\n if (is.null(k)) {\n if (nnet <= 25) {\n k <- ceiling(sqrt(nnet))\n } else {\n k <- ceiling(sqrt(nnet)) + 1\n }\n\n }\n if (!is.null(thresh)) {\n for (i in 1:length(net)) {\n neti <- net[[i]]\n neti[neti < quantile(c(neti[neti != 0]), thresh)] <- 0\n net[[i]] <- neti\n }\n }\n if (type == \"functional\") {\n # compute the functional similarity\n S3 <- matrix(0, nrow = nnet, ncol = nnet)\n for (i in 1:nnet) {\n for (j in 1:nnet) {\n idx.i <- which(position - i >= 0)[1]\n idx.j <- which(position - j >= 0)[1]\n net.i <- net[[idx.i-1]]\n net.j <- net[[idx.j-1]]\n Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1\n Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1\n S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)\n }\n }\n\n # define the similarity matrix\n S3[is.na(S3)] <- 0; diag(S3) <- 1\n S_signalings <- S3\n } else if (type == \"structural\") {\n # compute the structure distance\n D_signalings <- matrix(0, nrow = nnet, ncol = nnet)\n for (i in 1:nnet) {\n for (j in 1:nnet) {\n idx.i <- which(position - i >= 0)[1]\n idx.j <- which(position - j >= 0)[1]\n net.i <- net[[idx.i-1]]\n net.j <- net[[idx.j-1]]\n Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1\n Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1\n D_signalings[i,j] <- computeNetD_structure(Gi,Gj)\n }\n }\n # define the structure similarity matrix\n D_signalings[is.infinite(D_signalings)] <- 0\n D_signalings[is.na(D_signalings)] <- 0\n S_signalings <- 1-D_signalings\n }\n # smooth the similarity matrix using SNN\n SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)\n Similarity <- as.matrix(S_signalings*SNN)\n rownames(Similarity) <- signalingAll\n colnames(Similarity) <- rownames(Similarity)\n\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {\n methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL\n }\n # methods::slot(object, slot.name)$similarity[[type]]$matrix <- Similarity\n methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity\n return(object)\n}\n\n\n#' Manifold learning of the signaling networks based on their similarity\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object\n#' @param pathway.remove a range of the number of patterns\n#' @param umap.method UMAP implementation to run.\n#'\n#' Can be umap-learn: Run the python umap-learn package; uwot: Runs umap via the uwot R package; If umap.method = \"uwot\", please make sure you have installed the 'uwot' (https://github.com/jlmelville/uwot)\n#'\n#' @param n_neighbors the number of nearest neighbors in running umap\n#' @param min_dist This controls how tightly the embedding is allowed compress points together.\n#' Larger values ensure embedded points are moreevenly distributed, while smaller values allow the\n#' algorithm to optimise more accurately with regard to local structure. Sensible values are in the range 0.001 to 0.5.\n#' @param ... Parameters passing to umap\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetEmbedding <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, pathway.remove = NULL,\n umap.method = c(\"umap-learn\", \"uwot\"), n_neighbors = NULL,min_dist = 0.3,...) {\n umap.method <- match.arg(umap.method)\n if (object@options$mode == \"single\") {\n comparison <- \"single\"\n cat(\"Manifold learning of the signaling networks for a single dataset\", '\\n')\n } else if (object@options$mode == \"merged\") {\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Manifold learning of the signaling networks for datasets\", as.character(comparison), '\\n')\n }\n comparison.name <- paste(comparison, collapse = \"-\")\n Similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n if (is.null(pathway.remove)) {\n pathway.remove <- rownames(Similarity)[which(colSums(Similarity) == 1)]\n }\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(rownames(Similarity) %in% pathway.remove)\n Similarity <- Similarity[-pathway.remove.idx, -pathway.remove.idx]\n }\n if (is.null(n_neighbors)) {\n n_neighbors <- ceiling(sqrt(dim(Similarity)[1])) + 1\n }\n options(warn = -1)\n # dimension reduction\n if (umap.method == \"umap-learn\") {\n Y <- runUMAP(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)\n } else if (umap.method == \"uwot\") {\n Y <- uwot::umap(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)\n colnames(Y) <- paste0('UMAP', 1:ncol(Y))\n rownames(Y) <- colnames(Similarity)\n }\n\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$dr)) {\n methods::slot(object, slot.name)$similarity[[type]]$dr <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]] <- Y\n return(object)\n}\n\n\n#' Classification learning of the signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object\n#' @param k the number of signaling groups when running kmeans\n#' @param methods the methods for clustering: \"kmeans\" or \"spectral\"\n#' @param do.plot whether showing the eigenspectrum for inferring number of clusters; Default will save the plot\n#' @param fig.id add a unique figure id when saving the plot\n#' @param do.parallel whether doing parallel when inferring the number of signaling groups when running kmeans\n#' @param nCores number of workers when doing parallel\n#' @param k.eigen the number of eigenvalues used when doing spectral clustering\n#' @importFrom methods slot\n#' @importFrom future nbrOfWorkers plan\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @return\n#' @export\n#'\n#' @examples\nnetClustering <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, k = NULL, methods = \"kmeans\", do.plot = TRUE, fig.id = NULL, do.parallel = TRUE, nCores = 4, k.eigen = NULL) {\n type <- match.arg(type)\n if (object@options$mode == \"single\") {\n comparison <- \"single\"\n cat(\"Classification learning of the signaling networks for a single dataset\", '\\n')\n } else if (object@options$mode == \"merged\") {\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Classification learning of the signaling networks for datasets\", as.character(comparison), '\\n')\n }\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n data.use <- Y\n if (methods == \"kmeans\") {\n if (!is.null(k)) {\n clusters = kmeans(data.use,k,nstart=10)$cluster\n } else {\n N <- nrow(data.use)\n kRange <- seq(2,min(N-1, 10),by = 1)\n if (do.parallel) {\n future::plan(\"multisession\", workers = nCores)\n options(future.globals.maxSize = 1000 * 1024^2)\n }\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n results = my.sapply(\n X = 1:length(kRange),\n FUN = function(x) {\n idents <- kmeans(data.use,kRange[x],nstart=10)$cluster\n clusIndex <- idents\n #adjMat0 <- as.numeric(outer(clusIndex, clusIndex, FUN = \"==\")) - outer(1:N, 1:N, \"==\")\n adjMat0 <- Matrix::Matrix(as.numeric(outer(clusIndex, clusIndex, FUN = \"==\")), nrow = N, ncol = N)\n return(list(adjMat = adjMat0, ncluster = length(unique(idents))))\n },\n simplify = FALSE\n )\n adjMat <- lapply(results, \"[[\", 1)\n CM <- Reduce('+', adjMat)/length(kRange)\n res <- computeEigengap(as.matrix(CM))\n numCluster <- res$upper_bound\n clusters = kmeans(data.use,numCluster,nstart=10)$cluster\n if (do.plot) {\n gg <- res$gg.obj\n ggsave(filename= paste0(\"estimationNumCluster_\",fig.id,\"_\",type,\"_dataset_\",comparison.name,\".pdf\"), plot=gg, width = 3.5, height = 3, units = 'in', dpi = 300)\n }\n }\n\n } else if (methods == \"spectral\") {\n A <- as.matrix(data.use)\n D <- apply(A, 1, sum)\n L <- diag(D)-A # unnormalized version\n L <- diag(D^-0.5)%*%L%*% diag(D^-0.5) # normalized version\n evL <- eigen(L,symmetric=TRUE) # evL$values is decreasing sorted when symmetric=TRUE\n # pick the first k first k eigenvectors (corresponding k smallest) as data points in spectral space\n plot(rev(evL$values)[1:30])\n Z <- evL$vectors[,(ncol(evL$vectors)-k.eigen+1):ncol(evL$vectors)]\n clusters = kmeans(Z,k,nstart=20)$cluster\n }\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$group)) {\n methods::slot(object, slot.name)$similarity[[type]]$group <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]] <- clusters\n return(object)\n}\n\n\n#' Build SNN matrix\n# #' Adapted from swne (https://github.com/yanwu2014/swne)\n#' @param data.use Features x samples matrix to use to build the SNN\n#' @param k Defines k for the k-nearest neighbor algorithm\n#' @param k.scale Granularity option for k.param\n#' @param prune.SNN Sets the cutoff for acceptable Jaccard distances when\n#' computing the neighborhood overlap for the SNN construction.\n#'\n#' @return Returns similarity matrix in sparse matrix format\n#'\n#' @importFrom FNN get.knn\n#' @importFrom Matrix sparseMatrix\n#' @export\n#'\nbuildSNN <- function(data.use, k = 10, k.scale = 10, prune.SNN = 1/15) {\n n.cells <- ncol(data.use)\n if (n.cells < k) {\n stop(\"k cannot be greater than the number of samples\")\n }\n\n ## find the k-nearest neighbors for each single cell\n my.knn <- FNN::get.knn(t(as.matrix(data.use)), k = min(k.scale * k, n.cells - 1))\n nn.ranked <- cbind(1:n.cells, my.knn$nn.index[, 1:(k - 1)])\n nn.large <- my.knn$nn.index\n\n w <- ComputeSNN(nn.ranked, prune.SNN)\n colnames(w) <- rownames(w) <- colnames(data.use)\n\n Matrix::diag(w) <- 1\n return(w)\n}\n\n\n\n#' Compute the eigengap of a given matrix for inferring the number of clusters\n#'\n#' @param CM consensus matrix\n#' @param tau truncated consensus matrix\n#' @param tol tolerance\n#' @return\n#' @import ggplot2\n#' @export\ncomputeEigengap <- function(CM, tau = NULL, tol = 0.01){\n # compute the drop tolerance, enforcing parsimony of components\n K.init <- computeLaplacian(CM, tol = tol)$n_zeros\n if (is.null(tau)) {\n if (K.init <= 5) {\n tau = 0.3\n } else if (K.init <= 10){\n tau = 0.4\n } else {\n tau = 0.5\n }\n }\n\n # truncate the ensemble consensus matrix\n CM[CM <= tau] <- 0;\n # normalize and make symmetric\n CM <- (CM + t(CM))/2\n eigs <- computeLaplacian(CM, tol = tol)\n\n # compute the largest eigengap\n gaps <- diff(eigs$val)\n upper_bound <- which(gaps == max(gaps))\n\n # compute the number of zero eigenvalues\n lower_bound <- eigs$n_zeros\n\n df <- data.frame(nCluster = 1:min(c(30,length(eigs$val))), eigenVal = eigs$val[1:min(c(30,length(eigs$val)))])\n g <- ggplot(df, aes(x = nCluster, y = eigenVal)) + geom_point(size = 1) +\n geom_point(aes(x= upper_bound, y= eigs$val[upper_bound]), colour=\"red\", size = 3, pch = 1) + theme(legend.position=\"none\")\n title.name <- paste0('Inferred number of clusters: ', upper_bound,'; Min number: ', lower_bound)\n g <- g + labs(title = title.name) + theme_bw() + scale_x_continuous(breaks=seq(0,30,5)) +\n theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = 10)) + labs(x = 'Number of clusters', y = 'Eigenvalue of graph Laplacian')+\n theme(axis.text.x = element_text(size = 8), axis.text.y = element_text(size = 8))\n # ggsave(filename= paste0(\"estimationNumCluster_eigenspectrum\",sample.int(100,1),\".pdf\"), plot=g, width = 3.5, height = 3, units = 'in', dpi = 300)\n return(list(upper_bound = upper_bound,\n lower_bound = lower_bound,\n eigs = eigs,\n gg.obj = g))\n\n}\n\n\n#' Compute eigenvalues of associated Laplacian matrix of a given matrix\n#'\n#' @param CM consensus matrix\n#' @param tol tolerance\n#' @return\n#' @importFrom RSpectra eigs_sym\n#' @importFrom Matrix colSums\n#' @export\ncomputeLaplacian <- function(CM, tol = 0.01) {\n # Normalized Laplacian:\n Dsq <- sqrt(Matrix::colSums(CM))\n L <- -Matrix::t(CM / Dsq) / Dsq\n Matrix::diag(L) <- 1 + Matrix::diag(L)\n\n numEigs <- min(100,nrow(CM))\n res <- RSpectra::eigs_sym(L, k = numEigs, which = \"SM\", opt = list(tol = 1e-4))\n eigs <- abs(Re(res$values))\n n_zeros <- sum(eigs <= tol)\n return(list(val = sort(eigs), n_zeros = n_zeros))\n}\n\n\n#' Rank the similarity of the shared signaling pathways based on their joint manifold learning\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison1 a numerical vector giving the datasets for comparison. This should be the same as `comparison` in `computeNetSimilarityPairwise`\n#' @param comparison2 a numerical vector with two elements giving the datasets for comparison.\n#'\n#' If there are more than 2 datasets defined in `comparison1`, `comparison2` can be defined to indicate which two datasets used for computing the distance.\n#' e.g., comparison2 = c(1,3) indicates the first and third datasets defined in `comparison1` will be used for comparison.\n#' @param x.rotation rotation of x-labels\n#' @param title main title of the plot\n#' @param bar.w the width of bar plot\n#' @param color.use defining the color\n#' @param font.size font size\n#' @import ggplot2\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nrankSimilarity <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison1 = NULL, comparison2 = c(1,2),\n x.rotation = 90, title = NULL, color.use = NULL, bar.w = NULL, font.size = 8) {\n type <- match.arg(type)\n\n if (is.null(comparison1)) {\n comparison1 <- 1:length(unique(object@meta$datasets))\n }\n comparison.name <- paste(comparison1, collapse = \"-\")\n cat(\"Compute the distance of signaling networks between datasets\", as.character(comparison1[comparison2]), '\\n')\n comparison2.name <- names(methods::slot(object, slot.name))[comparison1[comparison2]]\n # net <- list()\n # for (i in 1:length(comparison2)) {\n # net[[i]] = methods::slot(object, slot.name)[[comparison1[comparison2[i]]]]$prob\n # }\n\n #net.dim <- sapply(net, dim)[3,]\n #position <- cumsum(net.dim); position <- c(0,position)\n # if (is.null(pathway.remove)) {\n # similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n # pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove.idx <- which(rownames(similarity) %in% pathway.remove)\n # }\n\n # if (length(pathway.remove.idx) > 0) {\n # for (i in 1:length(pathway.remove.idx)) {\n # idx <- which(position - pathway.remove.idx[i] > 0)\n # if (!is.null(idx)) {\n # position[idx[1]] <- position[idx[1]] - 1\n # if (idx[1] == 2) {\n # position[3] <- position[3] - 1\n # }\n # }\n # }\n # }\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n group <- sub(\".*--\", \"\", rownames(Y))\n data1 <- Y[group %in% comparison2.name[1], ]\n data2 <- Y[group %in% comparison2.name[2], ]\n rownames(data1) <- sub(\"--.*\", \"\", rownames(data1))\n rownames(data2) <- sub(\"--.*\", \"\", rownames(data2))\n\n pathway.show = as.character(intersect(rownames(data1), rownames(data2)))\n data1 <- data1[pathway.show, ]\n data2 <- data2[pathway.show, ]\n euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))\n dist <- NULL\n for(i in 1:nrow(data1)) dist[i] <- euc.dist(data1[i,],data2[i,])\n df <- data.frame(name = pathway.show, dist = dist, row.names = pathway.show)\n df <- df[order(df$dist), , drop = F]\n df$name <- factor(df$name, levels = as.character(df$name))\n\n gg <- ggplot(df, aes(x=name, y=dist)) + geom_bar(stat=\"identity\",width = bar.w) +\n theme_classic() + theme(text=element_text(size=font.size),axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_text(size=font.size)) +\n xlab(\"\") + ylab(\"Pathway distance\") + coord_flip()#+\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n if (!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = 1), drop = FALSE, na.value = \"white\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, na.value = \"white\")\n }\n return(gg)\n}\n\n\n\n\n\n\n\n#' Rank signaling networks based on the information flow or the number of interactions\n#'\n#' This function can also be used to rank signaling from certain cell groups to other cell groups\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param measure \"weight\" or \"count\". \"weight\": comparing the total interaction weights (strength); \"count\": comparing the number of interactions;\n#' @param mode \"single\",\"comparison\"\n#' @param comparison a numerical vector giving the datasets for comparison; a single value means ranking for only one dataset and two values means ranking comparison for two datasets\n#' @param color.use defining the color for each cell group\n#' @param stacked whether plot the stacked bar plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a vector giving the signaling pathway to show\n#' @param pairLR a vector giving the names of L-R pairs to show (e.g, pairLR = c(\"IL1A_IL1R1_IL1RAP\",\"IL1B_IL1R1_IL1RAP\"))\n#' @param signaling.type a char giving the types of signaling from the three categories c(\"Secreted Signaling\", \"ECM-Receptor\", \"Cell-Cell Contact\")\n#' @param do.stat whether do a Wilcoxon test to determine whether there is significant difference between two datasets. Default = FALSE\n#' @param paired.test a logical indicating whether you want a paired test. Paired test is applicable to compare two datasets with the same cellular compositions.\n#' @param cutoff.pvalue the cutoff of pvalue when doing Wilcoxon test; Default = 0.05\n#' @param tol a tolerance when considering the relative contribution being equal between two datasets. contribution.relative between 1-tol and 1+tol will be considered as equal contribution\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @param do.flip whether flip the x-y axis\n#' @param x.angle,y.angle,x.hjust,y.hjust parameters for rotating and spacing axis labels\n#' @param axis.gap whetehr making gaps in y-axes\n#' @param ylim,segments,tick_width,rel_heights parameters in the function gg.gap when making gaps in y-axes\n#' e.g., ylim = c(0, 35), segments = list(c(11, 14),c(16, 28)), tick_width = c(5,2,5), rel_heights = c(0.8,0,0.1,0,0.1)\n#' https://tobiasbusch.xyz/an-r-package-for-everything-ep2-gaps\n#' @param show.raw whether show the raw information flow. Default = FALSE, showing the scaled information flow to provide compariable data scale; When stacked = TRUE, use raw information flow by default.\n#' @param return.data whether return the data.frame consisting of the calculated information flow of each signaling pathway or L-R pair\n#' @param x.rotation rotation of x-labels\n#' @param title main title of the plot\n#' @param bar.w the width of bar plot\n#' @param font.size font size\n\n#' @import ggplot2\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nrankNet <- function(object, slot.name = \"netP\", measure = c(\"weight\",\"count\"), mode = c(\"comparison\", \"single\"), comparison = c(1,2), color.use = NULL, stacked = FALSE, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR = NULL, signaling.type = NULL, do.stat = FALSE, paired.test = TRUE, cutoff.pvalue = 0.05, tol = 0.05, thresh = 0.05, show.raw = FALSE, return.data = FALSE, x.rotation = 90, title = NULL, bar.w = 0.75, font.size = 8,\n do.flip = TRUE, x.angle = NULL, y.angle = 0, x.hjust = 1,y.hjust = 1,\n axis.gap = FALSE, ylim = NULL, segments = NULL, tick_width = NULL, rel_heights = c(0.9,0,0.1)) {\n measure <- match.arg(measure)\n mode <- match.arg(mode)\n options(warn = -1)\n object.names <- names(methods::slot(object, slot.name))\n if (measure == \"weight\") {\n ylabel = \"Information flow\"\n } else if (measure == \"count\") {\n ylabel = \"Number of interactions\"\n }\n if (mode == \"single\") {\n object1 <- methods::slot(object, slot.name)\n prob = object1$prob\n prob[object1$pval > thresh] <- 0\n if (measure == \"count\") {\n prob <- 1*(prob > 0)\n }\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n if (sum(prob) == 0) {\n stop(\"No inferred communications for the input!\")\n }\n\n pSum <- apply(prob, 3, sum)\n pSum.original <- pSum\n if (measure == \"weight\") {\n pSum <- -1/log(pSum)\n pSum[is.na(pSum)] <- 0\n idx1 <- which(is.infinite(pSum) | pSum < 0)\n values.assign <- seq(max(pSum)*1.1, max(pSum)*1.5, length.out = length(idx1))\n position <- sort(pSum.original[idx1], index.return = TRUE)$ix\n pSum[idx1] <- values.assign[match(1:length(idx1), position)]\n } else if (measure == \"count\") {\n pSum <- pSum.original\n }\n\n pair.name <- names(pSum)\n\n df<- data.frame(name = pair.name, contribution = pSum.original, contribution.scaled = pSum, group = object.names[comparison[1]])\n idx <- with(df, order(df$contribution))\n df <- df[idx, ]\n df$name <- factor(df$name, levels = as.character(df$name))\n for (i in 1:length(pair.name)) {\n df.t <- df[df$name == pair.name[i], \"contribution\"]\n if (sum(df.t) == 0) {\n df <- df[-which(df$name == pair.name[i]), ]\n }\n }\n\n if (!is.null(signaling.type)) {\n LR <- subset(object@DB$interaction, annotation %in% signaling.type)\n if (slot.name == \"netP\") {\n signaling <- unique(LR$pathway_name)\n } else if (slot.name == \"net\") {\n pairLR <- LR$interaction_name\n }\n }\n\n if ((slot.name == \"netP\") && (!is.null(signaling))) {\n df <- subset(df, name %in% signaling)\n } else if ((slot.name == \"netP\") &&(!is.null(pairLR))) {\n stop(\"You need to set `slot.name == 'net'` if showing specific L-R pairs \")\n }\n if ((slot.name == \"net\") && (!is.null(pairLR))) {\n df <- subset(df, name %in% pairLR)\n } else if ((slot.name == \"net\") && (!is.null(signaling))) {\n stop(\"You need to set `slot.name == 'netP'` if showing specific signaling pathways \")\n }\n\n gg <- ggplot(df, aes(x=name, y=contribution.scaled)) + geom_bar(stat=\"identity\",width = bar.w) +\n theme_classic() + theme(axis.text=element_text(size=font.size),axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(ylabel) + coord_flip()#+\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n\n } else if (mode == \"comparison\") {\n prob.list <- list()\n pSum <- list()\n pSum.original <- list()\n pair.name <- list()\n idx <- list()\n pSum.original.all <- c()\n object.names.comparison <- c()\n for (i in 1:length(comparison)) {\n object.list <- methods::slot(object, slot.name)[[comparison[i]]]\n prob <- object.list$prob\n prob[object.list$pval > thresh] <- 0\n if (measure == \"count\") {\n prob <- 1*(prob > 0)\n }\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n if (sum(prob) == 0) {\n stop(\"No inferred communications for the input!\")\n }\n prob.list[[i]] <- prob\n pSum.original[[i]] <- apply(prob, 3, sum)\n if (measure == \"weight\") {\n pSum[[i]] <- -1/log(pSum.original[[i]])\n pSum[[i]][is.na(pSum[[i]])] <- 0\n idx[[i]] <- which(is.infinite(pSum[[i]]) | pSum[[i]] < 0)\n pSum.original.all <- c(pSum.original.all, pSum.original[[i]][idx[[i]]])\n } else if (measure == \"count\") {\n pSum[[i]] <- pSum.original[[i]] # the prob is already binarized in line 1136\n }\n pair.name[[i]] <- names(pSum.original[[i]])\n object.names.comparison <- c(object.names.comparison, object.names[comparison[i]])\n }\n if (measure == \"weight\") {\n values.assign <- seq(max(unlist(pSum))*1.1, max(unlist(pSum))*1.5, length.out = length(unlist(idx)))\n position <- sort(pSum.original.all, index.return = TRUE)$ix\n for (i in 1:length(comparison)) {\n if (i == 1) {\n pSum[[i]][idx[[i]]] <- values.assign[match(1:length(idx[[i]]), position)]\n } else {\n pSum[[i]][idx[[i]]] <- values.assign[match(length(unlist(idx[1:i-1]))+1:length(unlist(idx[1:i])), position)]\n }\n }\n }\n\n\n\n pair.name.all <- as.character(unique(unlist(pair.name)))\n df <- list()\n for (i in 1:length(comparison)) {\n df[[i]] <- data.frame(name = pair.name.all, contribution = 0, contribution.scaled = 0, group = object.names[comparison[i]], row.names = pair.name.all)\n df[[i]][pair.name[[i]],3] <- pSum[[i]]\n df[[i]][pair.name[[i]],2] <- pSum.original[[i]]\n }\n\n\n # contribution.relative <- as.numeric(format(df[[length(comparison)]]$contribution/abs(df[[1]]$contribution), digits=1))\n # # contribution.relative <- as.numeric(format(df[[length(comparison)]]$contribution.scaled/abs(df[[1]]$contribution.scaled), digits=1))\n # contribution.relative2 <- as.numeric(format(df[[length(comparison)-1]]$contribution/abs(df[[1]]$contribution), digits=1))\n # contribution.relative[is.na(contribution.relative)] <- 0\n # for (i in 1:length(comparison)) {\n # df[[i]]$contribution.relative <- contribution.relative\n # df[[i]]$contribution.relative2 <- contribution.relative2\n # }\n # df[[1]]$contribution.data2 <- df[[length(comparison)]]$contribution\n # idx <- with(df[[1]], order(-contribution.relative, -contribution.relative2, contribution, -contribution.data2))\n #\n contribution.relative <- list()\n for (i in 1:(length(comparison)-1)) {\n contribution.relative[[i]] <- as.numeric(format(df[[length(comparison)-i+1]]$contribution/df[[1]]$contribution, digits=1))\n contribution.relative[[i]][is.na(contribution.relative[[i]])] <- 0\n }\n names(contribution.relative) <- paste0(\"contribution.relative.\", 1:length(contribution.relative))\n for (i in 1:length(comparison)) {\n for (j in 1:length(contribution.relative)) {\n df[[i]][[names(contribution.relative)[j]]] <- contribution.relative[[j]]\n }\n }\n df[[1]]$contribution.data2 <- df[[length(comparison)]]$contribution\n if (length(comparison) == 2) {\n idx <- with(df[[1]], order(-contribution.relative.1, contribution, -contribution.data2))\n } else if (length(comparison) == 3) {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2,contribution, -contribution.data2))\n } else if (length(comparison) == 4) {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2, -contribution.relative.3, contribution, -contribution.data2))\n } else {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2, -contribution.relative.3, -contribution.relative.4, contribution, -contribution.data2))\n }\n\n\n\n for (i in 1:length(comparison)) {\n df[[i]] <- df[[i]][idx, ]\n df[[i]]$name <- factor(df[[i]]$name, levels = as.character(df[[i]]$name))\n }\n df[[1]]$contribution.data2 <- NULL\n\n df <- do.call(rbind, df)\n df$group <- factor(df$group, levels = object.names.comparison)\n\n if (is.null(color.use)) {\n color.use = ggPalette(length(comparison))\n }\n\n # https://stackoverflow.com/questions/49448497/coord-flip-changes-ordering-of-bars-within-groups-in-grouped-bar-plot\n df$group <- factor(df$group, levels = rev(levels(df$group)))\n color.use <- rev(color.use)\n\n # perform statistical analysis\n # if (do.stat) {\n # pvalues <- c()\n # for (i in 1:length(pair.name.all)) {\n # df.prob <- data.frame()\n # for (j in 1:length(comparison)) {\n # if (pair.name.all[i] %in% pair.name[[j]]) {\n # df.prob <- rbind(df.prob, data.frame(prob = as.vector(prob.list[[j]][ , , pair.name.all[i]]), group = comparison[j]))\n # } else {\n # df.prob <- rbind(df.prob, data.frame(prob = as.vector(matrix(0, nrow = nrow(prob.list[[j]]), ncol = nrow(prob.list[[j]]))), group = comparison[j]))\n # }\n #\n # }\n # df.prob$group <- factor(df.prob$group, levels = comparison)\n # if (length(comparison) == 2) {\n # pvalues[i] <- wilcox.test(prob ~ group, data = df.prob)$p.value\n # } else {\n # pvalues[i] <- kruskal.test(prob ~ group, data = df.prob)$p.value\n # }\n # }\n # df$pvalues <- pvalues\n # }\n if (do.stat & length(comparison) == 2) {\n for (i in 1:length(pair.name.all)) {\n if (nrow(prob.list[[j]]) != nrow(prob.list[[1]])) {\n if (paired.test) {\n stop(\"Paired test is not applicable to datasets with different cellular compositions! Please set `do.stat = FALSE` or `paired.test = FALSE`! \\n\")\n }\n }\n prob.values <- matrix(0, nrow = nrow(prob.list[[1]]) * nrow(prob.list[[1]]), ncol = length(comparison))\n for (j in 1:length(comparison)) {\n if (pair.name.all[i] %in% pair.name[[j]]) {\n prob.values[, j] <- as.vector(prob.list[[j]][ , , pair.name.all[i]])\n } else {\n prob.values[, j] <- NA\n }\n }\n prob.values <- prob.values[rowSums(prob.values, na.rm = TRUE) != 0, , drop = FALSE]\n if (nrow(prob.values) >3 & sum(is.na(prob.values)) == 0) {\n pvalues <- wilcox.test(prob.values[ ,1], prob.values[ ,2], paired = paired.test)$p.value\n } else {\n pvalues <- 0\n }\n pvalues[is.na(pvalues)] <- 0\n df$pvalues[df$name == pair.name.all[i]] <- pvalues\n }\n }\n\n\n if (length(comparison) == 2) {\n if (do.stat) {\n colors.text <- ifelse((df$contribution.relative < 1-tol) & (df$pvalues < cutoff.pvalue), color.use[2], ifelse((df$contribution.relative > 1+tol) & df$pvalues < cutoff.pvalue, color.use[1], \"black\"))\n } else {\n colors.text <- ifelse(df$contribution.relative < 1-tol, color.use[2], ifelse(df$contribution.relative > 1+tol, color.use[1], \"black\"))\n }\n } else {\n message(\"The text on the y-axis will not be colored for the number of compared datasets larger than 3!\")\n colors.text = NULL\n }\n\n for (i in 1:length(pair.name.all)) {\n df.t <- df[df$name == pair.name.all[i], \"contribution\"]\n if (sum(df.t) == 0) {\n df <- df[-which(df$name == pair.name.all[i]), ]\n }\n }\n\n if ((slot.name == \"netP\") && (!is.null(signaling))) {\n df <- subset(df, name %in% signaling)\n } else if ((slot.name == \"netP\") &&(!is.null(pairLR))) {\n stop(\"You need to set `slot.name == 'net'` if showing specific L-R pairs \")\n }\n if ((slot.name == \"net\") && (!is.null(pairLR))) {\n df <- subset(df, name %in% pairLR)\n } else if ((slot.name == \"net\") && (!is.null(signaling))) {\n stop(\"You need to set `slot.name == 'netP'` if showing specific signaling pathways \")\n }\n\n if (stacked) {\n gg <- ggplot(df, aes(x=name, y=contribution, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position =\"fill\") # +\n # xlab(\"\") + ylab(\"Relative information flow\") #+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n # scale_y_discrete(breaks=c(\"0\",\"0.5\",\"1\")) +\n if (measure == \"weight\") {\n gg <- gg + xlab(\"\") + ylab(\"Relative information flow\")\n } else if (measure == \"count\") {\n gg <- gg + xlab(\"\") + ylab(\"Relative number of interactions\")\n }\n\n gg <- gg + geom_hline(yintercept = 0.5, linetype=\"dashed\", color = \"grey50\", size=0.5)\n } else {\n if (show.raw) {\n gg <- ggplot(df, aes(x=name, y=contribution, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position = position_dodge(0.8)) +\n xlab(\"\") + ylab(ylabel) #+ coord_flip()#+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n } else {\n gg <- ggplot(df, aes(x=name, y=contribution.scaled, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position = position_dodge(0.8)) +\n xlab(\"\") + ylab(ylabel) #+ coord_flip()#+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n }\n\n if (axis.gap) {\n gg <- gg + theme_bw() + theme(panel.grid = element_blank())\n gg.gap::gg.gap(gg,\n ylim = ylim,\n segments = segments,\n tick_width = tick_width,\n rel_heights = rel_heights)\n }\n }\n gg <- gg + CellChat_theme_opts() + theme_classic()\n if (do.flip) {\n gg <- gg + coord_flip() + theme(axis.text.y = element_text(colour = colors.text))\n if (is.null(x.angle)) {\n x.angle = 0\n }\n\n } else {\n if (is.null(x.angle)) {\n x.angle = 45\n }\n gg <- gg + scale_x_discrete(limits = rev) + theme(axis.text.x = element_text(colour = rev(colors.text)))\n\n }\n\n gg <- gg + theme(axis.text=element_text(size=font.size), axis.title.y = element_text(size=font.size))\n gg <- gg + scale_fill_manual(name = \"\", values = color.use)\n gg <- gg + guides(fill = guide_legend(reverse = TRUE))\n gg <- gg + theme(axis.text.x = element_text(angle = x.angle, hjust=x.hjust),\n axis.text.y = element_text(angle = y.angle, hjust=y.hjust))\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n }\n\n if (return.data) {\n df$contribution <- abs(df$contribution)\n df$contribution.scaled <- abs(df$contribution.scaled)\n return(list(signaling.contribution = df, gg.obj = gg))\n } else {\n return(gg)\n }\n}\n\n\n#' Comparing the number of inferred communication links between different datasets\n#'\n#' @param object A merged CellChat object\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param color.use defining the color for each group of datasets\n#' @param group a vector giving the groups of different datasets to define colors of the bar plot. Default: only one group and a single color\n#' @param group.levels the factor level in the defined group\n#' @param group.facet Name of one metadata column defining faceting groups\n#' @param group.facet.levels the factor level in the defined group.facet\n#' @param n.row Number of rows in facet_grid()\n#' @param color.alpha transparency\n#' @param legend.title legend title\n#' @param width bar width\n#' @param title.name main title of the plot\n#' @param digits integer indicating the number of decimal places (round) to be used when `measure` is `weight`.\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param remove.xtick whether remove xtick\n#' @param size.text font size of the text\n#' @param show.legend whether show the legend\n#' @param x.lab.rot,angle.x,vjust.x,hjust.x adjusting parameters if rotating xtick.labels when x.lab.rot = TRUE\n#' @import ggplot2\n#' @return A ggplot object\n#' @export\n#'\ncompareInteractions <- function(object, measure = c(\"count\", \"weight\"), color.use = NULL, group = NULL, group.levels = NULL, group.facet = NULL, group.facet.levels = NULL, n.row = 1, color.alpha = 1, legend.title = NULL, width=0.6, title.name = NULL, digits = 3,\n xlabel = NULL, ylabel = NULL, remove.xtick = FALSE,\n show.legend = TRUE, x.lab.rot = FALSE, angle.x = 45, vjust.x = NULL, hjust.x = 1, size.text = 10) {\n measure <- match.arg(measure)\n if (measure == \"count\") {\n df <- as.data.frame(sapply(object@net, function(x) sum(x$count)))\n if (is.null(ylabel)) {\n ylabel = \"Number of inferred interactions\"\n }\n } else if (measure == \"weight\") {\n df <- as.data.frame(sapply(object@net, function(x) sum(x$weight)))\n df[,1] <- round(df[,1],digits)\n if (is.null(ylabel)) {\n ylabel = \"Interaction strength\"\n }\n }\n colnames(df) <- \"count\"\n\n df$dataset <- names(object@net)\n if (is.null(group)) {\n group <- 1\n }\n df$group <- group\n df$dataset <- factor(df$dataset, levels = names(object@net))\n if (is.null(group.levels)) {\n df$group <- factor(df$group)\n } else {\n df$group <- factor(df$group, levels = group.levels)\n }\n\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(group)))\n }\n # theme_classic() #+ scale_x_discrete(limits = (levels(df$x)))\n if (!is.null(group.facet)) {\n if (all(group.facet %in% colnames(df))) {\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n gg <- gg + facet_wrap(group.facet, nrow = n.row)\n } else {\n df$group.facet <- group.facet\n if (is.null(group.facet.levels)) {\n df$group.facet <- factor(df$group.facet)\n } else {\n df$group.facet <- factor(df$group.facet, levels = group.facet.levels)\n }\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n gg <- gg + facet_wrap(~group.facet, nrow = n.row)\n }\n } else {\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n }\n gg <- gg + geom_text(aes(label=count), vjust=-0.3, size=3, position = position_dodge(0.9))\n gg <- gg + ylab(ylabel) + xlab(xlabel) + theme_classic() +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = size.text), axis.text = element_text(colour=\"black\"))\n gg <- gg + scale_fill_manual(values = alpha(color.use, alpha = color.alpha), drop = FALSE)\n # gg <- gg + scale_color_manual(values = alpha(color.use, alpha = 1), drop = FALSE) + guides(colour = FALSE)\n if (remove.xtick) {\n gg <- gg + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank())\n }\n if (is.null(legend.title)) {\n gg <- gg + theme(legend.title = element_blank())\n } else {\n gg <- gg + guides(fill=guide_legend(legend.title))\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n if (x.lab.rot) {\n gg <- gg + theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x, vjust = vjust.x, size=size.text))\n }\n gg\n return(gg)\n}\n\n\n#' Rank ligand-receptor interactions for any pair of two cell groups\n#'\n#' @param object CellChat object\n#' @param LR.use ligand-receptor interactions used in inferring communication network\n#' @return\n#' @export\n#'\nrankNetPairwise <- function(object, LR.use = NULL) {\n if (is.null(LR.use)) {\n pairLR.use <- object@LR$LRsig\n } else {\n pairLR.use <- LR.use\n }\n net <- object@net\n prob <- net$prob\n pval <- net$pval\n numCluster <- dim(prob)[1]\n pairwiseLR <- list()\n for (i in 1:numCluster) {\n temp <- list()\n for (j in 1:numCluster) {\n pvalij <- pval[i,j,]; pvalij <- as.vector(pvalij)\n probij <- prob[i,j,]; probij <- as.vector(probij)\n index <- 1:length(pvalij)\n data <- data.frame(pathway_index = index, interaction_name = pairLR.use$interaction_name, interaction_name_2 = pairLR.use$interaction_name_2, pathway_name = pairLR.use$pathway_name, ligand = pairLR.use$ligand, receptor = pairLR.use$receptor,\n prob = probij, pval = pvalij, row.names = rownames(pairLR.use))\n temp[[j]] <- data[with(data, order(pval, -prob)), ]\n }\n names(temp) <- colnames(prob)\n pairwiseLR[[i]] <- temp\n }\n names(pairwiseLR) <- rownames(prob)\n object@net$pairwiseRank <- pairwiseLR\n return(object)\n}\n\n\n#' compute the Shannon entropy\n#'\n#' @param a a numeric vector\n#' @return\nentropia<-function(a){\n a<-a[which(a>0)]\n return(-sum(a*log(a)))\n}\n\n\n#' compute the node distance matrix\n#'\n#' @param g a graph objecct\n#' @return\nnode_distance<-function(g){\n n<-length(V(g))\n if(n==1){\n retorno=1\n }\n\n if(n>1){\n a<-Matrix::Matrix(0,nrow=n,ncol=n,sparse=TRUE)\n m<-igraph::shortest.paths(g,algorithm=c(\"unweighted\"))\n m[which(m==\"Inf\")]<-n\n quem<-setdiff(intersect(m,m),0)\n for(j in (1:length(quem))){\n\n l<-which(m==quem[j])/n\n\n linhas<-floor(l)+1\n\n posicoesm1<-which(l==floor(l))\n\n if(length(posicoesm1)>0){\n linhas[posicoesm1]<-linhas[posicoesm1]-1\n }\n a[1:n,quem[j]]<-hist(linhas,plot=FALSE,breaks=(0:n))$counts\n\n }\n retorno=(a/(n-1))\n }\n return(retorno)\n}\n\n\n#' compute nnd\n#'\n#' @param g a graph objecct\n#' @return\nnnd<-function(g){\n\n N<-length(V(g))\n\n nd<-node_distance(g)\n\n pdfm<-Matrix::colMeans(nd)\n\n norm<-log(max(c(2,length(which(pdfm[1:(N-1)]>0))+1)))\n\n return(c(pdfm,max(c(0,entropia(pdfm)-entropia(as.matrix(nd))/N))/norm))\n}\n\n#' compute alpha centrality\n#'\n#' @param g a graph objecct\n#' @importFrom igraph degree alpha.centrality\n#' @return\nalpha_centrality<-function(g){\n\n N<-length(igraph::V(g))\n\n r<-sort(igraph::alpha.centrality(g,exo=igraph::degree(g)/(N-1),alpha=1/N))/((N^2))\n\n return(c(r,max(c(0,1-sum(r)))))\n\n}\n\n#' Compute the structural distance between two signaling networks\n#'\n#' @param g a graph object of one signaling network\n#' @param h a graph object of another signaling network\n#' @param w1 parameter\n#' @param w2 parameter\n#' @param w3 parameter\n#' @importFrom igraph graph_from_adjacency_matrix V graph.complementer\n#' @return\n#' @export\n#'\n#' @examples\ncomputeNetD_structure <- function(g, h, w1 = 0.45, w2 = 0.45, w3 = 0.1){\n\n first<-0\n\n second<-0\n\n third<-0\n\n # g<-read.graph(g,format=c(\"edgelist\"),directed=FALSE)\n #\n # h<-read.graph(h,format=c(\"edgelist\"),directed=FALSE)\n\n g <- graph_from_adjacency_matrix(g,mode=\"directed\")\n h <- graph_from_adjacency_matrix(h,mode=\"directed\")\n\n N<-length(V(g))\n\n M<-length(V(h))\n\n PM<-matrix(0,ncol=max(c(M,N)))\n\n if(w1+w2>0){\n\n pg = nnd(g)\n\n PM[1:(N-1)]=pg[1:(N-1)]\n\n PM[length(PM)]<-pg[N]\n\n ph=nnd(h)\n\n PM[1:(M-1)]=PM[1:(M-1)]+ph[1:(M-1)]\n\n PM[length(PM)]<-PM[length(PM)]+ph[M]\n\n PM<-PM/2\n\n first<-sqrt(max(c((entropia(PM)-(entropia(pg[1:N])+entropia(ph[1:M]))/2)/log(2),0)))\n\n second<-abs(sqrt(pg[N+1])-sqrt(ph[M+1]))\n\n\n }\n\n if(w3>0){\n\n pg<-alpha_centrality(g)\n\n ph<-alpha_centrality(h)\n\n m<-max(c(length(pg),length(ph)))\n\n Pg<-matrix(0,ncol=m)\n\n Ph<-matrix(0,ncol=m)\n\n Pg[(m-length(pg)+1):m]<-pg\n\n Ph[(m-length(ph)+1):m]<-ph\n\n third<-third+sqrt((entropia((Pg+Ph)/2)-(entropia(pg)+entropia(ph))/2)/log(2))/2\n\n g<-graph.complementer(g)\n\n h<-graph.complementer(h)\n\n\n pg<-alpha_centrality(g)\n\n ph<-alpha_centrality(h)\n\n m<-max(c(length(pg),length(ph)))\n\n Pg<-matrix(0,ncol=m)\n\n Ph<-matrix(0,ncol=m)\n\n Pg[(m-length(pg)+1):m]<-pg\n\n Ph[(m-length(ph)+1):m]<-ph\n\n third<-third+sqrt((entropia((Pg+Ph)/2)-(entropia(pg)+entropia(ph))/2)/log(2))/2\n }\n return(w1*first+w2*second+w3*third)\n}\n\n\n#' Identify all the significant interactions (L-R pairs) and related signaling genes for a given signaling pathway\n#'\n#' @param object CellChat object\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param geneLR.return whether return the related signaling genes of enriched L-R pairs\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param geneInfo a dataframe with gene official symbol (there should be one column named `Symbol`)\n#' @param complex_input signaling complex information from CellChatDB\n#' @importFrom dplyr select\n#'\n#' @return The returned value depends on the input argument:\n#'\n#' When `geneLR.return = FALSE`, it returns a data frame containing the significant interactions (L-R pairs)\n#'\n#' When `geneLR.return = TRUE`, it returns a list, the first element is a data frame containing the significant interactions (L-R pairs), and the second is a vector containing the related signaling genes of enriched L-R pairs, which can be used for examining the gene expression pattern using the function \\code{\\link{plotGeneExpression}}\n#'\n#' @export\n#'\nextractEnrichedLR <- function(object, signaling, geneLR.return = FALSE, enriched.only = TRUE, thresh = 0.05, geneInfo = NULL, complex_input = NULL) {\n DB <- object@DB\n if (is.null(geneInfo)) {\n geneInfo = DB$geneInfo\n } else {\n DB$geneInfo = geneInfo\n }\n if (is.null(complex_input)) {\n complex_input = DB$complex\n } else {\n DB$complex = complex_input\n }\n pairLR.all <- c()\n geneLR.all <- c()\n net0 <- slot(object, \"net\")\n for (ii in 1:length(signaling)) {\n signaling.i <- signaling[ii]\n if (object@options$mode == \"single\") {\n net <- net0\n LR <- object@LR\n res <- extractEnrichedLR_internal(net, LR, DB, signaling = signaling.i, enriched.only = enriched.only, thresh = thresh)\n } else {\n geneLR.t <- c()\n pairLR.t <- c()\n for (i in 1:length(net0)) {\n net <- net0[[i]]\n LR <- object@LR[[i]]\n res.t <- extractEnrichedLR_internal(net, LR, DB, signaling = signaling.i, enriched.only = enriched.only, thresh = thresh)\n geneLR.t <- BiocGenerics::union(geneLR.t, as.character(res.t[[1]]))\n pairLR.t <- BiocGenerics::union(pairLR.t, as.character(res.t[[2]]))\n }\n res <- list(geneLR.t, pairLR.t)\n }\n geneLR.all <- c(geneLR.all, as.character(res[[1]]))\n pairLR.all <- c(pairLR.all, as.character(res[[2]]))\n }\n pairLR.all <- data.frame(interaction_name = pairLR.all, stringsAsFactors = FALSE)\n\n if (geneLR.return) {\n return(list(pairLR = pairLR.all, geneLR = geneLR.all))\n } else {\n return(pairLR.all)\n }\n}\n\n#' Identify all the significant interactions (L-R pairs) and related signaling genes for a given signaling pathway\n#'\n#' @param net,LR,DB object@net object@LR object@DB\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom dplyr select\n#'\n#' @return a list: list(geneLR, pairLR.name.use)\nextractEnrichedLR_internal <- function(net, LR, DB, signaling, enriched.only = TRUE, thresh = 0.05){\n pairLR <- searchPair(signaling = signaling, pairLR.use = LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.name.use = dplyr::select(DB$interaction[rownames(pairLR),],\"interaction_name\")\n if (enriched.only) {\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n if (length(pairLR.name.use) == 0) {\n message(paste0('There is no significant communication of ', signaling))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n }\n geneL <- unique(pairLR$ligand)\n geneR <- unique(pairLR$receptor)\n geneL <- extractGeneSubset(geneL, DB$complex, DB$geneInfo)\n geneR <- extractGeneSubset(geneR, DB$complex, DB$geneInfo)\n geneLR <- c(geneL, geneR)\n return(list(geneLR, pairLR.name.use))\n}\n\n\n#' Compute the maximum value of certain measures in the inferred cell-cell communication networks\n#'\n#' To better control the node size and edge weights of the inferred networks across different datasets,\n#' we compute the maximum number of cells per cell group and the maximum number of interactions (or interaction weights) across all datasets\n#'\n#' @param object.list List of CellChat objects\n#' @param slot.name the slot name of object that is used to compute the maximum value.\n#'\n#' When slot.name = \"idents\", 'attribute' should be \"idents\", which will compute the maximum number of cells per cell group across all datasets\n#'\n#' When slot.name = \"net\", 'attribute' can be either \"count\" or \"weight\", which will compute he maximum number of interactions (or interaction weights) across all datasets\n#'\n#' When slot.name = \"net\" or \"netP\", 'attribute' can be a single pathway name or a ligand-receptor pair name\n#'\n#' @param attribute the attribute to compute the maximum values. `attribute` should have the same length as `slot.name`.\n#'\n#' `attribute` can only be \"count\", \"weight\",\"count.merged\",\"weight.merged\" or a single pathway name or a ligand-receptor pair name\n#'\n#' @return A numeric vector\n#' @export\n#'\ngetMaxWeight <- function(object.list, slot.name = c(\"idents\", \"net\"), attribute = c(\"idents\", \"count\")) {\n weight <- c()\n for (i in 1:length(slot.name)) {\n if (slot.name[i] == \"idents\") {\n weight.all <- sapply(object.list, function (x) {max(as.numeric(table(slot(x, slot.name[i]))))})\n } else if ((slot.name[i] == \"net\") & (attribute[i] %in% c(\"count\", \"weight\",\"count.merged\",\"weight.merged\"))) {\n weight.all <- sapply(object.list, function (x) {max(slot(x, slot.name[i])[[attribute[i]]])})\n } else if (attribute[i] %in% c(object.list[[1]]@DB$interaction$pathway_name, object.list[[1]]@DB$interaction$interaction_name)) {\n weight.all <- sapply(object.list, function (x) {max(slot(x, slot.name[i])$prob[,,attribute[i]])})\n }\n weight[i] <- max(weight.all)\n }\n names(weight) <- attribute\n weight.max <- weight\n return(weight.max)\n}\n\n\n#' Compute the number of interactions/interaction strength between cell types based on their associated cell subpopulations\n#'\n#' @param object CellChat object\n#' @param group.merged a factor defining the group for merging different clusters/subpopulations\n#'\n#' @return An updated slot `net` by adding three elements:\n#'\n#' `count.merged`: the number of interactions between cell types (i.e., merged cell groups)\n#'\n#' `weight.merged`: interaction strength between cell types (i.e., merged cell groups)\n#'\n#' `group.merged` the defined group for merging different clusters/subpopulations\n#'\n#' @export\n#'\nmergeInteractions <- function(object, group.merged) {\n if (!is.factor(group.merged)) {\n group.merged <- factor(group.merged)\n }\n count <- object@net$count\n count.merged <- matrix(0, nrow = nlevels(group.merged), ncol = nlevels(group.merged))\n rownames(count.merged) <- levels(group.merged); colnames(count.merged) <- levels(group.merged);\n weight <- object@net$weight\n weight.merged <- count.merged\n dimnames(weight.merged) <- dimnames(count.merged)\n for (i in levels(group.merged)) {\n for (j in levels(group.merged)) {\n count.merged[i, j] <- sum(count[group.merged == i, group.merged == j])\n weight.merged[i, j] <- sum(weight[group.merged == i, group.merged == j])\n }\n }\n object@net$count.merged <- count.merged\n object@net$weight.merged <- weight.merged\n object@net$group.merged <- group.merged\n return(object)\n}\n\n\n#' Subset the inferred cell-cell communications of interest\n#'\n#' NB: If all arguments are NULL, it returns a data frame consisting of all the inferred cell-cell communications\n#'\n#' @param object CellChat object\n#' @param net Alternative input is a data frame with at least with three columns defining the cell-cell communication network (\"source\",\"target\",\"interaction_name\")\n#' @param slot.name the slot name of object: slot.name = \"net\" when extracting the inferred communications at the level of ligands/receptors; slot.name = \"netP\" when extracting the inferred communications at the level of signaling pathways\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param datasets select the inferred cell-cell communications from a particular `datasets` when inputing a data frame `net`\n#' @param ligand.pvalues,ligand.logFC,ligand.pct.1,ligand.pct.2 set threshold for ligand genes\n#'\n#' ligand.pvalues: threshold for pvalues in the differential expression gene analysis (DEG)\n#'\n#' ligand.logFC: threshold for logFoldChange in the DEG analysis; When ligand.logFC > 0, keep upgulated genes; otherwise, kepp downregulated genes\n#'\n#' ligand.pct.1: threshold for the percent of expressed genes in the defined 'positive' cell group. keep genes with percent greater than ligand.pct.1\n#'\n#' ligand.pct.2: threshold for the percent of expressed genes in the cells except for the defined 'positive' cell group\n#'\n#' @param receptor.pvalues,receptor.logFC,receptor.pct.1,receptor.pct.2 set threshold for receptor genes\n#' @importFrom dplyr select group_by summarize groups\n#' @importFrom stringr str_split\n#' @importFrom BiocGenerics as.data.frame\n#' @importFrom reshape2 melt\n#' @importFrom magrittr %>%\n#'\n#' @return If input object is created from a single dataset, a data frame of the inferred cell-cell communications of interest, consisting of source, target, interaction_name, pathway_name, prob and other information\n#'\n#' If input object is a merged object from multiple datasets, it will return a list and each element is a data frame for one dataset\n#'\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # access all the inferred cell-cell communications\n#' df.net <- subsetCommunication(cellchat)\n#'\n#' # access all the inferred cell-cell communications at the level of signaling pathways\n#' df.net <- subsetCommunication(cellchat, slot.name = \"netP\")\n#'\n#' # Subset to certain cells with sources.use and targets.use\n#' df.net <- subsetCommunication(cellchat, sources.use = c(1,2), targets.use = c(4,5))\n#'\n#' # Subset to certain signaling, e.g., WNT and TGFb\n#' df.net <- subsetCommunication(cellchat, signaling = c(\"WNT\", \"TGFb\"))\n#'}\n#'\nsubsetCommunication <- function(object = NULL, net = NULL, slot.name = \"net\",\n sources.use = NULL, targets.use = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n thresh = 0.05,\n datasets = NULL, ligand.pvalues = NULL, ligand.logFC = NULL, ligand.pct.1 = NULL, ligand.pct.2 = NULL,\n receptor.pvalues = NULL, receptor.logFC = NULL, receptor.pct.1 = NULL, receptor.pct.2 = NULL) {\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n message(\"slot.name is set to be 'netP' when pairLR.use contains signaling pathways\")\n slot.name = \"netP\"\n }\n }\n\n if (!is.null(pairLR.use) & !is.null(signaling)) {\n stop(\"Please do not assign values to 'signaling' when using 'pairLR.use'\")\n }\n\n if (object@options$mode == \"single\") {\n if (is.null(net)) {\n net <- slot(object, \"net\")\n }\n LR <- object@LR$LRsig\n cells.level <- levels(object@idents)\n df.net <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n } else if (object@options$mode == \"merged\") {\n if (is.null(net)) {\n net0 <- slot(object, \"net\")\n df.net <- vector(\"list\", length(net0))\n names(df.net) <- names(net0)\n for (i in 1:length(net0)) {\n net <- net0[[i]]\n LR <- object@LR[[i]]$LRsig\n cells.level <- levels(object@idents[[i]])\n\n df.net[[i]] <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n }\n } else {\n LR <- data.frame()\n for (i in 1:length(object@LR)) {\n LR <- rbind(LR, object@LR[[i]]$LRsig)\n }\n LR <- unique(LR)\n cells.level <- levels(object@idents$joint)\n df.net <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n }\n\n }\n\n return(df.net)\n\n}\n\n#' Subset the inferred cell-cell communications of interest\n#'\n#' NB: If all arguments are NULL, it returns a data frame consisting of all the inferred cell-cell communications\n#'\n#' @param net,LR,cells.level net is object@net or a data frame; LR: object@LR$LRsig; cells.level: levels(object@idents)\n#' @param slot.name the slot name of object: slot.name = \"net\" when extracting the inferred communications at the level of ligands/receptors; slot.name = \"netP\" when extracting the inferred communications at the level of signaling pathways\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param datasets select the inferred cell-cell communications from a particular `datasets` when inputing a data frame `net`\n#' @param ligand.pvalues,ligand.logFC,ligand.pct.1,ligand.pct.2 set threshold for ligand genes\n#'\n#' ligand.pvalues: threshold for pvalues in the differential expression gene analysis (DEG)\n#'\n#' ligand.logFC: threshold for logFoldChange in the DEG analysis; When ligand.logFC > 0, keep upgulated genes; otherwise, kepp downregulated genes\n#'\n#' ligand.pct.1: threshold for the percent of expressed genes in the defined 'positive' cell group. keep genes with percent greater than ligand.pct.1\n#'\n#' ligand.pct.2: threshold for the percent of expressed genes in the cells except for the defined 'positive' cell group\n#'\n#' @param receptor.pvalues,receptor.logFC,receptor.pct.1,receptor.pct.2 set threshold for receptor genes\n#' @importFrom dplyr select group_by summarize groups\n#' @importFrom stringr str_split\n#' @importFrom BiocGenerics as.data.frame\n#' @importFrom reshape2 melt\n#' @importFrom magrittr %>%\n#'\n#' @return A data frame of the inferred cell-cell communications of interest, consisting of source, target, interaction_name, pathway_name, prob and other information\n\nsubsetCommunication_internal <- function(net, LR, cells.level, slot.name = \"net\",\n sources.use = NULL, targets.use = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n thresh = 0.05,\n datasets = NULL, ligand.pvalues = NULL, ligand.logFC = NULL, ligand.pct.1 = NULL, ligand.pct.2 = NULL,\n receptor.pvalues = NULL, receptor.logFC = NULL, receptor.pct.1 = NULL, receptor.pct.2 = NULL) {\n if (!is.data.frame(net)) {\n prob <- net$prob\n pval <- net$pval\n prob[pval >= thresh] <- 0\n net <- reshape2::melt(prob, value.name = \"prob\")\n colnames(net)[1:3] <- c(\"source\",\"target\",\"interaction_name\")\n net.pval <- reshape2::melt(pval, value.name = \"pval\")\n net$pval <- net.pval$pval\n # remove the interactions with zero values\n net <- subset(net, prob > 0)\n }\n if (!(\"ligand\" %in% colnames(net))) {\n col.use <- intersect(c(\"interaction_name_2\", \"pathway_name\", \"ligand\", \"receptor\" ,\"annotation\",\"evidence\"), colnames(LR))\n pairLR <- dplyr::select(LR, col.use)\n idx <- match(net$interaction_name, rownames(pairLR))\n net <- cbind(net, pairLR[idx,])\n }\n\n if (!is.null(signaling)) {\n pairLR.use <- data.frame()\n for (i in 1:length(signaling)) {\n pairLR.use.i <- searchPair(signaling = signaling[i], pairLR.use = LR, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.use <- rbind(pairLR.use, pairLR.use.i)\n }\n }\n\n if (!is.null(pairLR.use)){\n net <- tryCatch({\n subset(net,interaction_name %in% pairLR.use$interaction_name)\n }, error = function(e) {\n subset(net, pathway_name %in% pairLR.use$pathway_name)\n })\n }\n\n if (!is.null(datasets)) {\n if (!(\"datasets\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before selecting 'datasets'\")\n }\n net <- net[net$datasets %in% datasets, , drop = FALSE]\n }\n if (!is.null(ligand.pvalues)){\n if (!(\"ligand.pvalues\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pvalues'\")\n }\n net <- net[net$ligand.pvalues <= ligand.pvalues, , drop = FALSE]\n }\n if (!is.null(ligand.logFC)){\n if (!(\"ligand.logFC\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.logFC'\")\n }\n if (ligand.logFC >= 0) {\n net <- net[net$ligand.logFC >= ligand.logFC, , drop = FALSE]\n } else {\n net <- net[net$ligand.logFC <= ligand.logFC, , drop = FALSE]\n }\n }\n if (!is.null(ligand.pct.1)){\n if (!(\"ligand.pct.1\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pct.1'\")\n }\n net <- net[net$ligand.pct.1 >= ligand.pct.1, , drop = FALSE]\n }\n if (!is.null(ligand.pct.2)){\n if (!(\"ligand.pct.2\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pct.2'\")\n }\n net <- net[net$ligand.pct.2 >= ligand.pct.2, , drop = FALSE]\n }\n\n if (!is.null(receptor.pvalues)){\n if (!(\"receptor.pvalues\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pvalues'\")\n }\n net <- net[net$receptor.pvalues <= receptor.pvalues, , drop = FALSE]\n }\n if (!is.null(receptor.logFC)){\n if (!(\"receptor.logFC\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.logFC'\")\n }\n if (receptor.logFC >= 0) {\n net <- net[net$receptor.logFC >= receptor.logFC, , drop = FALSE]\n } else {\n net <- net[net$receptor.logFC <= receptor.logFC, , drop = FALSE]\n }\n }\n if (!is.null(receptor.pct.1)){\n if (!(\"receptor.pct.1\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pct.1'\")\n }\n net <- net[net$receptor.pct.1 >= receptor.pct.1, , drop = FALSE]\n }\n if (!is.null(receptor.pct.2)){\n if (!(\"receptor.pct.2\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pct.2'\")\n }\n net <- net[net$receptor.pct.2 >= receptor.pct.2, , drop = FALSE]\n }\n\n net <- net[rowSums(is.na(net)) != ncol(net), , drop = FALSE]\n\n if (nrow(net) == 0) {\n stop(\"No significant signaling interactions are inferred based on the input!\")\n }\n\n\n if (slot.name == \"netP\") {\n col.use <- intersect(c(\"source\",\"target\",\"pathway_name\",\"prob\", \"pval\",\"annotation\"), colnames(net))\n net <- dplyr::select(net, col.use)\n net$source_target <- paste(net$source, net$target, sep = \"sourceTotarget\")\n # net$source_target_pathway <- paste(paste(net$source, net$target, sep = \"_\"), net$pathway_name, sep = \"_\")\n net.pval <- net %>% group_by(source_target, pathway_name) %>% summarize(pval = mean(pval), .groups = 'drop')\n net <- net %>% group_by(source_target, pathway_name) %>% summarize(prob = sum(prob), .groups = 'drop')\n a <- stringr::str_split(net$source_target, \"sourceTotarget\", simplify = T)\n net$source <- as.character(a[, 1])\n net$target <- as.character(a[, 2])\n net <- dplyr::select(net, -source_target)\n net$pval <- net.pval$pval\n }\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n }\n\n net <- BiocGenerics::as.data.frame(net, stringsAsFactors=FALSE)\n\n if (nrow(net) == 0) {\n warning(\"No significant signaling interactions are inferred!\")\n } else {\n rownames(net) <- 1:nrow(net)\n }\n\n if (slot.name == \"net\") {\n if ((\"ligand.logFC\" %in% colnames(net)) & (\"datasets\" %in% colnames(net))) {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\",\n \"datasets\",\"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\", \"ligand.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\", \"receptor.pvalues\"), colnames(net))\n net <- net[,col.use]\n } else if (\"ligand.logFC\" %in% colnames(net)) {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\",\n \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\", \"ligand.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\", \"receptor.pvalues\"), colnames(net))\n net <- net[,col.use]\n } else {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\"), colnames(net))\n net <- net[,col.use]\n }\n } else if (slot.name == \"netP\") {\n col.use <- intersect(c(\"source\", \"target\", \"pathway_name\", \"prob\", \"pval\"), colnames(net))\n net <- net[,col.use]\n }\n\n return(net)\n\n}\n\n\n\n\n\n\n\n\n\n\n#' Heatmap showing the centrality scores/importance of cell groups as senders, receivers, mediators and influencers in a single intercellular communication network\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the name of signaling networks\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param measure centrality measures to show\n#' @param measure.name the names of centrality measures to show\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation draw\n#' @importFrom stats setNames\n#'\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_signalingRole_network <- function(object, signaling, slot.name = \"netP\", measure = c(\"outdeg\",\"indeg\",\"flowbet\",\"info\"), measure.name = c(\"Sender\",\"Receiver\",\"Mediator\",\"Influencer\"),\n color.use = NULL, color.heatmap = \"BuGn\",\n width = 6.5, height = 1.4, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE) {\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n centr <- slot(object, slot.name)$centr[signaling]\n for(i in 1:length(centr)) {\n centr0 <- centr[[i]]\n mat <- matrix(unlist(centr0), ncol = length(centr0), byrow = FALSE)\n mat <- t(mat)\n rownames(mat) <- names(centr0); colnames(mat) <- names(centr0$outdeg)\n if (!is.null(measure)) {\n mat <- mat[measure,,drop = FALSE]\n if (!is.null(measure.name)) {\n if (length(measure.name) != length(measure)) {\n stop(\"The length of `measure.name` is not the same as that of `measure`! Please modify it! \\n\")\n }\n rownames(mat) <- measure.name\n }\n }\n mat <- sweep(mat, 1L, apply(mat, 1, max), '/', check.margin = FALSE)\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(colnames(mat)))\n }\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n\n df<- data.frame(group = colnames(mat)); rownames(df) <- colnames(mat)\n cell.cols.assigned <- setNames(color.use, unique(as.character(df$group)))\n col_annotation <- HeatmapAnnotation(df = df, col = list(group = cell.cols.assigned),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = \"Importance\",\n bottom_annotation = col_annotation,\n cluster_rows = cluster.rows,cluster_columns = cluster.cols,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = paste0(names(centr[i]), \" signaling pathway network\"),column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 45,\n heatmap_legend_param = list(title = \"Importance\", title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = c(round(min(mat, na.rm = T), digits = 1), round(max(mat, na.rm = T), digits = 1)),\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n draw(ht1)\n }\n}\n\n\n#' 2D visualization of dominant senders (sources) and receivers (targets)\n#'\n#' @description\n#' This scatter plot shows the dominant senders (sources) and receivers (targets) in a 2D space.\n#' x-axis and y-axis are respectively the total outgoing or incoming communication probability associated with each cell group.\n#' Dot size is proportional to the number of inferred links (both outgoing and incoming) associated with each cell group.\n#' Dot colors indicate different cell groups. Dot shapes indicate different categories of cell groups if `group`` is defined.\n#'\n#' @param object CellChat object\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param color.use defining the color for each cell group\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param group a vector to categorize the cell groups, e.g., categorize the cell groups into two major categories: immune cells and fibroblasts\n#' @param weight.MinMax the Minmum/maximum weight, which is useful to control the dot size when comparing multiple datasets\n#' @param point.shape point shape when group is not NULL\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size a range defining the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_signalingRole_scatter <- function(object, signaling = NULL, color.use = NULL, slot.name = \"netP\", group = NULL, weight.MinMax = NULL, dot.size = c(2, 6), point.shape = c(21, 22, 24, 23, 25, 8, 3), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\",xlabel = \"Outgoing interaction strength\", ylabel = \"Incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n centr <- slot(object, slot.name)$centr\n outgoing <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n incoming <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n dimnames(outgoing) <- list(levels(object@idents), names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n if (is.null(signaling)) {\n message(\"Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\")\n } else {\n message(\"Signaling role analysis on the cell-cell communication network from user's input\")\n signaling <- signaling[signaling %in% object@netP$pathways]\n if (length(signaling) == 0) {\n stop('There is no significant communication for the input signaling. All the significant signaling are shown in `object@netP$pathways`')\n }\n outgoing <- outgoing[ , signaling, drop = FALSE]\n incoming <- incoming[ , signaling, drop = FALSE]\n }\n outgoing.cells <- rowSums(outgoing)\n incoming.cells <- rowSums(incoming)\n\n num.link <- aggregateNet(object, signaling = signaling, return.object = FALSE, remove.isolate = FALSE)$count\n num.link <- rowSums(num.link) + colSums(num.link)-diag(num.link)\n df <- data.frame(x = outgoing.cells, y = incoming.cells, labels = names(incoming.cells),\n Count = num.link)\n df$labels <- factor(df$labels, levels = names(incoming.cells))\n if (!is.null(group)) {\n df$Group <- group\n }\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(object@idents))\n }\n if (!is.null(group)) {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Count, colour = labels, fill = labels, shape = Group))\n } else {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Count, colour = labels, fill = labels))\n }\n\n gg <- gg + CellChat_theme_opts() +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\"))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE) + guides(colour=\"none\")\n # gg <- gg + scale_colour_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(colour=\"none\")\n # gg <- gg + scale_shape_manual(values = point.shape[1:length(prob)])\n if (!is.null(group)) {\n gg <- gg + scale_shape_manual(values = point.shape[1:length(unique(df$Group))])\n }\n if (is.null(weight.MinMax)) {\n gg <- gg + scale_size_continuous(range = dot.size)\n } else {\n gg <- gg + scale_size_continuous(limits = weight.MinMax, range = dot.size)\n }\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = labels), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n\n#' 2D visualization of differential signaling roles (dominant senders (sources) or receivers (targets) ) of each cell group when comparing mutiple datasets\n#'\n#' @description\n#' This scatter plot shows the differential signaling roles (dominant senders (sources) or receivers (targets) in a 2D space.\n#'\n#' x-axis and y-axis are respectively the differential outgoing or incoming communication probability associated with each cell group.\n#' Dot colors indicate different cell groups. Dot shapes indicate different categories of cell groups if `group`` is defined.\n#'\n#' Positive values indicate the increase in the second dataset while negative values indicate the increase in the first dataset\n#'\n#' @param object A merged CellChat object of a list of CellChat objects\n#' @param color.use defining the color for each cell group\n#' @param comparison an index vector giving the two datasets for comparison\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param signaling.exclude signaling pathways to exclude\n#' @param idents.exclude cell groups to exclude. This is useful when zooming into the small changes\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param group a vector to categorize the cell groups, e.g., categorize the cell groups into two major categories: immune cells and fibroblasts\n#' @param point.shape point shape when group is not NULL\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., Outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., Incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_diff_signalingRole_scatter <- function(object, color.use = NULL, comparison = c(1,2), signaling = NULL, signaling.exclude = NULL, idents.exclude = NULL, slot.name = \"netP\", group = NULL, dot.size = 2.5, point.shape = c(21, 22, 24, 23, 25, 8, 3), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\", xlabel = \"Outgoing interaction strength\", ylabel = \"Incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (is.list(object)) {\n object <- mergeCellChat(object, add.names = names(object))\n }\n if (!is.list(object@net[[1]])) {\n stop(\"This function cannot be applied to a single cellchat object from one dataset!\")\n }\n\n dataset.name <- names(object@net)\n message(paste0(\"Visualizing differential outgoing and incoming signaling changes from \", dataset.name[comparison[1]], \" to \", dataset.name[comparison[2]]))\n title <- paste0(\"Signaling changes \", \" (\", dataset.name[comparison[1]], \" vs. \", dataset.name[comparison[2]], \")\")\n\n cell.levels <- levels(object@idents$joint)\n if (is.null(xlabel) | is.null(ylabel)) {\n xlabel = \"Differential outgoing interaction strength\"\n ylabel = \"Differential incoming interaction strength\"\n }\n if (is.null(signaling)) {\n signaling <- union(object@netP[[comparison[1]]]$pathways, object@netP[[comparison[2]]]$pathways)\n }\n if (!is.null(signaling.exclude)) {\n signaling <- setdiff(signaling, signaling.exclude)\n }\n\n mat.all.merged <- list()\n for (ii in 1:length(comparison)) {\n if (length(slot(object, slot.name)[[comparison[ii]]]$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores for each dataset seperately! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n\n centr <- slot(object, slot.name)[[comparison[ii]]]$centr\n outgoing <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n incoming <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n dimnames(outgoing) <- list(cell.levels, names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n mat.out <- t(outgoing)\n mat.in <- t(incoming)\n\n mat.all <- array(0, dim = c(length(signaling),ncol(mat.out),2))\n mat.t <-list(mat.out, mat.in)\n for (i in 1:length(comparison)) {\n mat = mat.t[[i]]\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n mat.all[,,i] = mat\n }\n dimnames(mat.all) <- list(dimnames(mat)[[1]], dimnames(mat)[[2]], c(\"outgoing\", \"incoming\"))\n mat.all.merged[[ii]] <- mat.all\n\n }\n\n mat.diff <- mat.all.merged[[2]] - mat.all.merged[[1]]\n\n outgoing.diff <- colSums(mat.diff[ , , 1])\n incoming.diff <- colSums(mat.diff[ , , 2])\n\n\n df <- data.frame(x = outgoing.diff, y = incoming.diff, labels = names(incoming.diff))\n df$labels <- factor(df$labels, levels = names(incoming.diff))\n if (!is.null(group)) {\n df$Group <- group\n }\n if (is.null(color.use)) {\n color.use <- scPalette(length(cell.levels))\n }\n if (!is.null(idents.exclude)) {\n df <- df[!(df$labels %in% idents.exclude), ]\n color.use <- color.use[!(cell.levels %in% idents.exclude)]\n df$labels = droplevels(df$labels, exclude = setdiff(levels(df$labels),unique(df$labels)))\n }\n\n if (!is.null(group)) {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = labels, fill = labels, shape = Group), size = dot.size)\n } else {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = labels, fill = labels), size = dot.size)\n }\n\n gg <- gg + CellChat_theme_opts() + theme_linedraw() +theme(panel.grid = element_blank()) +\n geom_hline(yintercept=0,linetype=\"dashed\", color = \"grey50\", size = 0.25) + geom_vline(xintercept=0, linetype=\"dashed\", color = \"grey50\",size = 0.25) +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\", hjust = 0.5))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE) + guides(colour=\"none\")\n if (!is.null(group)) {\n gg <- gg + scale_shape_manual(values = point.shape[1:length(unique(df$Group))])\n }\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = labels), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n\n#' 2D visualization of differential outgoing and incoming signaling associated with one cell group\n#'\n#' @description\n#' Positive values indicate the increase in the second dataset while negative values indicate the increase in the first dataset\n#'\n#'\n#' @param object A merged CellChat object of a list of CellChat objects\n#' @param idents.use the cell group names of interest. Should be one of `levels(object@idents$joint)`\n#' @param color.use a vector with three elements: the first is for coloring shared pathways, the second is for specific pathways in the first dataset, and the third is for specific pathways in the second dataset\n#' @param comparison an index vector giving the two datasets for comparison\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param signaling.label a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param signaling.exclude signaling pathways to exclude when plotting\n#' @param xlims,ylims set x-Axis and y-Axis Limits for zoom into the plot. e.g., xlims = c(-0.05, 0.1), ylims = c(-0.01, 0.035)\n#' @param slot.name the slot name of object\n#' @param point.shape point shape\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., Outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., Incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @importFrom plyr mapvalues\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_signalingChanges_scatter <- function(object, idents.use, color.use = c(\"grey10\", \"#F8766D\", \"#00BFC4\"), comparison = c(1,2), signaling = NULL, signaling.label = NULL, top.label = 1, signaling.exclude = NULL, xlims = NULL, ylims = NULL,slot.name = \"netP\", dot.size = 2.5, point.shape = c(21, 22, 24, 23), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\", xlabel = \"Differential outgoing interaction strength\", ylabel = \"Differential incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (is.list(object)) {\n object <- mergeCellChat(object, add.names = names(object))\n }\n if (is.list(object@net[[1]])) {\n dataset.name <- names(object@net)\n message(paste0(\"Visualizing differential outgoing and incoming signaling changes from \", dataset.name[comparison[1]], \" to \", dataset.name[comparison[2]]))\n title <- paste0(\"Signaling changes of \", idents.use, \" (\", dataset.name[comparison[1]], \" vs. \", dataset.name[comparison[2]], \")\")\n\n cell.levels <- levels(object@idents$joint)\n if (is.null(xlabel) | is.null(ylabel)) {\n xlabel = \"Differential outgoing interaction strength\"\n ylabel = \"Differential incoming interaction strength\"\n }\n\n } else {\n message(\"Visualizing outgoing and incoming signaling on a single object \\n\")\n title <- paste0(\"Signaling patterns of \", idents.use)\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n cell.levels <- levels(object@idents)\n }\n if (!(idents.use %in% cell.levels)) {\n stop(\"Please check the input cell group names!\")\n }\n if (is.null(signaling)) {\n signaling <- union(object@netP[[comparison[1]]]$pathways, object@netP[[comparison[2]]]$pathways)\n }\n if (!is.null(signaling.exclude)) {\n signaling <- setdiff(signaling, signaling.exclude)\n }\n mat.all.merged <- list()\n for (ii in 1:length(comparison)) {\n if (length(slot(object, slot.name)[[comparison[ii]]]$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores for each dataset seperately! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n centr <- slot(object, slot.name)[[comparison[ii]]]$centr\n outgoing <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n incoming <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n dimnames(outgoing) <- list(cell.levels, names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n mat.out <- t(outgoing)\n mat.in <- t(incoming)\n\n mat.all <- array(0, dim = c(length(signaling),ncol(mat.out),2))\n mat.t <-list(mat.out, mat.in)\n for (i in 1:length(comparison)) {\n mat = mat.t[[i]]\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n mat.all[,,i] = mat\n }\n dimnames(mat.all) <- list(dimnames(mat)[[1]], dimnames(mat)[[2]], c(\"outgoing\", \"incoming\"))\n mat.all.merged[[ii]] <- mat.all\n }\n mat.all.merged.use <- list(mat.all.merged[[1]][,idents.use,], mat.all.merged[[2]][,idents.use,])\n idx.specific <- mat.all.merged.use[[1]] * mat.all.merged.use[[2]]\n mat.sum <- mat.all.merged.use[[2]] + mat.all.merged.use[[1]]\n out.specific.signaling <- rownames(idx.specific)[(mat.sum[,1] != 0) & (idx.specific[,1] == 0)]\n in.specific.signaling <- rownames(idx.specific)[(mat.sum[,2] != 0) & (idx.specific[,2] == 0)]\n\n mat.diff <- mat.all.merged.use[[2]] - mat.all.merged.use[[1]]\n idx <- rowSums(mat.diff) != 0\n mat.diff <- mat.diff[idx, ]\n out.specific.signaling <- rownames(mat.diff) %in% out.specific.signaling\n in.specific.signaling <- rownames(mat.diff) %in% in.specific.signaling\n out.in.specific.signaling <- as.logical(out.specific.signaling * in.specific.signaling)\n specificity.out.in <- matrix(0, nrow = nrow(mat.diff), ncol = 1)\n specificity.out.in[out.in.specific.signaling] <- 2 # both outgoing and incoming specific to one condition\n specificity.out.in[setdiff(which(out.specific.signaling), which(out.in.specific.signaling))] <- 1 # only outgoing specific to one condition\n specificity.out.in[setdiff(which(in.specific.signaling), which(out.in.specific.signaling))] <- -1 # only incoming specific to one condition\n\n\n df <- as.data.frame(mat.diff)\n df$specificity.out.in <- specificity.out.in\n df$specificity = 0\n df$specificity[(specificity.out.in != 0) & (rowSums(mat.diff >= 0) ==2)] = 1 # specific to dataset 2\n df$specificity[(specificity.out.in != 0) & (rowSums(mat.diff <= 0) ==2)] = -1 # specific to dataset 1\n\n # change number to char\n out.in.category <- c(\"Shared\", \"Incoming specific\", \"Outgoing specific\", \"Incoming & Outgoing specific\")\n specificity.category <- c(\"Shared\", paste0(dataset.name[comparison[1]],\" specific\"), paste0(dataset.name[comparison[2]],\" specific\"))\n df$specificity.out.in <- plyr::mapvalues(df$specificity.out.in, from = c(0,-1,1,2),to = out.in.category)\n df$specificity.out.in <- factor(df$specificity.out.in, levels = out.in.category)\n df$specificity <- plyr::mapvalues(df$specificity, from = c(0,-1,1),to = specificity.category)\n df$specificity <- factor(df$specificity, levels = specificity.category)\n\n point.shape.use <- point.shape[out.in.category %in% unique(df$specificity.out.in)]\n df$specificity.out.in = droplevels(df$specificity.out.in, exclude = setdiff(out.in.category,unique(df$specificity.out.in)))\n\n color.use <- color.use[specificity.category %in% unique(df$specificity)]\n df$specificity = droplevels(df$specificity, exclude = setdiff(specificity.category,unique(df$specificity)))\n\n df$labels <- rownames(df)\n gg <- ggplot(data = df, aes(outgoing, incoming)) +\n geom_point(aes(colour = specificity, fill = specificity, shape = specificity.out.in), size = dot.size)\n gg <- gg + theme_linedraw() +theme(panel.grid = element_blank()) +\n geom_hline(yintercept=0,linetype=\"dashed\", color = \"grey50\", size = 0.25) + geom_vline(xintercept=0, linetype=\"dashed\", color = \"grey50\",size = 0.25) +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, hjust = 0.5, face=\"plain\"))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n gg <- gg + scale_shape_manual(values = point.shape.use)\n gg <- gg + theme(legend.title = element_blank())\n if (!is.null(xlims)) {\n gg <- gg + xlim(xlims)\n }\n if (!is.null(ylims)) {\n gg <- gg + ylim(ylims)\n }\n\n if (do.label) {\n if (is.null(signaling.label)) {\n thresh <- stats::quantile(abs(as.matrix(df[,1:2])), probs = 1-top.label)\n idx = abs(df[,1]) > thresh | abs(df[,2]) > thresh\n data.label <- df[idx,]\n } else {\n data.label <- df[rownames(df) %in% signaling.label, ]\n }\n\n gg <- gg + ggrepel::geom_text_repel(data = data.label, mapping = aes(label = labels, colour = specificity), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n#' Heatmap showing the contribution of signals (signaling pathways or ligand-receptor pairs) to cell groups in terms of outgoing or incoming signaling\n#'\n#' In this heatmap, colobar represents the relative signaling strength of a signaling pathway across cell groups (NB: values are row-scaled).\n#' The top colored bar plot shows the total signaling strength of a cell group by summarizing all signaling pathways displayed in the heatmap.\n#' The right grey bar plot shows the total signaling strength of a signaling pathway by summarizing all cell groups displayed in the heatmap.\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the names of signaling networks of interest\n#' @param pattern this parameter can be set as \"outgoing\", \"incoming\" or \"all\". When pattern = \"all\", CellChat aggregates the outgoing and incoming signaling strength together;\n#' @param slot.name the slot name of object that is used to examine the signaling patterns at the level of signaling pathways (slot.name = \"netP\") or ligand-receptor pairs (slot.name = \"net\");\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param title title name\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation anno_barplot rowAnnotation\n#' @importFrom stats setNames\n#'\n#' @return\n#' @export\n#'\nnetAnalysis_signalingRole_heatmap <- function(object, signaling = NULL, pattern = c(\"outgoing\", \"incoming\",\"all\"), slot.name = \"netP\",\n color.use = NULL, color.heatmap = \"BuGn\",\n title = NULL, width = 10, height = 8, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE){\n pattern <- match.arg(pattern)\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n centr <- slot(object, slot.name)$centr\n outgoing <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n incoming <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n dimnames(outgoing) <- list(levels(object@idents), names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]]$outdeg\n incoming[,i] <- centr[[i]]$indeg\n }\n if (pattern == \"outgoing\") {\n mat <- t(outgoing)\n legend.name <- \"Outgoing\"\n } else if (pattern == \"incoming\") {\n mat <- t(incoming)\n legend.name <- \"Incoming\"\n } else if (pattern == \"all\") {\n mat <- t(outgoing+ incoming)\n legend.name <- \"Overall\"\n }\n if (is.null(title)) {\n title <- paste0(legend.name, \" signaling patterns\")\n } else {\n title <- paste0(paste0(legend.name, \" signaling patterns\"), \" - \",title)\n }\n\n if (!is.null(signaling)) {\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n }\n mat.ori <- mat\n mat <- sweep(mat, 1L, apply(mat, 1, max), '/', check.margin = FALSE)\n mat[mat == 0] <- NA\n\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(colnames(mat)))\n }\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n\n df<- data.frame(group = colnames(mat)); rownames(df) <- colnames(mat)\n names(color.use) <- colnames(mat)\n col_annotation <- HeatmapAnnotation(df = df, col = list(group = color.use),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n ha2 = HeatmapAnnotation(Strength = anno_barplot(colSums(mat.ori), border = FALSE,gp = gpar(fill = color.use, col=color.use)), show_annotation_name = FALSE)\n\n pSum <- rowSums(mat.ori)\n pSum.original <- pSum\n pSum <- -1/log(pSum)\n pSum[is.na(pSum)] <- 0\n idx1 <- which(is.infinite(pSum) | pSum < 0)\n if (length(idx1) > 0) {\n values.assign <- seq(max(pSum)*1.1, max(pSum)*1.5, length.out = length(idx1))\n position <- sort(pSum.original[idx1], index.return = TRUE)$ix\n pSum[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n\n ha1 = rowAnnotation(Strength = anno_barplot(pSum, border = FALSE), show_annotation_name = FALSE)\n\n if (min(mat, na.rm = T) == max(mat, na.rm = T)) {\n legend.break <- max(mat, na.rm = T)\n } else {\n legend.break <- c(round(min(mat, na.rm = T), digits = 1), round(max(mat, na.rm = T), digits = 1))\n }\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = \"Relative strength\",\n bottom_annotation = col_annotation, top_annotation = ha2, right_annotation = ha1,\n cluster_rows = cluster.rows,cluster_columns = cluster.rows,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = title,column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 90,\n heatmap_legend_param = list(title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = legend.break,\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n # draw(ht1)\n return(ht1)\n}\n\n\n\n#' Mapping the differential expressed genes (DEG) information onto the inferred cell-cell communications\n#'\n#' This function returns a data frame consisting of all the inferred cell-cell communications with mapped DEG information\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for extracting the DEG in `object@var.features[[features.name]]`\n#' @param variable.all variable.all = TRUE will compute the c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\") for a ligand/receptor complex using the mean value of its all subunits, that is requiring all subunits of the complex are differential expressed;\n#' variable.all = FALSE will compute the minimum value of \"pvalues\" and maximum value of c(\"logFC\", \"pct.1\", \"pct.2\") among the subunits, that is only requiring that any one of the subunits of the complex is differential expressed.\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom dplyr select\n#'\n#' @return a data frame of the inferred cell-cell communications, consisting of source, target, interaction_name, pathway_name, prob and other CellChatDB information as well as DEG information\n#'\n#' @export\n#'\nnetMappingDEG <- function(object, features.name, variable.all = TRUE, thresh = 0.05) {\n features.name <- paste0(features.name, \".info\")\n if (!(features.name %in% names(object@var.features))) {\n stop(\"The input features.name does not exist in `names(object@var.features)`. Please first run `identifyOverExpressedGenes`! \")\n }\n DEG <- object@var.features[[features.name]]\n geneInfo <- object@DB$geneInfo\n complex_input <- object@DB$complex\n\n df.net <- subsetCommunication(object, thresh = thresh)\n if (!is.data.frame(df.net)) {\n net <- data.frame()\n for (ii in 1:length(df.net)) {\n df.net[[ii]]$datasets <- names(df.net)[ii]\n net <- rbind(net, df.net[[ii]])\n }\n } else {\n net <- df.net\n }\n net$source.ligand <- paste0(net$source,\".\", net$ligand)\n net$target.receptor <- paste0(net$target,\".\", net$receptor)\n\n DEG$clusters.features <- paste0(DEG$clusters,\".\", DEG$features)\n\n net <- cbind(net, data.frame(ligand.pvalues = NA, ligand.logFC = NA, ligand.pct.1 = NA, ligand.pct.2 = NA,\n receptor.pvalues = NA, receptor.logFC = NA, receptor.pct.1 = NA, receptor.pct.2 = NA))\n # compute values for ligand\n idx1.ligand <- net$ligand %in% geneInfo$Symbol\n idx2.ligand <- which((net$ligand %in% geneInfo$Symbol) == \"FALSE\")\n idx.pos <- match(net$source.ligand, DEG$clusters.features)\n idx1.source.ligand <- which(!is.na(idx.pos))\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n idx2.source.ligand <- which(idx1.ligand & !(net$source.ligand %in% DEG$clusters.features))\n net[idx1.source.ligand, c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")] <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n\n if (length(idx2.ligand) > 0) {\n net.temp.all <- data.frame()\n for (i in 1:length(idx2.ligand)) {\n complex <- net$ligand[idx2.ligand[i]]\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n\n source.ligand.complex <- paste0(net$source[idx2.ligand[i]],\".\", complexsubunitsV)\n idx.pos <- match(source.ligand.complex, DEG$clusters.features)\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n if (length(idx1.clusters.features) > 0) {\n net.temp <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\"), drop = FALSE]\n if (variable.all == TRUE) {\n net.temp <- colMeans(net.temp, na.rm = TRUE)\n } else {\n net.temp <- c(min(net.temp$pvalues), apply(net.temp[, 2:ncol(net.temp), drop = FALSE], 2, function(x) max(x, na.rm = TRUE)))\n names(net.temp)[1] <- \"pvalues\"\n }\n net.temp <- as.data.frame(t(net.temp))\n colnames(net.temp) <- c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")\n } else {\n net.temp <- data.frame(ligand.pvalues = NA, ligand.logFC = NA, ligand.pct.1 = NA, ligand.pct.2 = NA)\n }\n net.temp.all <- rbind(net.temp.all, net.temp)\n }\n net[idx2.ligand, c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")] <- net.temp.all\n }\n\n # compute values for receptor\n idx1.receptor <- net$receptor %in% geneInfo$Symbol\n idx2.receptor <- which((net$receptor %in% geneInfo$Symbol) == \"FALSE\")\n idx.pos <- match(net$target.receptor, DEG$clusters.features)\n idx1.target.receptor <- which(!is.na(idx.pos))\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n net[idx1.target.receptor, c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")] <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n\n if (length(idx2.receptor) > 0) {\n net.temp.all <- data.frame()\n for (i in 1:length(idx2.receptor)) {\n complex <- net$receptor[idx2.receptor[i]]\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n\n target.receptor.complex <- paste0(net$target[idx2.receptor[i]],\".\", complexsubunitsV)\n idx.pos <- match(target.receptor.complex, DEG$clusters.features)\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n if (length(idx1.clusters.features) > 0) {\n net.temp <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n if (variable.all == TRUE) {\n net.temp <- colMeans(net.temp, na.rm = TRUE)\n } else {\n net.temp <- c(min(net.temp$pvalues, na.rm = TRUE), apply(net.temp[, 2:ncol(net.temp), drop = FALSE], 2, function(x) max(x, na.rm = TRUE)))\n names(net.temp)[1] <- \"pvalues\"\n }\n net.temp <- as.data.frame(t(net.temp))\n colnames(net.temp) <- c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")\n } else {\n net.temp <- data.frame(receptor.pvalues = NA, receptor.logFC = NA, receptor.pct.1 = NA, receptor.pct.2 = NA)\n }\n net.temp.all <- rbind(net.temp.all, net.temp)\n }\n net[idx2.receptor, c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")] <- net.temp.all\n }\n # net <- dplyr::select[net, -c(\"source.ligand\", \"target.receptor\")]\n return(net)\n}\n\n\n#' Compute and visualize the enrichment score of ligand-receptor pairs in one condition compared to another condition\n#'\n#' @param df a dataframe\n#' @param measure compute the enrichment score in terms of \"ligand\", \"signaling\",or \"LR-pair\"\n#' @param color.use defining the color for each group of datasets\n#' @param color.name the color names in RColorBrewer::brewer.pal\n#' @param n.color the number of colors\n#' @param species define the species as one of the c('mouse','human') to extract the CellChatDB; For other species, users need to provide a ligand-receptor database `db`\n#' @param db a customized ligand-receptor database `db`\n#' @param variable.both variable.both = TRUE will require that both ligand and receptor from one pair are over-expressed;\n#' variable.both = FALSE will only require that either ligand or receptor from one pair is over-expressed.\n#' @param scale A vector of length 2 indicating the range of the size of the words.\n#' @param min.freq words with frequency below min.freq will not be plotted\n#' @param max.words Maximum number of words to be plotted. least frequent terms dropped\n#' @param random.order plot words in random order. If false, they will be plotted in decreasing frequency\n#' @param rot.per \tproportion words with 90 degree rotation\n#' @param return.data whether return the data frame for plotting wordcloud\n#' @param seed set a seed\n#' @param ... Other parameters passing to wordcloud::wordcloud\n#' @import dplyr\n#' @return A ggplot object\n#' @export\n#'\ncomputeEnrichmentScore <- function(df, measure = c(\"ligand\", \"signaling\",\"LR-pair\"), variable.both = TRUE, species = c('mouse','human'), db = NULL, color.use = NULL, color.name = \"Dark2\", n.color = 8,\n scale=c(4,.8), min.freq = 0, max.words = 200, random.order = FALSE, rot.per = 0,return.data = FALSE,seed = 1,...) {\n measure <- match.arg(measure)\n species <- match.arg(species)\n LRpairs <- as.character(unique(df$interaction_name))\n ES <- vector(length = length(LRpairs))\n for (i in 1:length(LRpairs)) {\n df.i <- subset(df, interaction_name == LRpairs[i])\n idx = which(rowSums(is.na(df.i)) > 0)\n if (variable.both & (length(idx) > 0)) {\n df.i <- df.i[-idx, ,drop = FALSE]\n }\n ES[i] = mean(abs(df.i$ligand.logFC) * abs(df.i$receptor.logFC) *abs(df.i$ligand.pct.2-df.i$ligand.pct.1)*abs(df.i$receptor.pct.2-df.i$receptor.pct.1), na.rm = TRUE)\n }\n idx.na <- which(is.na(ES))\n if (length(idx.na) > 0) {\n ES <- ES[-idx.na]\n LRpairs <- LRpairs[-idx.na]\n }\n\n if (length(ES) == 0) {\n stop(\"No enriched signaling! Please adjust the parameters for selecting differential expressed signaling!\")\n }\n if (is.null(db)) {\n if (species == \"mouse\") {\n CellChatDB <- CellChatDB.mouse\n } else if (species == 'human') {\n CellChatDB <- CellChatDB.human\n } else {\n stop(\"Only mouse and human are supported currently. Please provide a `db` instead! \")\n }\n } else {\n CellChatDB <- db\n }\n df.es <- CellChatDB$interaction[LRpairs, c(\"ligand\",'receptor','pathway_name')]\n df.es$score <- ES\n # summarize the enrichment score\n df.es.ensemble <- df.es %>% group_by(ligand) %>% summarize(total = sum(score)) # avg = mean(score),\n\n set.seed(seed)\n if (is.null(color.use)) {\n color.use <- RColorBrewer::brewer.pal(n.color, color.name)\n }\n\n wordcloud::wordcloud(words = df.es.ensemble$ligand, freq = df.es.ensemble$total, min.freq = min.freq, max.words = max.words,scale=scale,\n random.order = random.order, rot.per = rot.per, colors = color.use,...)\n if (return.data) {\n return(df.es.ensemble)\n }\n}\n\n\n#' Find the enriched signaling according to the genes (e.g.DEGs) and cell groups of interest\n#'\n#' @param object CellChat object\n#' @param features a vector giving the genes of interest\n#' @param idents a vector giving the names of cell groups of interest. If idents = NULL, it returns signaling according to the input features.\n#' @param pattern \"both\", \"outgoing\" or \"incoming\"\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @return a dataframe of the cell-cell communication associated with the input features.\n#' @export\n#' @examples\n#'\\dontrun{\n#' # find all the significant outgoing signaling according to the features and cell groups of interest\n#' df <- findEnrichedSignaling(object, features = c(\"CCL19\", \"CXCL12\"), idents = c(\"Inflam. FIB\", \"COL11A1+ FIB\"), pattern =\"outgoing\")\n#'}\nfindEnrichedSignaling <- function(object, features, idents = NULL, pattern = c(\"both\",\"outgoing\",\"incoming\"), thresh = 0.05) {\n pattern <- match.arg(pattern)\n df.net <- subsetCommunication(object, thresh = thresh)\n if (!is.null(idents)) {\n if (pattern == \"both\") {\n idx <- (df.net$source %in% idents) | (df.net$target %in% idents)\n } else if (pattern == \"outgoing\") {\n idx <- df.net$source %in% idents\n } else if (pattern == \"incoming\"){\n idx <- df.net$target %in% idents\n }\n idx.feature <- (df.net$ligand %in% features) | (df.net$receptor %in% features)\n df.net.sub <- df.net[idx & idx.feature, , drop = FALSE]\n } else {\n if (pattern == \"both\") {\n idx.feature <- (df.net$ligand %in% features) | (df.net$receptor %in% features)\n } else if (pattern == \"outgoing\") {\n idx.feature <- (df.net$ligand %in% features)\n } else if (pattern == \"incoming\"){\n idx.feature <- (df.net$receptor %in% features)\n }\n df.net.sub <- df.net[idx.feature, , drop = FALSE]\n }\n return(df.net.sub)\n}\n\n"], ["/CellChat/R/app.R", "#' Generate a Shiny App for interactive exploration of CellChat's outputs\n#'\n#' @param object CellChat object\n#' @param ... Other parameters of `shinyApp` function from shiny R package\n#' @return A Shiny app object on the basis of one CellChat object\n#' @export\n#' @importFrom stringr str_split_1\n# #' @importFrom plotly subplot plot_ly ggplotly add_markers highlight highlight_key plotlyOutput layout\n# #' @importFrom bsicons bs_icon\n#' @import shiny bslib\n#'\nrunCellChatApp <- function(object,...) {\n # ##########################################################################\n # set some global options\n # ##########################################################################\n options(stringsAsFactors = FALSE)\n\n # ##########################################################################\n # some useful elements for ui.R\n # ##########################################################################\n choices_cell_groups <-levels(object@idents)\n names(choices_cell_groups) <- levels(object@idents)\n\n choices_pathways <- object@netP$pathways\n names(choices_pathways) <- object@netP$pathways\n\n # all signaling gene names\n choices_gene_names <- CellChat::extractGene(object@DB)\n # all ligand-receptor pair names\n #choices_pairLR_use <- object@DB$interaction$interaction_name\n if (\"LRs\" %in% names(object@net)) {\n choices_pairLR_use <- object@net$LRs\n } else {\n thresh = 0.05\n prob <- object@net$prob\n prob[object@net$pval > thresh] <- 0\n LR <- dimnames(prob)[[3]]\n LR.sig <- LR[apply(prob, 3, sum) != 0]\n choices_pairLR_use <- LR.sig\n }\n\n\n # Palettes (sequential)\n choices_palettes_sequential <- stringr::str_split_1(\"Blues, BuGn, BuPu, GnBu, Greens, Greys, Oranges, OrRd, PuBu, PuBuGn, PuRd, Purples, RdPu, Reds, YlGn, YlGnBu, YlOrBr, YlOrRd\",\", \")\n names(choices_palettes_sequential) <- choices_palettes_sequential\n choices_palettes_diverging <- stringr::str_split_1(\"BrBG, PiYG, PRGn, PuOr, RdBu, RdGy, RdYlBu, RdYlGn, Spectral\",\", \")\n names(choices_palettes_diverging) <- choices_palettes_diverging\n\n # ##########################################################################\n # interactive visualization\n # ##########################################################################\n\n # interactive Heatmap\n # [Colors (ggplot2)](http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/)\n plotly_netVisual_heatmap <- function(obj_heatmap,palette.heatmap,direction.heatmap=1) {\n gg_heatmap <- obj_heatmap@matrix %>%\n as.data.frame() %>%\n mutate(row = rownames(.)) %>%\n tidyr::pivot_longer(\n data = .,\n cols = colnames(.)[-length(colnames(.))],\n names_to = \"column\",\n values_to = \"value\"\n ) %>%\n ggplot() +\n geom_tile(aes(row, column, fill = value),\n width = 0.95,\n height = 0.95) +\n # guides(fill=guide_legend(title=obj_heatmap@row_title))+\n labs(title = '',\n x = '',\n y = obj_heatmap@row_title,\n # I can't set the direction of the legend title, I thick it's a bug\n # fill = obj_heatmap@column_title,\n ) +\n scale_fill_distiller(\n palette = palette.heatmap,\n na.value = 'white',\n direction = direction.heatmap,\n ) +\n theme_minimal()+\n theme(axis.title.y = element_text(size = 14))\n\n # ggplot transpose the matrix, so we need use colSums to calc the 'rowSums'\n # of the matrix\n gg_right <- obj_heatmap@matrix %>%\n colSums(abs(.)) %>%\n tibble(row_sum = ., sources_name = names(.)) %>%\n ggplot() +\n geom_bar(aes(x = sources_name, y = row_sum, fill = sources_name),\n stat = 'identity') +\n labs(title = '',\n x = '',\n y = '',) +\n guides(fill = FALSE) +\n scale_fill_brewer(palette = \"Set1\", direction = 1) +\n theme_minimal() +\n coord_flip()\n\n gg_top <- obj_heatmap@matrix %>%\n rowSums(abs(.)) %>%\n tibble(col_sum = ., sources_name = names(.)) %>%\n ggplot() +\n # use fill to set the columns' colors\n geom_bar(aes(x = sources_name, y = col_sum, fill = sources_name),\n stat = 'identity') +\n labs(title = obj_heatmap@column_title,\n x = '',\n y = '',) +\n guides(fill = FALSE)+\n scale_fill_brewer(palette = \"Set1\", direction = 1) +\n # theme() function should be used behind the theme_*()\n theme_minimal()+\n theme(plot.title = element_text(hjust = 0.5,size = 14))\n\n return(plotly::subplot(\n gg_top,\n plotly::plotly_empty(),\n gg_heatmap,\n gg_right,\n nrows = 2,\n heights = c(0.2, 0.8),\n widths = c(0.8, 0.2),\n margin = 0,\n shareX = TRUE,\n shareY = TRUE,\n titleX = TRUE,\n titleY = TRUE\n )\n )\n }\n\n # interactive DimPlot\n plotly_DimPlot <- function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n reduction = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1)\n {\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[, group.by]\n labels <- factor(labels)\n }\n if (length(names(object@dr)) == 0) {\n stop(\"Please check `addReduction` to add a new reduced space into `object@dr`. \\n\")\n }\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please specify the dimensionality reduction to use. \\n\"))\n }\n }\n coordinates <- as.data.frame(coords)\n samples <- object@meta$samples\n if (ncol(coordinates) >= 2) {\n coordinates <- coordinates[, c(1,2)]\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n # temp_coordinates = coordinates\n # coordinates[,1] = temp_coordinates[,2]\n # coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n\n\n\n cells.level <- levels(labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n if (is.null(sources.use) & is.null(targets.use)) {\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n }\n else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use,\n \"Others\"))\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use,\n targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n # print(color.use)->return a color vector\n coordinates$cell_labels <- labels\n\n py <- plotly::highlight_key(coordinates,~cell_labels) %>%\n plotly::plot_ly(x = ~x_cent, y = ~y_cent,marker = list(size = point.size)) %>%\n plotly::add_markers(color=~cell_labels,alpha=alpha,colors=color.use) %>%\n plotly::layout(\n title = title.name,\n yaxis = list(\n title = \"\",\n #autorange = \"reversed\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n ),\n xaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n )\n ) %>%\n plotly::highlight(on = \"plotly_click\",\n off = \"plotly_relayout\")\n\n return(py)\n }\n\n # interactive FeaturePlot\n # https://plotly.com/r/subplots/\n plotly_FeaturePlot <- function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n reduction = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE){\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(\"Please make sure `object@dr` contains a low-dimensional space of the data and specify the dimensionality reduction to use.\")\n }\n }\n\n samples <- object@meta$samples\n cell_labels <- object@idents\n data <- as.matrix(object@data)\n meta <- object@meta\n coords <- as.data.frame(coords)\n if (ncol(coords) >= 2) {\n coords <- coords[, c(1,2)]\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n\n # add idents info\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = -1))(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n }\n else {\n colormap <- color.heatmap\n }\n if (is.null(features) &\n is.null(signaling) & is.null(pairLR.use)) {\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)) {\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)) {\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)) {\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n df <- data.frame(x = coords[, 1], y = coords[, 2],\n cell_labels = cell_labels)\n\n\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n geneLR.return = TRUE,\n enriched.only = enriched.only,\n thresh = thresh\n )\n feature.use <- res$geneLR\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex,\n object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex,\n object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n }\n else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) >\n 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n }\n else if (length(intersect(feature.use, colnames(meta))) >\n 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[, feature.use, drop = FALSE])\n }\n else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \", cutoff, \"to the values...\",\n \"\\n\")\n data.use[data.use <= cutoff] <- 0\n }\n\n\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 0.95) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_colour_gradientn(\n colours = colormap,\n guide = guide_colorbar(\n title = NULL,\n ticks = T,\n label = T,\n barwidth = 0.5\n ),\n na.value = \"grey90\"\n ) +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + ggtitle(feature.name) +\n theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n # g <- g + coord_fixed() +\n # scale_y_reverse()\n\n gg[[i]] <- g %>% plotly::ggplotly(height = 400)\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n # print(annotations_pos)\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',annotations = annotations)\n }\n else {\n gg <- plotly::ggplotly(gg[[1]])\n }\n }\n else {\n # do.binary\n set_individual_legend <- function(plt) {\n # plt is a plotly plot obj\n plt_build <- plotly::plotly_build(plt)\n\n # get the num of traces\n len_legend <- length(plt_build$x$data)\n\n for (i in 1:len_legend) {\n # set legendgroup\n plt_build$x$data[[i]]$legendgroup <- feature.name\n # set legendtitle\n plt_build$x$data[[i]]$legendgrouptitle <- list(text=feature.name,font=list(size=12))\n }\n return(plt_build)\n }\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n enriched.only = enriched.only,\n thresh = thresh\n )\n LR.pair <- object@LR$LRsig[res$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL\n rownames(dataR) <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \")\n }\n gg <- vector(\"list\", numFeature)\n\n # set subplot title pos\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 1) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i,] > cutoff\n idx2 = dataR[i,] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\", ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i], geneR[i],\n \"Both\", \"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i], geneR[i], \"Both\",\n \"None\")\n if (length(setdiff(levels(group), unique(group))) >\n 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group),\n unique(group)))\n }\n df$feature.data <- group\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + guides(color = guide_legend(override.aes = list(size = legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n # g <- g + coord_fixed() +\n # scale_y_reverse()\n\n # cat(feature.name)\n gg[[i]] <- g %>% plotly::ggplotly(\n type = 'scatter',\n mode='markers+text',\n ) %>% set_individual_legend()\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',\n annotations = annotations,\n legend = list(tracegroupgap = 10,title=list(text=''))\n )\n }\n else {\n gg <- plotly::ggplotly(gg[[1]],\n type = 'scatter',\n mode = 'markers') %>%\n plotly::layout(legend = list(title = list(text = '')))\n }\n }\n return(gg)\n }\n\n # interactive spatialDimPlot\n plotly_spatialDimPlot <- function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1)\n {\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[, group.by]\n labels <- factor(labels)\n }\n\n coordinates <- as.data.frame(object@images$coordinates)\n samples <- object@meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n\n\n cells.level <- levels(labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n if (is.null(sources.use) & is.null(targets.use)) {\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n }\n else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use,\n \"Others\"))\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use,\n targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n # print(color.use)->return a color vector\n coordinates$cell_labels <- labels\n\n py <- plotly::highlight_key(coordinates,~cell_labels) %>%\n plotly::plot_ly(x = ~x_cent, y = ~y_cent,marker = list(size = point.size)) %>%\n plotly::add_markers(color=~cell_labels,alpha=alpha,colors=color.use) %>%\n plotly::layout(\n title = title.name,\n yaxis = list(\n autorange = \"reversed\",\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n showline = FALSE\n ),\n xaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n showline = FALSE\n )\n ) %>%\n plotly::highlight(on = \"plotly_click\",\n off = \"plotly_relayout\")\n\n return(py)\n }\n\n # interactive spatialFeaturePlot\n # https://plotly.com/r/subplots/\n plotly_spatialFeaturePlot <- function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE){\n coords <- as.data.frame(object@images$coordinates)\n samples <- object@meta$samples\n cell_labels <- object@idents\n data <- as.matrix(object@data)\n meta <- object@meta\n\n if (ncol(coords) == 2) {\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coords = coords\n coords[,1] = temp_coords[,2]\n coords[,2] = temp_coords[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n # add idents info\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = -1))(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n }\n else {\n colormap <- color.heatmap\n }\n if (is.null(features) &\n is.null(signaling) & is.null(pairLR.use)) {\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)) {\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)) {\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)) {\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n df <- data.frame(x = coords[, 1], y = coords[, 2],\n cell_labels = cell_labels)\n\n\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n geneLR.return = TRUE,\n enriched.only = enriched.only,\n thresh = thresh\n )\n feature.use <- res$geneLR\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex,\n object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex,\n object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n }\n else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) >\n 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n }\n else if (length(intersect(feature.use, colnames(meta))) >\n 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[, feature.use, drop = FALSE])\n }\n else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \", cutoff, \"to the values...\",\n \"\\n\")\n data.use[data.use <= cutoff] <- 0\n }\n\n\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 0.95) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_colour_gradientn(\n colours = colormap,\n guide = guide_colorbar(\n title = NULL,\n ticks = T,\n label = T,\n barwidth = 0.5\n ),\n na.value = \"grey90\"\n ) +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + ggtitle(feature.name) +\n theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n g <- g + coord_fixed() +\n scale_y_reverse()\n\n gg[[i]] <- g %>% plotly::ggplotly(height = 400)\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n # print(annotations_pos)\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',annotations = annotations)\n }\n else {\n gg <- plotly::ggplotly(gg[[1]])\n }\n }\n else {\n # do.binary\n set_individual_legend <- function(plt) {\n # plt is a plotly plot obj\n plt_build <- plotly::plotly_build(plt)\n\n # get the num of traces\n len_legend <- length(plt_build$x$data)\n\n for (i in 1:len_legend) {\n # set legendgroup\n plt_build$x$data[[i]]$legendgroup <- feature.name\n # set legendtitle\n plt_build$x$data[[i]]$legendgrouptitle <- list(text=feature.name,font=list(size=12))\n }\n return(plt_build)\n }\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n enriched.only = enriched.only,\n thresh = thresh\n )\n LR.pair <- object@LR$LRsig[res$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL\n rownames(dataR) <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \")\n }\n gg <- vector(\"list\", numFeature)\n\n # set subplot title pos\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 1) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i,] > cutoff\n idx2 = dataR[i,] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\", ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i], geneR[i],\n \"Both\", \"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i], geneR[i], \"Both\",\n \"None\")\n if (length(setdiff(levels(group), unique(group))) >\n 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group),\n unique(group)))\n }\n df$feature.data <- group\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + guides(color = guide_legend(override.aes = list(size = legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n g <- g + coord_fixed() +\n scale_y_reverse()\n\n # cat(feature.name)\n gg[[i]] <- g %>% plotly::ggplotly(\n type = 'scatter',\n mode='markers+text',\n ) %>% set_individual_legend()\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',\n annotations = annotations,\n legend = list(tracegroupgap = 10,title=list(text=''))\n )\n }\n else {\n gg <- plotly::ggplotly(gg[[1]],\n type = 'scatter',\n mode = 'markers') %>%\n plotly::layout(legend = list(title = list(text = '')))\n }\n }\n return(gg)\n }\n\n\n\n # ##########################################################################\n # Shiny App's UI\n # ##########################################################################\n ui <- fluidPage(\n theme = bslib::bs_theme(version = 5),\n # ##########################################################################\n # meta info of the HTML pages\n # ##########################################################################\n tags$head(\n # title\n tags$title(\"Interactive CellChat Explorer\"),\n # icon\n tags$link(rel = \"shortcut icon\", type = \"image/x-icon\", href = \"favicon.ico\"),\n tags$link(rel=\"stylesheet\",href=\"https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css\"),\n ),\n tags$body(\n # ##########################################################################\n # logo and title of the website\n # ##########################################################################\n tags$nav(class=\"navbar navbar-light bg-light\",\n div(class=\"container-fluid justify-content-center\",\n tags$a(\n class=\"navbar-brand\",href=\"http://www.cellchat.org/\",\n img(src=\"https://s2.loli.net/2023/08/08/2qjSoRACDtHByOY.png\",class=\"d-inline\",alt=\"\",height=\"30\"),\n tags$p(\"Interactive CellChat Explorer\",class=\"fs-1 d-inline\")\n )\n\n )),\n # ##########################################################################\n # 1.Basic exploration of spatial-resolved gene expression\n # ##########################################################################\n\n # Visualize cell groups and signaling expression\n h3(tags$i(class=\"bi bi-1-square-fill\"),\n \"Visualize cell groups and signaling expression\",class=\"h3\"),\n bslib::card(\n bslib::card_header(\n h6(tags$i(class=\"bi bi-bookmark\"),\n \"Dim Plot\",class=\"h6\")),\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n sliderInput(\n \"dimplot_point_size\",\n label = \"Point size\",\n min = 3,\n max = 8,\n step = 0.5,\n value = 3\n ),\n sliderInput(\n \"dimplot_alpha\",\n label = \"Alpha\",\n min = 0,\n max = 1,\n step = 0.2,\n value = 1\n ),\n )\n ),\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"DimPlot\",\n width = 664,height = 498)\n )\n\n ),\n\n ),\n\n # gene expression distribution\n # https://shiny.posit.co/r/gallery/widgets/datatables-options/\n # https://shiny.posit.co/r/gallery/widgets/selectize-examples/\n navset_card_tab(\n title = h6(tags$i(class=\"bi bi-bookmark-dash\"),\n \"Feature Plot\",class=\"h6\"),\n sidebar = NULL,\n # content\n nav_panel(\n title = \"use gene names\",\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectizeInput(\n inputId = 'selectize_gene_names',\n label = 'Gene Names',\n choices = NULL,\n multiple = TRUE,\n # options = list(maxItems = 4)\n ),\n numericInput(\n \"nrows_feature_plot1\",\n label = \"nrows\",\n min = 1,\n step = 1,\n value = 1,\n ),\n ),\n\n accordion_panel(\n title = \"Color\",\n icon = tags$i(class=\"bi bi-palette-fill\"),\n selectInput(\n \"direction_feature_plot1\",\n label = \"direction\",\n choices = list(\"1\"=1,\"-1\"=-1),\n selected = 1,\n multiple = F\n ),\n selectInput(\n \"palette_feature_plot1\",\n label = \"palette\",\n choices = c(choices_palettes_diverging,choices_palettes_sequential),\n selected = \"Reds\",\n multiple = F\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n numericInput(\n \"cut.off_feature_plot1\",\n label = \"cut.off\",\n min = 0,\n step = 0.1,\n value = 0,\n ),\n sliderInput(\n \"point.size_feature_plot1\",\n label = \"point.size\",\n min = 0,\n max = 2,\n step = 0.1,\n value = 0.4\n )\n )\n\n ),\n # nav content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"gene_expression_distribution\",width = 664,height = 498),\n ),\n )\n ),\n nav_panel(\n title = \"use L-R pairs\",\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectizeInput(\n inputId = 'selectize_pairLR_use',\n label = 'pairLR_use',\n choices = NULL,\n multiple = T\n ),\n numericInput(\n \"nrows_feature_plot2\",\n label = \"nrows\",\n min = 1,\n step = 1,\n value = 1,\n ),\n checkboxInput(\n \"do.binary_feature_plot\",\n label = \"do.binary\",\n value = TRUE),\n ),\n accordion_panel(\n title = \"Color\",\n icon = tags$i(class=\"bi bi-palette-fill\"),\n selectInput(\n \"direction_feature_plot2\",\n label = \"direction\",\n choices = list(\"1\"=1,\"-1\"=-1),\n selected = 1,\n multiple = F\n ),\n selectInput(\n \"palette_feature_plot2\",\n label = \"palette\",\n choices = c(choices_palettes_diverging,choices_palettes_sequential),\n selected = \"Reds\",\n multiple = F\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n numericInput(\n \"cut.off_feature_plot2\",\n label = \"cut.off\",\n min = 0,\n step = 0.1,\n value = 0,\n ),\n sliderInput(\n \"point.size_feature_plot2\",\n label = \"point.size\",\n min = 0,\n max = 2,\n step = 0.1,\n value = 0.4\n )\n )\n ),\n # nav content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"gene_expression_distribution2\",width = 664,height = 498)\n )\n ),\n )\n ),\n\n # ##########################################################################\n # 2.Examine signaling between cell groups\n # ##########################################################################\n h2(tags$i(class=\"bi bi-2-square-fill\"),\n \"Examine signaling between cell groups\"),\n navset_card_tab(\n title = NULL,\n sidebar = NULL,\n nav_panel(\"Heatmap\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"The number of interactions/interaction strength between any two cell groups\",\n class=\"h6\"),\n hr(),\n\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"measure_heatmap\",\n label = \"measurement\",\n choices = list(\"count\" = \"count\", \"weight\" = \"weight\"),\n selected = \"count\"\n ),\n selectInput(\n \"palette_heatmap\",\n label = \"palette (sequential)\",\n choices = choices_palettes_sequential,\n selected = \"Blues\"\n ),\n # Sets the order of colours in the scale. If 1, the default, colours are as output by RColorBrewer::brewer.pal(). If -1, the order of colours is reversed.\n selectInput(\n \"direction_heatmap\",\n label = \"direction\",\n choices = list(\n \"1\"=1,\n \"-1\"=-1\n ),\n selected = 1,\n )\n\n # refer to: https://ggplot2.tidyverse.org/reference/scale_brewer.html\n ),\n ),\n\n # content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"netVisual_heatmap\",width = 664,height = 498)\n )\n )\n ),\n\n # the enriched signaling among one selected pair of cell groups\n nav_panel(\"rankNet\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"The enriched signaling\",\n class=\"h6\"),\n hr(),\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"select1_cell_group\",\n label = \"cell groups for sources.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[1],\n multiple = TRUE\n ),\n selectInput(\n \"select2_cell_group\",\n label = \"cell groups for targets.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[2],\n multiple = TRUE\n ),\n\n # selectInput(\n # \"measure_ranknet\",\n # label = \"measurement\",\n # choices = list(\"count\" = \"count\", \"weight\" = \"weight\"),\n # selected = \"count\"\n # ),\n selectInput(\n \"slot.name_ranknet\",\n label = \"slot.name\",\n choices = list(\"net\" = \"net\", \"netP\" = \"netP\"),\n selected = \"netP\"\n ),\n # selectInput(\n # \"palette_ranknet\",\n # label = \"palette (sequential)\",\n # choices = choices_palettes_sequential,\n # selected = \"Blues\"\n # ),\n ),\n ),\n\n # content\n plotly::plotlyOutput(outputId = \"rankNet\")\n )\n ),\n nav_panel(\"Contribution Plot\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"Contribution of each L-R pair to overall signaling\",\n class = \"h6\"),\n hr(),\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"pathway_contribution_plot\",\n label = \"a pathway to show\",\n choices = choices_pathways,\n selected = choices_pathways[1]\n ),\n selectInput(\n \"select3_cell_group\",\n label = \"a cell group for sources.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[1]\n ),\n selectInput(\n \"select4_cell_group\",\n label = \"a cell group for targets.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[2]\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n sliderInput(\n \"font.size_contribution_plot\",\n label = \"font.size\",\n min = 10,\n max=30,\n step = 5,\n value = 20\n )\n )\n ),\n\n # content\n plotOutput(outputId = \"netAnalysis_contribution\"),\n )\n ),\n ),\n\n # Contribution of each L-R pair to overall signaling\n # width = 3.2inch, height = 1.5inch,\n # height might change dependent on dataset\n\n ## Examine individual signaling pathway\n ## (the following four plots will be appeared based on user's input)\n h2(tags$i(class=\"bi bi-3-square-fill\"),\n \"Examine individual signaling pathway\"),\n navset_card_tab(\n title = h6(\"Plots\",class=\"h6\"),\n sidebar = accordion(\n selectizeInput(\n inputId = 'selectize_pathway',\n label = 'Select a pathway to show',\n choices = NULL,\n multiple = FALSE\n ),\n hr(),\n accordion_panel(\n title = \"Circle plot\",\n icon = tags$i(class=\"bi bi-circle-fill\"),\n # edge.width.max = 5, vertex.size.max = 12, vertex.label.cex = 0.8\n sliderInput(\n \"slider_Circle_plot_edge.width.max\",\n label = \"edge.width.max\",\n min = 5,\n max = 15,\n value = 8,\n step = 1\n ),\n sliderInput(\n \"slider_Circle_plot_vertex.size.max\",\n label = \"vertex.size.max\",\n min = 8,\n max = 16,\n value = 12,\n step = 2),\n sliderInput(\n \"slider_Circle_plot_vertex.label.cex\",\n label = \"vertex.label.cex\",\n min = 1,\n max = 2,\n value = 1,\n step = 0.2\n ),\n ),\n accordion_panel(\n title = \"Spatial plot\",\n icon = tags$i(class=\"bi bi-layers-half\"),\n # edge.width.max = 5, vertex.size.max = 1,\n # point.size = 2.5,\n # alpha.image = 0.2, vertex.label.cex = 5\n sliderInput(\n \"slider_Spatial_plot_edge.width.max\",\n label = \"edge.width.max\",\n min = 2,\n max = 8,\n value = 5,\n step = 1\n ),\n sliderInput(\n \"slider_Spatial_plot_vertex.size.max\",\n label = \"vertex.size.max\",\n min = 2,\n max = 8,\n value = 5,\n step = 1),\n sliderInput(\n \"slider_Spatial_plot_vertex.label.cex\",\n label = \"vertex.label.cex\",\n min = 5,\n max = 10,\n value = 8,\n step = 1\n ),\n\n sliderInput(\n \"slider_Spatial_plot_point.size\",\n label = \"point.size\",\n min = 1,\n max = 3,\n value = 2.4,\n step = 0.2\n ),\n sliderInput(\n \"slider_Spatial_plot_alpha.image\",\n label = \"alpha.image\",\n min = 0,\n max = 1,\n value = 0.2,\n step = 0.05\n ),\n ),\n accordion_panel(\n title = \"Contribution of each L-R pair\",\n icon = tags$i(class=\"bi bi-bar-chart-fill\"),\n ),\n ),\n\n # nav tab\n nav_panel(\n title = \"Circle plot\",\n div(class=\"d-flex justify-content-center\",\n plotOutput(outputId = \"Circle_plot\",\n height = \"780px\",width = \"580px\")\n )\n ),\n nav_panel(\n title = \"Spatial plot\",\n div(class=\"d-flex justify-content-center\",\n plotOutput(outputId = \"Spatial_plot\",\n height = \"780px\",width = \"580px\")\n )\n ),\n nav_panel(\n title = \"Contribution of each L-R pair\",\n plotly::plotlyOutput(outputId = \"LR_pair_contribution\",\n height = \"900px\")\n ),\n\n ),\n # body\n\n ),\n # page\n )\n # ##########################################################################\n # Shiny App's Server\n # ##########################################################################\n server <- function(input, output, session) {\n ############################################################################\n if (object@options$datatype == \"RNA\") {\n output$DimPlot <- plotly::renderPlotly({\n plotly_DimPlot(\n object,\n point.size = input$dimplot_point_size,\n alpha = input$dimplot_alpha,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"DimPlot\",\n width = 800,\n height = 600\n ))\n })\n } else {\n output$spatialDimPlot <- plotly::renderPlotly({\n plotly_spatialDimPlot(\n object,\n point.size = input$dimplot_point_size,\n alpha = input$dimplot_alpha,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialDimPlot\",\n width = 800,\n height = 600\n ))\n })\n }\n\n\n observe({\n updateSelectizeInput(\n session,\n \"selectize_gene_names\",\n # selected = c(\"Wnt10a\", \"Fzd1\", \"Lrp6\"),\n selected = choices_gene_names[1:2],\n # selected = c(\"Wnt10a\", \"Fzd1\", \"Lrp6\",\"Ror2\",\n # \"Nrp1\",\"Nrp2\",\"Bmpr2\",\"Ret\"),\n choices = choices_gene_names,\n server = TRUE\n )\n })\n # output$out6 <- renderPrint(input$selectize_gene_names)\n\n if (object@options$datatype == \"RNA\") {\n output$gene_expression_distribution <- plotly::renderPlotly(plotly_FeaturePlot(\n object,\n features = input$selectize_gene_names,\n plot_nrows = input$nrows_feature_plot1,\n point.size = input$point.size_feature_plot1,\n cutoff = input$cut.off_feature_plot1,\n color.heatmap = input$palette_feature_plot1,\n direction = input$direction_feature_plot1,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"FeaturePlot (use gene names)\",\n width = 600,\n height = 600\n ))\n )\n } else {\n output$gene_expression_distribution <- plotly::renderPlotly(plotly_spatialFeaturePlot(\n object,\n features = input$selectize_gene_names,\n plot_nrows = input$nrows_feature_plot1,\n point.size = input$point.size_feature_plot1,\n cutoff = input$cut.off_feature_plot1,\n color.heatmap = input$palette_feature_plot1,\n direction = input$direction_feature_plot1,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialFeaturePlot (use gene names)\",\n width = 600,\n height = 600\n ))\n )\n }\n\n\n observe({\n updateSelectizeInput(\n session,\n \"selectize_pairLR_use\",\n selected = choices_pairLR_use[1],\n # selected = c(\"WNT10A_FZD1_LRP6\",\"WNT10A_FZD10_LRP6\",\"BMP2_BMPR1A_ACVR2A\"),\n choices = choices_pairLR_use,\n server = TRUE\n )\n })\n # output$out7 <- renderPrint(input$selectize_pairLR_use)\n if (object@options$datatype == \"RNA\") {\n output$gene_expression_distribution2 <- plotly::renderPlotly({\n plotly_FeaturePlot(\n object,\n pairLR.use = input$selectize_pairLR_use,\n point.size = input$point.size_feature_plot2,\n do.binary = input$do.binary_feature_plot,\n cutoff = input$cut.off_feature_plot2,\n enriched.only = F,\n color.heatmap = input$palette_feature_plot2,\n direction = input$direction_feature_plot2,\n plot_nrows = as.numeric(input$nrows_feature_plot2)\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"FeaturePlot(use pairLRs)\",\n width = 600,\n height = 600\n ))\n })\n } else {\n output$gene_expression_distribution2 <- plotly::renderPlotly({\n plotly_spatialFeaturePlot(\n object,\n pairLR.use = input$selectize_pairLR_use,\n point.size = input$point.size_feature_plot2,\n do.binary = input$do.binary_feature_plot,\n cutoff = input$cut.off_feature_plot2,\n enriched.only = F,\n color.heatmap = input$palette_feature_plot2,\n direction = input$direction_feature_plot2,\n plot_nrows = as.numeric(input$nrows_feature_plot2)\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialFeaturePlot(use pairLRs)\",\n width = 600,\n height = 600\n ))\n })\n }\n\n\n ############################################################################\n output$netVisual_heatmap <- plotly::renderPlotly({\n suppressWarnings({\n netVisual_heatmap(object,\n measure = input$measure_heatmap,\n ) %>%\n plotly_netVisual_heatmap(\n palette.heatmap = input$palette_heatmap,\n direction.heatmap = input$direction_heatmap)\n })\n })\n\n output$rankNet <- plotly::renderPlotly({\n rankNet(\n object,\n mode = \"single\",\n measure = \"weight\",\n sources.use = input$select1_cell_group,\n targets.use = input$select2_cell_group,\n slot.name = input$slot.name_ranknet\n ) %>%\n plotly::ggplotly()\n })\n\n output$netAnalysis_contribution <- renderPlot({\n netAnalysis_contribution(\n object,\n signaling = input$pathway_contribution_plot,\n sources.use = input$select3_cell_group,\n targets.use = input$select4_cell_group,\n font.size = input$font.size_contribution_plot,\n font.size.title = input$font.size_contribution_plot,\n )\n },res = 96)\n ############################################################################\n observe({\n updateSelectizeInput(\n session,\n \"selectize_pathway\",\n selected = choices_pathways[1],\n choices = choices_pathways,\n server = TRUE\n )\n })\n output$Circle_plot <- renderPlot({\n netVisual_aggregate(\n object,\n signaling = input$selectize_pathway,\n layout = \"circle\",\n edge.width.max = input$slider_Circle_plot_edge.width.max,\n vertex.size.max = input$slider_Circle_plot_vertex.size.max,\n vertex.label.cex = input$slider_Circle_plot_vertex.label.cex\n )\n },res = 96)\n output$Spatial_plot <- renderPlot({\n netVisual_aggregate(\n object,\n signaling = input$selectize_pathway,\n layout = \"spatial\",\n edge.width.max = input$slider_Spatial_plot_edge.width.max,\n vertex.size.max = input$slider_Spatial_plot_vertex.size.max,\n vertex.label.cex = input$slider_Spatial_plot_vertex.label.cex,\n alpha.image = input$slider_Spatial_plot_alpha.image,\n point.size = input$slider_Spatial_plot_point.size,\n )\n })\n output$LR_pair_contribution <- plotly::renderPlotly({\n netAnalysis_contribution(\n object,\n signaling = input$selectize_pathway,\n font.size = 12,\n font.size.title = 14\n )\n })\n ############################################################################\n }\n\n\n # Running a Shiny app\n shinyApp(ui = ui, server = server,...)\n}\n"], ["/CellChat/R/modeling.R", "\n#' Compute the communication probability/strength between any interacting cell groups\n#'\n#' To further speed up on large-scale datasets, USER can downsample the data using the function 'subset' from Seurat package (e.g., pbmc.small <- subset(pbmc, downsample = 500)), or using the function `sketchData` from CellChat, in particular for the large cell clusters;\n#'\n#'\n#' @param object CellChat object\n#' @param type Methods for computing the average gene expression per cell group. By default = \"triMean\", producing fewer but stronger interactions;\n#' When setting `type = \"truncatedMean\"`, a value should be assigned to 'trim', producing more interactions.\n#' @param trim the fraction (0 to 0.25) of observations to be trimmed from each end of x before the mean is computed\n#' @param LR.use A subset of ligand-receptor interactions used in inferring communication network\n#' @param raw.use Whether use the raw data (i.e., `object@data.signaling`) or the smoothed data (i.e., `object@data.smooth`).\n#' Set raw.use = FALSE to use the projected data when analyzing single-cell data with shallow sequencing depth because the projected data could help to reduce the dropout effects of signaling genes, in particular for possible zero expression of subunits of ligands/receptors.\n#' @param population.size Whether consider the proportion of cells in each group across all sequenced cells.\n#' Set population.size = FALSE if analyzing sorting-enriched single cells, to remove the potential artifact of population size.\n#' Set population.size = TRUE if analyzing unsorted single-cell transcriptomes, with the reason that abundant cell populations tend to send collectively stronger signals than the rare cell populations.\n#'\n#' Parameters for spatial data analysis:\n#' @param distance.use Whether to use distance constraints to compute communication probability. Setting `distance.use = TRUE` indicates that the cell-cell communication probability is inversely proportional to the computed distance.\n#' Setting `distance.use = FALSE` will only filter out interactions between spatially distant regions, but not add distance constraints.\n#' @param interaction.range The maximum interaction/diffusion length of ligands (Unit: microns). This hard threshold is used to filter out the connections between spatially distant regions\n#' @param scale.distance A scale or normalization factor for the spatial distances when setting `distance.use = TRUE`. For example, scale.distance equals 1, 0.1, 0.01, 0.001, 0.11, or 0.011. We choose this values such that the minimum value of the scaled distances is in [1,2]. This value is not necessary when setting `distance.use = FALSE`.\n#'\n#' When comparing communication across different CellChat objects, the same scale factor should be used. For a single CellChat analysis, different scale factors will not affect the ranking of the signaling based on their interaction strength.\n#'\n#' @param k.min The minimum number of interacting cell pairs required for defining spatially proximal cell groups.\n#' @param contact.dependent Whether using the `contact-dependent` manner for inference signaling, that is determining interacting cell pairs by requiring cells to be in direct membrane-membrane contact. By default `contact.dependent = TRUE` when inferring contact-dependent and juxtacrine signaling (that is \"Cell-Cell Contact\" signaling classified in CellChatDB$interaction$annotation).\n#' If only focusing on `Secreted Signaling`, the `contact-dependent` manner will be not used except for setting `contact.dependent.forced = TRUE`.\n#' @param contact.range The interaction range (Unit: microns) to restrict the contact-dependent signaling when `contact.dependent = TRUE`.\n#' For spatial transcriptomics in a single-cell resolution, `contact.range` is approximately equal to the estimated cell diameter (i.e., the cell center-to-center distance), which means that contact-dependent and juxtacrine signaling can only happens when the two cells are contact to each other.\n#'\n#' Typically, `contact.range = 10`, which is a typical human cell size. However, for low-resolution spatial data such as 10X visium, it should be the cell center-to-center distance (i.e., `contact.range = 100` for visium data). The function `computeCellDistance` can compute the center-to-center distance.\n#'\n#' @param contact.knn.k Number of neighbors to restrict the contact-dependent signaling within the neatest neighbors when `contact.dependent = TRUE`. By default, CellChat uses `contact.range` to restrict the contact-dependent signaling; however, users can also provide a value of `contact.knn.k`, in order to determine interacting cell pairs based on the k-nearest neighbors (knn).\n#' For 10X visium, contact.knn.k = 6. For other spatial technologies, this value may be hard to determine because the sequenced cells/spots are usually not regularly arranged.\n#' @param do.symmetric Whether converting the adjacent matrix into symmetric one when determining spatially proximal cell groups. Default is TRUE, indicating that if adj(i,j) or adj(j,i) is zero, then both are zeros.\n#'\n#' @param contact.dependent.forced Whether forcing to use the `contact-dependent` manner for inference signaling for all L-R pairs including secreted signaling. Users can set `contact.dependent.forced = TRUE` if also preferring interactions within a contact manner for `Secreted Signaling`.\n#'\n#' @param nboot Threshold of p-values\n#' @param seed.use Set a random seed. By default, set the seed to 1.\n#' @param Kh Parameter in Hill function\n#' @param n Parameter in Hill function\n#'\n#'\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom stats aggregate\n#' @importFrom Matrix crossprod\n#' @importFrom utils txtProgressBar setTxtProgressBar\n#'\n#' @return A CellChat object with updated slot 'net':\n#'\n#' object@net$prob is the inferred communication probability (strength) array, where the first, second and third dimensions represent a source, target and ligand-receptor pair, respectively.\n#'\n#' USER can access all the inferred cell-cell communications using the function 'subsetCommunication(object)', which returns a data frame.\n#'\n#' object@net$pval is the corresponding p-values of each interaction\n#'\n#' @export\n#'\ncomputeCommunProb <- function(object, type = c(\"triMean\", \"truncatedMean\",\"thresholdedMean\", \"median\"), trim = 0.1, LR.use = NULL, raw.use = TRUE, population.size = FALSE,\n distance.use = TRUE, interaction.range = 250, scale.distance = 0.01, k.min = 10, contact.dependent = TRUE, contact.range = NULL, contact.knn.k = NULL, contact.dependent.forced = FALSE, do.symmetric = TRUE,\n nboot = 100, seed.use = 1L, Kh = 0.5, n = 1) {\n type <- match.arg(type)\n cat(type, \"is used for calculating the average gene expression per cell group.\", \"\\n\")\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n thresholdedMean = function(x) thresholdedMean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n if (raw.use) {\n data <- as.matrix(object@data.signaling)\n } else {\n data <- as.matrix(object@data.smooth)\n }\n if (is.null(LR.use)) {\n pairLR.use <- object@LR$LRsig\n } else {\n if (length(unique(LR.use$annotation)) > 1) {\n LR.use$annotation <- factor(LR.use$annotation, levels = c(\"Secreted Signaling\",\"ECM-Receptor\", \"Non-protein Signaling\", \"Cell-Cell Contact\"))\n LR.use <- LR.use[order(LR.use$annotation), , drop = FALSE]\n LR.use$annotation <- as.character(LR.use$annotation)\n }\n pairLR.use <- LR.use\n }\n complex_input <- object@DB$complex\n cofactor_input <- object@DB$cofactor\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n\n ptm = Sys.time()\n\n pairLRsig <- pairLR.use\n group <- object@idents\n geneL <- as.character(pairLRsig$ligand)\n geneR <- as.character(pairLRsig$receptor)\n nLR <- nrow(pairLRsig)\n numCluster <- nlevels(group)\n if (numCluster != length(unique(group))) {\n stop(\"Please check `unique(object@idents)` and ensure that the factor levels are correct!\n You may need to drop unused levels using 'droplevels' function. e.g.,\n `meta$labels = droplevels(meta$labels, exclude = setdiff(levels(meta$labels),unique(meta$labels)))`\")\n }\n\n data.use <- data/max(data)\n nC <- ncol(data.use)\n\n # compute the average expression per group\n data.use.avg <- aggregate(t(data.use), list(group), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n colnames(data.use.avg) <- levels(group)\n # compute the expression of ligand or receptor\n dataLavg <- computeExpr_LR(geneL, data.use.avg, complex_input)\n dataRavg <- computeExpr_LR(geneR, data.use.avg, complex_input)\n # take account into the effect of co-activation and co-inhibition receptors\n dataRavg.co.A.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avg, pairLRsig, type = \"A\")\n dataRavg.co.I.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avg, pairLRsig, type = \"I\")\n dataRavg <- dataRavg * dataRavg.co.A.receptor/dataRavg.co.I.receptor\n\n dataLavg2 <- t(replicate(nrow(dataLavg), as.numeric(table(group))/nC))\n dataRavg2 <- dataLavg2\n\n # compute the expression of agonist and antagonist\n index.agonist <- which(!is.na(pairLRsig$agonist) & pairLRsig$agonist != \"\")\n index.antagonist <- which(!is.na(pairLRsig$antagonist) & pairLRsig$antagonist != \"\")\n # quantify the communication probability\n\n # compute the spatial constraint\n if (object@options$datatype != \"RNA\") {\n data.spatial <- object@images$coordinates\n if (\"spatial.factors\" %in% names(object@images)) {\n ratio <- object@images$spatial.factors$ratio\n tol <- object@images$spatial.factors$tol\n } else {\n stop(\"`object@images$spatial.factors` is missing. Please update the object via `updateCellChat`! \\n\")\n }\n\n meta.t = data.frame(group = group, samples = object@meta$samples, row.names = rownames(object@meta))\n res <- computeRegionDistance(coordinates = data.spatial, meta = meta.t, interaction.range = interaction.range, ratio = ratio, tol = tol, k.min = k.min, contact.dependent = contact.dependent, contact.range = contact.range, contact.knn.k = contact.knn.k)\n d.spatial <- res$d.spatial # NaN if no nearby cell pairs\n adj.contact <- res$adj.contact # zeros if no nearby cell pairs\n if (distance.use) {\n print(paste0('>>> Run CellChat on spatial transcriptomics data using distances as constraints of the computed communication probability <<< [', Sys.time(),']'))\n d.spatial <- d.spatial * scale.distance\n diag(d.spatial) <- NaN\n d.min <- min(d.spatial, na.rm = TRUE)\n if (d.min < 1) {\n cat(\"The suggested minimum value of scaled distances is in [1,2], and the calculated value here is \", d.min,\"\\n\")\n stop(\"Please increase the value of `scale.distance` and use a value that is slighly smaller than \", format(1/d.min, digits = 2) ,\"\\n\")\n }\n P.spatial <- 1/d.spatial\n P.spatial[is.na(d.spatial)] <- 0\n diag(P.spatial) <- max(P.spatial) # if this value is 1, the self-connections will have more larger weight.\n d.spatial <- d.spatial/scale.distance # This is only for saving the data\n } else {\n print(paste0('>>> Run CellChat on spatial transcriptomics data without distance values as constraints of the computed communication probability <<< [', Sys.time(),']'))\n P.spatial <- matrix(1, nrow = numCluster, ncol = numCluster)\n P.spatial[is.na(d.spatial)] <- 0 # diagonal is 1\n }\n\n } else {\n print(paste0('>>> Run CellChat on sc/snRNA-seq data <<< [', Sys.time(),']'))\n d.spatial <- matrix(NaN, nrow = numCluster, ncol = numCluster)\n P.spatial <- matrix(1, nrow = numCluster, ncol = numCluster)\n adj.contact <- matrix(1, nrow = numCluster, ncol = numCluster)\n contact.dependent = FALSE; contact.dependent.forced = FALSE; contact.range = NULL; contact.knn.k = NULL;\n distance.use = NULL; interaction.range = NULL; ratio = NULL; tol = NULL; k.min = NULL;\n }\n\n if (object@options$datatype == \"RNA\") {\n nLR1 <- nLR\n } else {\n if (contact.dependent.forced == TRUE) {\n cat(\"Force to run CellChat in a `contact-dependent` manner for all L-R pairs including secreted signaling.\\n\")\n P.spatial <- P.spatial * adj.contact\n nLR1 <- nLR\n } else { # contact.dependent.forced == F\n if (contact.dependent == TRUE && length(unique(pairLRsig$annotation)) > 0) {\n if (all(unique(pairLRsig$annotation) %in% c(\"Cell-Cell Contact\"))) {\n cat(\"All the input L-R pairs are `Cell-Cell Contact` signaling. Run CellChat in a contact-dependent manner. \\n\")\n P.spatial <- P.spatial * adj.contact\n nLR1 <- nLR\n } else if (all(unique(pairLRsig$annotation) %in% c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\"))) {\n cat(\"Molecules of the input L-R pairs are diffusible. Run CellChat in a diffusion manner based on the `interaction.range`.\\n\")\n nLR1 <- nLR\n } else {\n cat(\"The input L-R pairs have both secreted signaling and contact-dependent signaling. Run CellChat in a contact-dependent manner for `Cell-Cell Contact` signaling, and in a diffusion manner based on the `interaction.range` for other L-R pairs. \\n\")\n nLR1 <- max(which(pairLRsig$annotation %in% c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\")))\n }\n } else { # contact.dependent == F or there is no `annotation` column in the database\n cat(\"Run CellChat in a diffusion manner based on the `interaction.range` for all L-R pairs. Setting `contact.dependent = TRUE` if preferring a contact-dependent manner for `Cell-Cell Contact` signaling. \\n\")\n nLR1 <- nLR\n }\n }\n }\n\n Prob <- array(0, dim = c(numCluster,numCluster,nLR))\n Pval <- array(0, dim = c(numCluster,numCluster,nLR))\n\n set.seed(seed.use)\n permutation <- replicate(nboot, sample.int(nC, size = nC))\n data.use.avg.boot <- my.sapply(\n X = 1:nboot,\n FUN = function(nE) {\n groupboot <- group[permutation[, nE]]\n data.use.avgB <- aggregate(t(data.use), list(groupboot), FUN = FunMean)\n data.use.avgB <- t(data.use.avgB[,-1])\n return(data.use.avgB)\n },\n simplify = FALSE\n )\n pb <- txtProgressBar(min = 0, max = nLR, style = 3, file = stderr())\n\n for (i in 1:nLR) {\n # ligand/receptor\n dataLR <- Matrix::crossprod(matrix(dataLavg[i,], nrow = 1), matrix(dataRavg[i,], nrow = 1))\n P1 <- dataLR^n/(Kh^n + dataLR^n)\n P1_Pspatial <- P1*P.spatial\n if (sum(P1_Pspatial) == 0) {\n Pnull = P1_Pspatial\n Prob[ , , i] <- Pnull\n p = 1\n Pval[, , i] <- matrix(p, nrow = numCluster, ncol = numCluster, byrow = FALSE)\n } else {\n if (i > nLR1) {\n P.spatial <- P.spatial * adj.contact\n }\n # agonist and antagonist\n if (is.element(i, index.agonist)) {\n data.agonist <- computeExpr_agonist(data.use = data.use.avg, pairLRsig, cofactor_input, index.agonist = i, Kh = Kh, n = n)\n P2 <- Matrix::crossprod(matrix(data.agonist, nrow = 1))\n } else {\n P2 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n if (is.element(i, index.antagonist)) {\n data.antagonist <- computeExpr_antagonist(data.use = data.use.avg, pairLRsig, cofactor_input, index.antagonist = i, Kh = Kh, n = n)\n P3 <- Matrix::crossprod(matrix(data.antagonist, nrow = 1))\n } else {\n P3 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n # number of cells\n if (population.size) {\n P4 <- Matrix::crossprod(matrix(dataLavg2[i,], nrow = 1), matrix(dataRavg2[i,], nrow = 1))\n } else {\n P4 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n # Pnull = P1*P2*P3*P4\n Pnull = P1*P2*P3*P4*P.spatial\n Prob[ , , i] <- Pnull\n\n Pnull <- as.vector(Pnull)\n\n #Pboot <- foreach(nE = 1:nboot) %dopar% {\n Pboot <- sapply(\n X = 1:nboot,\n FUN = function(nE) {\n data.use.avgB <- data.use.avg.boot[[nE]]\n dataLavgB <- computeExpr_LR(geneL[i], data.use.avgB, complex_input)\n dataRavgB <- computeExpr_LR(geneR[i], data.use.avgB, complex_input)\n # take account into the effect of co-activation and co-inhibition receptors\n dataRavgB.co.A.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avgB, pairLRsig[i, , drop = FALSE], type = \"A\")\n dataRavgB.co.I.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avgB, pairLRsig[i, , drop = FALSE], type = \"I\")\n dataRavgB <- dataRavgB * dataRavgB.co.A.receptor/dataRavgB.co.I.receptor\n dataLRB = Matrix::crossprod(dataLavgB, dataRavgB)\n P1.boot <- dataLRB^n/(Kh^n + dataLRB^n)\n # agonist and antagonist\n if (is.element(i, index.agonist)) {\n data.agonist <- computeExpr_agonist(data.use = data.use.avgB, pairLRsig, cofactor_input, index.agonist = i, Kh = Kh, n = n)\n P2.boot <- Matrix::crossprod(matrix(data.agonist, nrow = 1))\n } else {\n P2.boot <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n if (is.element(i, index.antagonist)) {\n data.antagonist <- computeExpr_antagonist(data.use = data.use.avgB, pairLRsig, cofactor_input, index.antagonist = i, Kh = Kh, n= n)\n P3.boot <- Matrix::crossprod(matrix(data.antagonist, nrow = 1))\n } else {\n P3.boot <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n if (population.size) {\n groupboot <- group[permutation[, nE]]\n dataLavg2B <- as.numeric(table(groupboot))/nC\n dataLavg2B <- matrix(dataLavg2B, nrow = 1)\n dataRavg2B <- dataLavg2B\n P4.boot = Matrix::crossprod(dataLavg2B, dataRavg2B)\n } else {\n P4.boot = matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n # Pboot = P1.boot*P2.boot*P3.boot*P4.boot\n Pboot = P1.boot*P2.boot*P3.boot*P4.boot*P.spatial\n return(as.vector(Pboot))\n }\n )\n Pboot <- matrix(unlist(Pboot), nrow=length(Pnull), ncol = nboot, byrow = FALSE)\n nReject <- rowSums(Pboot - Pnull > 0)\n p = nReject/nboot\n Pval[, , i] <- matrix(p, nrow = numCluster, ncol = numCluster, byrow = FALSE)\n }\n setTxtProgressBar(pb = pb, value = i)\n }\n close(con = pb)\n Pval[Prob == 0] <- 1\n dimnames(Prob) <- list(levels(group), levels(group), rownames(pairLRsig))\n dimnames(Pval) <- dimnames(Prob)\n net <- list(\"prob\" = Prob, \"pval\" = Pval)\n execution.time = Sys.time() - ptm\n object@options$run.time <- as.numeric(execution.time, units = \"secs\")\n\n object@options$parameter <- list(type.mean = type, trim = trim, raw.use = raw.use, population.size = population.size, nboot = nboot, seed.use = seed.use, Kh = Kh, n = n,\n distance.use = distance.use, interaction.range = interaction.range, ratio = ratio, tol = tol, k.min = k.min,\n contact.dependent = contact.dependent, contact.range = contact.range, contact.knn.k = contact.knn.k, contact.dependent.forced = contact.dependent.forced\n )\n if (object@options$datatype != \"RNA\") {\n object@images$distance <- d.spatial\n }\n object@net <- net\n print(paste0('>>> CellChat inference is done. Parameter values are stored in `object@options$parameter` <<< [', Sys.time(),']'))\n return(object)\n}\n\n\n#' Compute the communication probability on signaling pathway level by summarizing all related ligands/receptors\n#'\n#' @param object CellChat object\n#' @param net A list from object@net; If net = NULL, net = object@net\n#' @param pairLR.use A dataframe giving the ligand-receptor interactions; If pairLR.use = NULL, pairLR.use = object@LR$LRsig\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @return A CellChat object with updated slot 'netP':\n#'\n#' object@netP$prob is the communication probability array on signaling pathway level; USER can convert this array to a data frame using the function 'reshape2::melt()',\n#'\n#' e.g., `df.netP <- reshape2::melt(object@netP$prob, value.name = \"prob\"); colnames(df.netP)[1:3] <- c(\"source\",\"target\",\"pathway_name\")` or access all significant interactions using the function \\code{\\link{subsetCommunication}}\n#'\n#' object@netP$pathways list all the signaling pathways with significant communications.\n#'\n#' From version >= 1.1.0, pathways are ordered based on the total communication probabilities. NB: pathways with small total communication probabilities might be also very important since they might be specifically activated between only few cell types.\n#'\n#' @export\n#'\ncomputeCommunProbPathway <- function(object = NULL, net = NULL, pairLR.use = NULL, thresh = 0.05) {\n if (is.null(net)) {\n net <- object@net\n }\n if (is.null(pairLR.use)) {\n pairLR.use <- object@LR$LRsig\n }\n prob <- net$prob\n prob[net$pval > thresh] <- 0\n\n LR <- dimnames(prob)[[3]]\n LR.sig <- LR[apply(prob, 3, sum) != 0]\n\n pathways <- unique(pairLR.use$pathway_name)\n group <- factor(pairLR.use$pathway_name, levels = pathways)\n prob.pathways <- aperm(apply(prob, c(1, 2), by, group, sum), c(2, 3, 1))\n pathways.sig <- pathways[apply(prob.pathways, 3, sum) != 0]\n prob.pathways.sig <- prob.pathways[,,pathways.sig, drop = FALSE]\n idx <- sort(apply(prob.pathways.sig, 3, sum), decreasing=TRUE, index.return = TRUE)$ix\n pathways.sig <- pathways.sig[idx]\n prob.pathways.sig <- prob.pathways.sig[, , idx]\n\n if (is.null(object)) {\n netP = list(pathways = pathways.sig, prob = prob.pathways.sig)\n return(netP)\n } else {\n object@net$LRs <- LR.sig\n object@netP$pathways <- pathways.sig\n object@netP$prob <- prob.pathways.sig\n return(object)\n }\n}\n\n\n#' Calculate the aggregated network by counting the number of links or summarizing the communication probability\n#'\n#' @param object CellChat object\n#' @param sources.use,targets.use,signaling,pairLR.use Please check the description in function \\code{\\link{subsetCommunication}}\n#' @param remove.isolate whether removing the isolate cell groups without any interactions when applying \\code{\\link{subsetCommunication}}\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param return.object whether return an updated CellChat object\n#' @importFrom dplyr group_by summarize groups\n#' @importFrom stringr str_split\n#'\n#' @return Return an updated CellChat object:\n#'\n#' `object@net$count` is a matrix: rows and columns are sources and targets respectively, and elements are the number of interactions between any two cell groups. USER can convert a matrix to a data frame using the function `reshape2::melt()`\n#'\n#' `object@net$weight` is also a matrix containing the interaction weights between any two cell groups\n#'\n#' `object@net$sum` is deprecated. Use `object@net$weight`\n#'\n#' @export\n#'\naggregateNet <- function(object, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR.use = NULL, remove.isolate = TRUE, thresh = 0.05, return.object = TRUE) {\n net <- object@net\n if (is.null(sources.use) & is.null(targets.use) & is.null(signaling) & is.null(pairLR.use)) {\n prob <- net$prob\n pval <- net$pval\n pval[prob == 0] <- 1\n prob[pval >= thresh] <- 0\n net$count <- apply(prob > 0, c(1,2), sum)\n net$weight <- apply(prob, c(1,2), sum)\n net$weight[is.na(net$weight)] <- 0\n net$count[is.na(net$count)] <- 0\n } else {\n df.net <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.net$source_target <- paste(df.net$source, df.net$target, sep = \"_\")\n df.net2 <- df.net %>% group_by(source_target) %>% summarize(count = n(), .groups = 'drop')\n df.net3 <- df.net %>% group_by(source_target) %>% summarize(prob = sum(prob), .groups = 'drop')\n df.net2$prob <- df.net3$prob\n a <- stringr::str_split(df.net2$source_target, \"_\", simplify = T)\n df.net2$source <- as.character(a[, 1])\n df.net2$target <- as.character(a[, 2])\n cells.level <- levels(object@idents)\n if (remove.isolate) {\n message(\"Isolate cell groups without any interactions are removed. To block it, set `remove.isolate = FALSE`\")\n df.net2$source <- factor(df.net2$source, levels = cells.level[cells.level %in% unique(df.net2$source)])\n df.net2$target <- factor(df.net2$target, levels = cells.level[cells.level %in% unique(df.net2$target)])\n } else {\n df.net2$source <- factor(df.net2$source, levels = cells.level)\n df.net2$target <- factor(df.net2$target, levels = cells.level)\n }\n\n count <- tapply(df.net2[[\"count\"]], list(df.net2[[\"source\"]], df.net2[[\"target\"]]), sum)\n prob <- tapply(df.net2[[\"prob\"]], list(df.net2[[\"source\"]], df.net2[[\"target\"]]), sum)\n net$count <- count\n net$weight <- prob\n net$weight[is.na(net$weight)] <- 0\n net$count[is.na(net$count)] <- 0\n }\n if (return.object) {\n object@net <- net\n return(object)\n } else {\n return(net)\n }\n\n}\n\n\n#' Compute averaged expression values for each cell group\n#'\n#' @param object CellChat object\n#' @param features a char vector giving the used features. default use all features\n#' @param group.by cell group information; default is `object@idents` when input is a single object and `object@idents$joint` when input is a merged object; otherwise it should be one of the column names of the meta slot\n#' @param type methods for computing the average gene expression per cell group.\n#'\n#' By default = \"triMean\", defined as a weighted average of the distribution's median and its two quartiles (https://en.wikipedia.org/wiki/Trimean);\n#'\n#' When setting `type = \"truncatedMean\"`, a value should be assigned to 'trim'. See the function `base::mean`.\n#'\n#' @param trim the fraction (0 to 0.25) of observations to be trimmed from each end of x before the mean is computed.\n#' @param slot.name the data in the slot.name to use\n#' @param data.use a customed data matrix. Default: data.use = NULL and the expression matrix in the 'slot.name' is used\n#'\n#' @return Returns a matrix with genes as rows, cell groups as columns.\n\n#' @export\n#'\ncomputeAveExpr <- function(object, features = NULL, group.by = NULL, type = c(\"triMean\", \"truncatedMean\", \"median\"), trim = NULL,\n slot.name = c(\"data.signaling\", \"data\"), data.use = NULL) {\n type <- match.arg(type)\n slot.name <- match.arg(slot.name)\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n if (is.null(data.use)) {\n data.use <- slot(object, slot.name)\n }\n if (is.null(features)) {\n features.use <- row.names(data.use)\n } else {\n features.use <- intersect(features, row.names(data.use))\n }\n data.use <- data.use[features.use, , drop = FALSE]\n data.use <- as.matrix(data.use)\n\n if (is.null(group.by)) {\n labels <- object@idents\n if (!is.factor(labels)) {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n # compute the average expression per group\n data.use.avg <- aggregate(t(data.use), list(labels), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n rownames(data.use.avg) <- features.use\n colnames(data.use.avg) <- levels(labels)\n return(data.use.avg)\n}\n\n\n\n#' Compute the expression of complex in individual cells using geometric mean\n#' @param complex_input the complex_input from CellChatDB\n#' @param data.use data matrix (row are genes and columns are cells or cell groups)\n#' @param complex the names of complex\n#' @return\n#' @importFrom dplyr select starts_with\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @export\ncomputeExpr_complex <- function(complex_input, data.use, complex) {\n Rsubunits <- complex_input[complex,] %>% dplyr::select(starts_with(\"subunit\"))\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n data.complex = my.sapply(\n X = 1:nrow(Rsubunits),\n FUN = function(x) {\n RsubunitsV <- unlist(Rsubunits[x,], use.names = F)\n RsubunitsV <- RsubunitsV[RsubunitsV != \"\"]\n return(geometricMean(data.use[RsubunitsV, , drop = FALSE]))\n }\n )\n data.complex <- t(data.complex)\n return(data.complex)\n}\n\n# Compute the average expression of complex per cell group using geometric mean\n# @param complex_input the complex_input from CellChatDB\n# @param data.use data matrix (rows are genes and columns are cells)\n# @param complex the names of complex\n# @param group a factor defining the cell groups\n# @param FunMean the function for computing mean expression per group\n# @return\n# @importFrom dplyr select starts_with\n# @importFrom future nbrOfWorkers\n# @importFrom future.apply future_sapply\n# @importFrom pbapply pbsapply\n# #' @export\n.computeExprGroup_complex <- function(complex_input, data.use, complex, group, FunMean) {\n Rsubunits <- complex_input[complex,] %>% dplyr::select(starts_with(\"subunit\"))\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n data.complex = my.sapply(\n X = 1:nrow(Rsubunits),\n FUN = function(x) {\n RsubunitsV <- unlist(Rsubunits[x,], use.names = F)\n RsubunitsV <- RsubunitsV[RsubunitsV != \"\"]\n RsubunitsV <- intersect(RsubunitsV, rownames(data.use))\n if (length(RsubunitsV) > 1) {\n data.avg <- aggregate(t(data.use[RsubunitsV, ,drop = FALSE]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n } else if (length(RsubunitsV) == 1) {\n data.avg <- aggregate(matrix(data.use[RsubunitsV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n } else {\n data.avg = matrix(0, nrow = 1, ncol = length(unique(group)))\n }\n return(geometricMean(data.avg))\n }\n )\n data.complex <- t(data.complex)\n return(data.complex)\n}\n\n#' Compute the expression of ligands or receptors using geometric mean\n#' @param geneLR a char vector giving a set of ligands or receptors\n#' @param data.use data matrix (row are genes and columns are cells or cell groups)\n#' @param complex_input the complex_input from CellChatDB\n# #' @param group a factor defining the cell groups; If NULL, compute the expression of ligands or receptors in individual cells; otherwise, compute the average expression of ligands or receptors per cell group\n# #' @param FunMean the function for computing average expression per cell group\n#' @return\n#' @export\ncomputeExpr_LR <- function(geneLR, data.use, complex_input){\n nLR <- length(geneLR)\n numCluster <- ncol(data.use)\n index.singleL <- which(geneLR %in% rownames(data.use))\n dataL1avg <- data.use[geneLR[index.singleL],]\n dataLavg <- matrix(nrow = nLR, ncol = numCluster)\n dataLavg[index.singleL,] <- dataL1avg\n index.complexL <- setdiff(1:nLR, index.singleL)\n if (length(index.complexL) > 0) {\n complex <- geneLR[index.complexL]\n data.complex <- computeExpr_complex(complex_input, data.use, complex)\n dataLavg[index.complexL,] <- data.complex\n }\n return(dataLavg)\n}\n\n\n#' Modeling the effect of coreceptor on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig a data frame giving ligand-receptor interactions\n#' @param type when type == \"A\", computing expression of co-activation receptor; when type == \"I\", computing expression of co-inhibition receptor.\n#' @return\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @export\ncomputeExpr_coreceptor <- function(cofactor_input, data.use, pairLRsig, type = c(\"A\", \"I\")) {\n type <- match.arg(type)\n if (type == \"A\") {\n coreceptor.all = pairLRsig$co_A_receptor\n } else if (type == \"I\"){\n coreceptor.all = pairLRsig$co_I_receptor\n }\n index.coreceptor <- which(!is.na(coreceptor.all) & coreceptor.all != \"\")\n if (length(index.coreceptor) > 0) {\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n coreceptor <- coreceptor.all[index.coreceptor]\n coreceptor.ind <- cofactor_input[coreceptor, grepl(\"cofactor\" , colnames(cofactor_input) )]\n data.coreceptor.ind = my.sapply(\n X = 1:nrow(coreceptor.ind),\n FUN = function(x) {\n coreceptor.indV <- unlist(coreceptor.ind[x,], use.names = F)\n coreceptor.indV <- coreceptor.indV[coreceptor.indV != \"\"]\n coreceptor.indV <- intersect(coreceptor.indV, rownames(data.use))\n if (length(coreceptor.indV) == 1) {\n return(1 + data.use[coreceptor.indV, ])\n } else if (length(coreceptor.indV) > 1) {\n return(apply(1 + data.use[coreceptor.indV, ], 2, prod))\n } else {\n return(matrix(1, nrow = 1, ncol = ncol(data.use)))\n }\n }\n )\n data.coreceptor.ind <- t(data.coreceptor.ind)\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = ncol(data.use))\n data.coreceptor[index.coreceptor,] <- data.coreceptor.ind\n } else {\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = ncol(data.use))\n }\n return(data.coreceptor)\n}\n\n# Modeling the effect of coreceptor on the ligand-receptor interaction\n#\n# @param data.use data matrix\n# @param cofactor_input the cofactor_input from CellChatDB\n# @param pairLRsig a data frame giving ligand-receptor interactions\n# @param type when type == \"A\", computing expression of co-activation receptor; when type == \"I\", computing expression of co-inhibition receptor.\n# @param group a factor defining the cell groups\n# @param FunMean the function for computing mean expression per group\n# @return\n# @importFrom future nbrOfWorkers\n# @importFrom future.apply future_sapply\n# @importFrom pbapply pbsapply\n# #' @export\n.computeExprGroup_coreceptor <- function(cofactor_input, data.use, pairLRsig, type = c(\"A\", \"I\"), group, FunMean) {\n type <- match.arg(type)\n if (type == \"A\") {\n coreceptor.all = pairLRsig$co_A_receptor\n } else if (type == \"I\"){\n coreceptor.all = pairLRsig$co_I_receptor\n }\n index.coreceptor <- which(!is.na(coreceptor.all) & coreceptor.all != \"\")\n if (length(index.coreceptor) > 0) {\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n coreceptor <- coreceptor.all[index.coreceptor]\n coreceptor.ind <- cofactor_input[coreceptor, grepl(\"cofactor\" , colnames(cofactor_input) )]\n data.coreceptor.ind = my.sapply(\n X = 1:nrow(coreceptor.ind),\n FUN = function(x) {\n coreceptor.indV <- unlist(coreceptor.ind[x,], use.names = F)\n coreceptor.indV <- coreceptor.indV[coreceptor.indV != \"\"]\n coreceptor.indV <- intersect(coreceptor.indV, rownames(data.use))\n if (length(coreceptor.indV) > 1) {\n data.avg <- aggregate(t(data.use[coreceptor.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n return(apply(1 + data.avg, 2, prod))\n # return(1 + apply(data.avg, 2, mean))\n } else if (length(coreceptor.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[coreceptor.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n return(1 + data.avg)\n } else {\n return(matrix(1, nrow = 1, ncol = length(unique(group))))\n }\n }\n )\n data.coreceptor.ind <- t(data.coreceptor.ind)\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = length(unique(group)))\n data.coreceptor[index.coreceptor,] <- data.coreceptor.ind\n } else {\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = length(unique(group)))\n }\n\n return(data.coreceptor)\n}\n\n#' Modeling the effect of agonist on the ligand-receptor interaction\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n#' @param group a factor defining the cell groups\n#' @param index.agonist the index of agonist in the database\n#' @param Kh a parameter in Hill function\n#' @param FunMean the function for computing mean expression per group\n#' @param n Hill coefficient\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExprGroup_agonist <- function(data.use, pairLRsig, cofactor_input, group, index.agonist, Kh, FunMean, n) {\n agonist <- pairLRsig$agonist[index.agonist]\n agonist.ind <- cofactor_input[agonist, grepl(\"cofactor\" , colnames(cofactor_input))]\n agonist.indV <- unlist(agonist.ind, use.names = F)\n agonist.indV <- agonist.indV[agonist.indV != \"\"]\n agonist.indV <- intersect(agonist.indV, rownames(data.use))\n if (length(agonist.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[agonist.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.agonist <- 1 + data.avg^n/(Kh^n + data.avg^n)\n } else if (length(agonist.indV) > 1) {\n data.avg <- aggregate(t(data.use[agonist.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.agonist <- apply(1 + data.avg^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n data.agonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n }\n return(data.agonist)\n}\n\n#' Modeling the effect of antagonist on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n#' @param group a factor defining the cell groups\n#' @param index.antagonist the index of antagonist in the database\n#' @param Kh a parameter in Hill function\n#' @param n Hill coefficient\n#' @param FunMean the function for computing mean expression per group\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExprGroup_antagonist <- function(data.use, pairLRsig, cofactor_input, group, index.antagonist, Kh, FunMean, n) {\n antagonist <- pairLRsig$antagonist[index.antagonist]\n antagonist.ind <- cofactor_input[antagonist, grepl( \"cofactor\" , colnames(cofactor_input) )]\n antagonist.indV <- unlist(antagonist.ind, use.names = F)\n antagonist.indV <- antagonist.indV[antagonist.indV != \"\"]\n antagonist.indV <- intersect(antagonist.indV, rownames(data.use))\n if (length(antagonist.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[antagonist.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.antagonist <- Kh^n/(Kh^n + data.avg^n)\n } else if (length(antagonist.indV) > 1) {\n data.avg <- aggregate(t(data.use[antagonist.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.antagonist <- apply(Kh^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n data.antagonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n }\n return(data.antagonist)\n}\n\n\n#' Modeling the effect of agonist on the ligand-receptor interaction\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n# #' @param group a factor defining the cell groups\n#' @param index.agonist the index of agonist in the database\n#' @param Kh a parameter in Hill function\n# #' @param FunMean the function for computing mean expression per group\n#' @param n Hill coefficient\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExpr_agonist <- function(data.use, pairLRsig, cofactor_input, index.agonist, Kh, n) {\n agonist <- pairLRsig$agonist[index.agonist]\n agonist.ind <- cofactor_input[agonist, grepl(\"cofactor\" , colnames(cofactor_input))]\n agonist.indV <- unlist(agonist.ind, use.names = F)\n agonist.indV <- agonist.indV[agonist.indV != \"\"]\n agonist.indV <- intersect(agonist.indV, rownames(data.use))\n if (length(agonist.indV) == 1) {\n # data.avg <- aggregate(matrix(data.use[agonist.indV,], ncol = 1), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[agonist.indV,, drop = FALSE]\n data.agonist <- 1 + data.avg^n/(Kh^n + data.avg^n)\n } else if (length(agonist.indV) > 1) {\n # data.avg <- aggregate(t(data.use[agonist.indV,]), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[agonist.indV,, drop = FALSE]\n data.agonist <- apply(1 + data.avg^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n # data.agonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n data.agonist = matrix(1, nrow = 1, ncol = ncol(data.use))\n }\n return(data.agonist)\n}\n\n#' Modeling the effect of antagonist on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n# #' @param group a factor defining the cell groups\n#' @param index.antagonist the index of antagonist in the database\n#' @param Kh a parameter in Hill function\n#' @param n Hill coefficient\n# #' @param FunMean the function for computing mean expression per group\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExpr_antagonist <- function(data.use, pairLRsig, cofactor_input, index.antagonist, Kh, n) {\n antagonist <- pairLRsig$antagonist[index.antagonist]\n antagonist.ind <- cofactor_input[antagonist, grepl( \"cofactor\" , colnames(cofactor_input) )]\n antagonist.indV <- unlist(antagonist.ind, use.names = F)\n antagonist.indV <- antagonist.indV[antagonist.indV != \"\"]\n antagonist.indV <- intersect(antagonist.indV, rownames(data.use))\n if (length(antagonist.indV) == 1) {\n # data.avg <- aggregate(matrix(data.use[antagonist.indV,], ncol = 1), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[antagonist.indV,, drop = FALSE]\n data.antagonist <- Kh^n/(Kh^n + data.avg^n)\n } else if (length(antagonist.indV) > 1) {\n # data.avg <- aggregate(t(data.use[antagonist.indV,]), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[antagonist.indV,, drop = FALSE]\n data.antagonist <- apply(Kh^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n # data.antagonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n data.antagonist = matrix(1, nrow = 1, ncol = ncol(data.use))\n }\n return(data.antagonist)\n}\n\n\n#' Compute the geometric mean\n#' @param x a numeric vector\n#' @param na.rm whether remove na\n#' @return\n#' @export\ngeometricMean <- function(x,na.rm=TRUE){\n if (is.null(nrow(x))) {\n exp(mean(log(x),na.rm=na.rm))\n } else {\n exp(apply(log(x),2,mean,na.rm=na.rm))\n }\n}\n\n\n#' Compute the Tukey's trimean\n#' @param x a numeric vector\n#' @param na.rm whether remove na\n#' @return\n#' @importFrom stats quantile\n#' @export\ntriMean <- function(x, na.rm = TRUE) {\n mean(stats::quantile(x, probs = c(0.25, 0.50, 0.50, 0.75), na.rm = na.rm))\n}\n\n#' Compute the average expression per cell group when the percent of expressing cells per cell group larger than a threshold\n#' @param x a numeric vector\n#' @param trim the percent of expressing cells per cell group to be considered as zero\n#' @param na.rm whether remove na\n#' @return\n#' @importFrom Matrix nnzero\n# #' @export\nthresholdedMean <- function(x, trim = 0.1, na.rm = TRUE) {\n percent <- Matrix::nnzero(x)/length(x)\n if (percent < trim) {\n return(0)\n } else {\n return(mean(x, na.rm = na.rm))\n }\n}\n\n#' Filter cell-cell communication if there are only few number of cells in certain cell groups or inconsistent cell-cell communication across samples\n#'\n#' @param object CellChat object\n#' @param min.cells The minmum number of cells required in each cell group for cell-cell communication\n#' @param min.samples The minmum number of samples required for consistent cell-cell communication across samples (that is an interaction present in at least `min.samples` samples) when mutiple samples/replicates/batches are merged as an input for CellChat analysis.\n#' @param rare.keep Whether to keep the interactions associated with the rare populations when min.samples >= 2. When a rare population is identified in the merged samples (say 15 cells in this rare population from two samples), it is likely to filter out the interactions associated with this rare population when setting min.samples >= 2. Setting `rare.keep = TRUE` to retain the identified interactions associated with this rare population.\n#' @param nonFilter.keep Whether to keep the non-filtered cell-cell communication in the CellChat object. This is useful for avoiding re-running `computeCommunProb` if you want to adjust the parameters when running `filterCommunication`.\n#' @return CellChat object with an updated slot net\n#' @export\n#'\nfilterCommunication <- function(object, min.cells = 10, min.samples = NULL, rare.keep = FALSE, nonFilter.keep = FALSE) {\n net <- object@net\n if (nonFilter.keep == TRUE) {\n cat(\"The non-filtered cell-cell communication is stored in `object@net$prob.nonFilter` and `object@net$pval.nonFilter`. \\n\")\n object@net$prob.nonFilter <- net$prob\n object@net$pval.nonFilter <- net$pval\n }\n num.interaction0 <- sum(net$prob > 0)\n cell.excludes <- which(as.numeric(table(object@idents)) <= min.cells)\n if (length(cell.excludes) > 0) {\n cat(\"The cell-cell communication related with the following cell groups are excluded due to the few number of cells: \", toString(levels(object@idents)[cell.excludes]), \"!\",'\\t')\n net$prob[cell.excludes,,] <- 0\n net$prob[,cell.excludes,] <- 0\n num.interaction1 <- sum(net$prob > 0)\n pct.dicrease <- scales::percent((num.interaction0-num.interaction1)/num.interaction0, accuracy = .1)\n cat(paste0(pct.dicrease, \" interactions are removed!\",'\\n'))\n } else {\n num.interaction1 <- num.interaction0\n }\n\n sample.info <- object@meta$samples\n sample.id <- levels(sample.info)\n if (is.null(min.samples)) {\n min.samples <- 1\n } else if (min.samples > length(sample.id)) {\n stop(paste0(\"There are only \", length(sample.id), \" samples in the data. Please change the value of `min.samples`! \"))\n }\n if (length(sample.id) >= 2 & min.samples >= 2) {\n if (object@options$parameter$raw.use == TRUE) {\n data <- as.matrix(object@data.signaling)\n } else {\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n stop(\"`object@data.smooth` is missing. Please update the CellChat object via `updateCellChat`! \\n\")\n }\n data <- as.matrix(object@data.smooth)\n }\n data.use <- data/max(data)\n group <- object@idents\n type <- object@options$parameter$type.mean\n trim <- object@options$parameter$trim\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n thresholdedMean = function(x) thresholdedMean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n LR <- dimnames(net$prob)[[3]]\n idx.nonzero <- which(apply(net$prob, 3, sum) != 0)\n LR.nonzero <- LR[idx.nonzero] # only examine the L-R pairs with nonzero communication probabilities.\n\n interaction_input <- object@DB$interaction\n complex_input <- object@DB$complex\n geneIfo <- object@DB$geneInfo\n idx <- match(LR.nonzero, interaction_input$interaction_name)\n geneL <- as.character(interaction_input$ligand[idx])\n geneR <- as.character(interaction_input$receptor[idx])\n\n geneLR <- c(unique(geneL), unique(geneR))\n geneLR <- extractGeneSubset(geneLR, complex_input, geneIfo)\n data.use <- data.use[rownames(data.use) %in% geneLR, ]\n\n score.LR <- array(0, dim = c(nlevels(group),nlevels(group),length(LR.nonzero), length(sample.id)))\n LR.nonzero.all <- c()\n cell.excludes.sample <- c()\n for (i in 1:length(sample.id)) {\n cell.use <- which(sample.info == sample.id[i])\n group.use <- group[cell.use]\n group.use <- droplevels(group.use)\n # get the rare populations with few cells in each sample\n cell.excludes.sample.i <- which(as.numeric(table(object@idents[cell.use])) <= min.cells)\n cell.excludes.sample <- c(cell.excludes.sample, cell.excludes.sample.i)\n # compute average expression per cell group\n data.use.i <- data.use[, cell.use]\n data.use.avg <- aggregate(t(data.use.i), list(group.use), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n group.exist <- which(levels(group) %in% unique(group.use))\n if (length(group.exist) < nlevels(group)) {\n data.use.avg.temp <- matrix(0, nrow = nrow(data.use), ncol = nlevels(group))\n data.use.avg.temp[ , group.exist] <- data.use.avg\n rownames(data.use.avg.temp) <- rownames(data.use.avg)\n data.use.avg <- data.use.avg.temp\n }\n colnames(data.use.avg) <- levels(group)\n # compute the average expression of ligand or receptor in each cell group\n dataLavg <- computeExpr_LR(geneL, data.use.avg, complex_input)\n dataRavg <- computeExpr_LR(geneR, data.use.avg, complex_input)\n # compute the interaction scores for each ligand-receptor pair based on their expression\n for (jj in 1:length(LR.nonzero)) { # It is not good to use parallel here because it will change the order of LR\n score.LR[,,jj,i] <- Matrix::crossprod(matrix(dataLavg[jj, ], nrow = 1), matrix(dataRavg[jj, ], nrow = 1))\n }\n if (length(cell.excludes.sample.i) > 0) {\n cat(paste0(\"The number of cells of the following cell groups in \", sample.id[i], \" sample are less than \", min.cells, \" cells: \",toString(levels(object@idents)[cell.excludes.sample.i]), \"!\",'\\n'))\n score.LR[cell.excludes.sample.i, , , i] <- 0\n score.LR[ ,cell.excludes.sample.i, , i] <- 0\n }\n #LR.nonzero.all <- c(LR.nonzero.all, LR.nonzero[apply(score.LR[ , , , i], 3, sum) != 0])\n }\n #LR.nonzero.jointOnly <- setdiff(LR.nonzero, unique(LR.nonzero.all))\n\n # get the excluded cell groups that are not observed in the merged data, which is very possible for rare populations\n cell.excludes.sample <- unique(cell.excludes.sample)\n if (length(cell.excludes.sample) > 0) {\n cell.excludes.sample <- setdiff(cell.excludes.sample, cell.excludes)\n }\n\n score.LR[score.LR > 0] <- 1 # binarize the interaction score\n score.LR.consitent <- array(0, dim = c(nlevels(group),nlevels(group),length(LR.nonzero)))\n LR.inconsitent <- c()\n for (jj in 1:length(LR.nonzero)) {\n score.LR.sum <- apply(score.LR[ , , jj, ], c(1,2), sum) # elements 2 and 1 means consistent and inconsistent interactions across samples, respectively.\n # set communication probability to be zero for inconsistent interactions across samples\n if (sum((score.LR.sum > 0) * (score.LR.sum < min.samples)) > 0) {\n #LR.inconsitent <- c(LR.inconsitent, LR.nonzero[jj])\n score.LR.consitent <- (score.LR.sum >= min.samples) * 1\n if (rare.keep == TRUE & length(cell.excludes.sample) > 0) {\n score.LR.consitent[cell.excludes.sample, ] <- 1\n score.LR.consitent[ ,cell.excludes.sample] <- 1\n }\n net$prob[ , , LR.nonzero[jj]] <- net$prob[ , , LR.nonzero[jj]] * score.LR.consitent\n }\n }\n num.interaction2 <- sum(net$prob > 0)\n pct.dicrease <- scales::percent((num.interaction1-num.interaction2)/num.interaction1, accuracy = .1)\n cat(paste0(pct.dicrease, \" interactions are removed due to their inconsistence across \", min.samples, \" samples!\",'\\n'))\n }\n\n object@net <- net\n return(object)\n}\n\n\n#' Identify all the significant interactions (L-R pairs) from some cell groups to other cell groups\n#'\n#' @param object CellChat object\n#' @param from a vector giving the index or the name of source cell groups\n#' @param to a corresponding vector giving the index or the name of target cell groups. Note: The length of 'from' and 'to' must be the same, giving the corresponding pair of cell groups for communication.\n#' @param bidirection whether show the bidirectional communication, i.e., both 'from'->'to' and 'to'->'from'.\n#' @param pair.only whether only return ligand-receptor pairs without pathway names and communication strength\n#' @param pairLR.use0 ligand-receptor pairs to use; default is all the significant interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @return\n#' @export\n#'\nidentifyEnrichedInteractions <- function(object, from, to, bidirection = FALSE, pair.only = TRUE, pairLR.use0 = NULL, thresh = 0.05){\n pairwiseLR <- object@net$pairwiseRank\n if (is.null(pairwiseLR)) {\n stop(\"The interactions between pairwise cell groups have not been extracted!\n Please first run `object <- rankNetPairwise(object)`\")\n }\n group.names.all <- names(pairwiseLR)\n if (!is.numeric(from)) {\n from <- match(from, group.names.all)\n if (sum(is.na(from)) > 0) {\n message(\"Some input cell group names in 'from' do not exist!\")\n from <- from[!is.na(from)]\n }\n }\n if (!is.numeric(to)) {\n to <- match(to, group.names.all)\n if (sum(is.na(to)) > 0) {\n message(\"Some input cell group names in 'to' do not exist!\")\n to <- to[!is.na(to)]\n }\n }\n if (length(from) != length(to)) {\n stop(\"The length of 'from' and 'to' must be the same!\")\n }\n if (bidirection) {\n from2 <- c(from, to)\n to <- c(to, from)\n from <- from2\n }\n if (is.null(pairLR.use0)) {\n k <- 0\n pairLR.use0 <- list()\n for (i in 1:length(from)){\n pairwiseLR_ij <- pairwiseLR[[from[i]]][[to[i]]]\n idx <- pairwiseLR_ij$pval < thresh\n if (length(idx) > 0) {\n k <- k +1\n pairLR.use0[[k]] <- pairwiseLR_ij[idx,]\n }\n }\n pairLR.use0 <- do.call(rbind, pairLR.use0)\n }\n\n k <- 0\n pval <- matrix(nrow = length(rownames(pairLR.use0)), ncol = length(from))\n prob <- pval\n group.names <- c()\n for (i in 1:length(from)) {\n k <- k+1\n pairwiseLR_ij <- pairwiseLR[[from[i]]][[to[i]]]\n pairwiseLR_ij <- pairwiseLR_ij[rownames(pairLR.use0),]\n pval_ij <- pairwiseLR_ij$pval\n prob_ij <- pairwiseLR_ij$prob\n pval_ij[pval_ij > 0.05] = 1\n pval_ij[pval_ij > 0.01 & pval_ij <= 0.05] = 2\n pval_ij[pval_ij <= 0.01] = 3\n prob_ij[pval_ij ==1] <- 0\n pval[,k] <- pval_ij\n prob[,k] <- prob_ij\n group.names <- c(group.names, paste(group.names.all[from[i]], group.names.all[to[i]], sep = \" - \"))\n }\n prob[which(prob == 0)] <- NA\n # remove rows that are entirely NA\n pval <- pval[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n pairLR.use0 <- pairLR.use0[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n prob <- prob[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n if (pair.only) {\n pairLR.use0 <- dplyr::select(pairLR.use0, ligand, receptor)\n }\n return(pairLR.use0)\n}\n\n\n#' Compute the region distance based on the spatial locations of each splot/cell of the spatial transcriptomics\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param meta a data frame including at least two columns named `group` and `samples`. `meta$group` is a factor vector defining the regions/labels of each cell/spot. `meta$samples` is a factor vector defining the sample labels of each dataset.\n#' @param interaction.range The maximum interaction/diffusion range of ligands. This hard threshold is used to filter out the connections between spatially distant regions\n#' @param ratio a numerical vector giving the conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns).\n#'\n#' For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates.\n#' For 10X visium, it is the ratio of the theoretical spot size (i.e., 65um) over the number of pixels that span the diameter of a theoretical spot size in the full-resolution image (i.e., 'spot.size.fullres' in the 'scalefactors_json.json' file).\n#' @param tol a numerical vector giving the tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um.\n#'\n#' For example, for 10X visium, `tol` can be set as `65/2`; for slide-seq, `tol` can be set as `10/2`.\n#' If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance.\n#' @param k.min the minimum number of interacting cell pairs required for defining adjacent cell groups\n#' @param contact.dependent Whether determining spatially proximal cell groups based on either the contact.range or the k-nearest neighbors (knn). By default `contact.dependent = TRUE` when inferring contact-dependent and juxtacrine signaling (including ECM-Receptor and Cell-Cell Contact signaling classified in CellChatDB$interaction$annotation).\n#' If only focusing on `Secreted Signaling`, the `contact.dependent` will be automatically set as FALSE except for `contact.dependent.forced = TRUE`.\n#' @param contact.range The interaction range (Unit: microns) to restrict the contact-dependent signaling.\n#' For spatial transcriptomics in a single-cell resolution, `contact.range` is approximately equal to the estimated cell diameter (i.e., the cell center-to-center distance), which means that contact-dependent and juxtacrine signaling can only happens when the two cells are contact to each other.\n#'\n#' Typically, `contact.range = 10`, which is a typical human cell size. However, for low-resolution spatial data such as 10X visium, it should be the cell center-to-center distance (i.e., `contact.range = 100` for visium data). The function `computeCellDistance` can compute the center-to-center distance.\n#'\n#' @param contact.knn.k Number of neighbors to restrict the contact-dependent signaling within the neatest neighbors. By default, CellChat uses `contact.range` to restrict the contact-dependent signaling; however, users can also provide a value of `contact.knn.k`, in order to determine spatially proximal cell groups based on the k-nearest neighbors (knn).\n#' For 10X visium, contact.knn.k = 6. For other spatial technologies, this value may be hard to determine because the sequenced cells/spots are usually not regularly arranged.\n#' @param do.symmetric Whether converting the adjacent matrix into symmetric one when determining spatially proximal cell groups. Default is TRUE, indicating that if adj(i,j) or adj(j,i) is zero, then both are zeros.\n#'\n#' @importFrom BiocNeighbors queryKNN AnnoyParam\n#' @return A list including a square matrix giving the pairwise region distances and an adjacent matrix indicating physically contacting cell groups based on either the contact.range or the k-nearest neighbors\n#'\n#' @export\ncomputeRegionDistance <- function(coordinates, meta,\n interaction.range = NULL, ratio = NULL, tol = NULL, k.min = 10,\n contact.dependent = TRUE, contact.range = NULL, contact.knn.k = NULL, do.symmetric = TRUE\n) {\n trim <- 0.1\n FunMean <- function(x) mean(x, trim = trim, na.rm = TRUE) # This is used for computing the average distance between two cell groups\n group <- meta$group\n numCluster <- nlevels(group)\n level.use <- levels(group)\n level.use <- level.use[level.use %in% unique(group)]\n samples <- meta$samples\n samples.use <- levels(samples)\n d.spatial <- array(NaN, dim = c(numCluster,numCluster,length(samples.use)))\n adj.spatial <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n adj.contact <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n adj.contact.knn <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n\n if (contact.dependent == TRUE & !is.null(contact.knn.k)) {\n ## find the k-nearest neighbors for each single cell\n # my.knn <- FNN::get.knn(coordinates, k = contact.knn.k)\n # nn.ranked <- my.knn$nn.index # this is a matrix with the size of nCell * contact.knn.k\n nn.ranked <- matrix(NA, nrow = nrow(coordinates), ncol = contact.knn.k)\n for (k in 1:length(samples.use)) {\n idx.k <- which(samples == samples.use[k])\n my.knn <- suppressWarnings(BiocNeighbors::findKNN(coordinates[idx.k, ], k = contact.knn.k, BNPARAM = BiocNeighbors::AnnoyParam(), get.index = TRUE))\n nn.ranked[idx.k, ] <- my.knn$index # this is a matrix with the size of nCell * contact.knn.k\n }\n k.min.contact <- k.min\n } else {\n nn.ranked <- matrix(1, nrow = nrow(coordinates), ncol = 1)\n k.min.contact <- -1 # this produces adj.contact.knn with all elements being 1\n }\n if (contact.dependent == TRUE) {\n if (is.null(contact.range) & is.null(contact.knn.k)) {\n stop(\"Please check the documentation of `computeCommunProb` and provide the value of either `contact.range` or `contact.knn.k`\")\n }\n } else {\n contact.range <- 10000 # this produces adj.contact with all elements being 1\n }\n\n for (k in 1:length(samples.use)) {\n idx.k <- samples == samples.use[k]\n for (i in 1:numCluster) {\n for (j in 1:numCluster) {\n idx.i <- which((group == level.use[i]) & idx.k)\n idx.j <- which((group == level.use[j]) & idx.k)\n if (length(idx.i) == 0 | length(idx.j) == 0) {\n next # if one cell group is missing in one sample, just goes to next loop\n }\n data.spatial.i <- coordinates[idx.i, , drop = FALSE]\n data.spatial.j <- coordinates[idx.j, , drop = FALSE]\n # for each point in the i-th cell group, find its 1-nearest neighbor in the j-th cell group\n #qout <- suppressWarnings(BiocNeighbors::queryKNN(data.spatial.j, data.spatial.i, k = 1, BNPARAM = BiocNeighbors::KmknnParam(), get.index = TRUE))\n qout <- suppressWarnings(BiocNeighbors::queryKNN(data.spatial.j, data.spatial.i, k = 1, BNPARAM = BiocNeighbors::AnnoyParam(), get.index = TRUE))\n # qout$index is an one column matrix with length being `length(idx.i)`, which is the index of the 1-nearest neighbor in the j-th cell group defined by `idx.j`\n # qout$distance is an one column matrix with length being `length(idx.i)`, which is the distance to the 1-nearest neighbor in the j-th cell group defined by `idx.j`\n\n # conver the calculated distance into the distance in micrometers\n qout$distance <- qout$distance*ratio[k]\n # long-range distance\n idx <- qout$distance - interaction.range < tol[k]\n adj.spatial[i,j,k] <- (length(unique(qout$index[idx])) >= k.min) * 1\n # short-range distance based on contact.range\n idx2 <- qout$distance - contact.range < tol[k]\n adj.contact[i,j,k] <- (length(unique(qout$index[idx2])) >= k.min) * 1\n # short-range distance based on knn\n knn.i <- unique(as.vector(nn.ranked[idx.i, ]))\n #adj.contact.knn[i,j,k] <- (length(intersect(knn.i, idx.j)) >= k.min.contact) * 1\n adj.contact.knn[i,j,k] <- (length(intersect(knn.i, unique(qout$index[idx]))) >= k.min.contact) * 1 # knn within the long-range distance\n # computing the average distance between two cell groups\n d.spatial[i,j,k] <- FunMean(qout$distance) # since distances are positive values, different ways for computing the mean have little effects.\n\n }\n }\n }\n\n # merged spatial information from different samples\n d.spatial <- apply(d.spatial, c(1,2), function(x) mean(x, na.rm = TRUE))\n adj.spatial <- apply(adj.spatial, c(1,2), mean)\n adj.contact <- apply(adj.contact, c(1,2), mean)\n adj.contact.knn <- apply(adj.contact.knn, c(1,2), mean)\n # for multi-samples analysis, the following is needed\n adj.spatial[adj.spatial > 0] <- 1\n adj.contact[adj.contact > 0] <- 1\n adj.contact.knn[adj.contact.knn > 0] <- 1\n\n # make these adjacent matrix as symmetric\n if (do.symmetric) {\n adj.spatial <- adj.spatial * t(adj.spatial) # if one is zero, then both are zeros.\n adj.contact <- adj.contact * t(adj.contact) # if one is zero, then both are zeros.\n adj.contact.knn <- adj.contact.knn * t(adj.contact.knn) # if one is zero, then both are zeros.\n }\n d.spatial <- (d.spatial + t(d.spatial))/2\n\n # filter out the spatially distant cell groups\n adj.spatial[adj.spatial == 0] <- NaN\n d.spatial <- d.spatial * adj.spatial\n\n rownames(d.spatial) <- levels(group); colnames(d.spatial) <- levels(group)\n\n if (length(contact.knn.k) > 0) {\n adj.contact = adj.contact.knn\n }\n res <- list(d.spatial = d.spatial, adj.contact = adj.contact)\n return(res)\n\n}\n\n#' Compute cell-cell distance based on the spatial coordinates\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param interaction.range The maximum interaction/diffusion range of ligands. This hard threshold is used to filter out the connections between spatially distant cells\n#' @param ratio The conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns).\n#'\n#' For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates.\n#' For 10X visium, it is the ratio of the theoretical spot size (i.e., 65um) over the number of pixels that span the diameter of a theoretical spot size in the full-resolution image (i.e., 'spot.size.fullres' in the 'scalefactors_json.json' file).\n#' @param tol The tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um.\n#'\n#' For example, for 10X visium, `tol` can be set as `65/2`; for slide-seq, `tol` can be set as `10/2`.\n#' If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance.\n#'\n#' @return an object of class \"dist\" giving the pairwise cell-cell distance\n#' @export\n#'\ncomputeCellDistance <- function(coordinates, interaction.range = NULL, ratio = NULL, tol = NULL){\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n d.spatial <- stats::dist(coordinates)\n if (!is.null(ratio)) {\n d.spatial <- d.spatial*ratio\n }\n\n if(!is.null(interaction.range) & !is.null(tol)){\n message(\"\\n Apply a predefined spatial distance threshold based on the interaction length...\")\n d.spatial[d.spatial > (interaction.range + tol)] <- NaN\n }\n return(d.spatial)\n}\n\n\n"], ["/CellChat/R/utilities.R", "#' Normalize data using a scaling factor\n#'\n#' @param data.raw input raw data\n#' @param scale.factor the scaling factor used for each cell\n#' @param do.log whether to do log transformation with pseudocount 1\n#' @param do.sparse whether to use sparse format\n#' @export\n#'\nnormalizeData <- function(data.raw, scale.factor = 10000, do.log = TRUE, do.sparse = TRUE) {\n # Scale counts within a sample\n library.size <- Matrix::colSums(data.raw)\n #scale.factor <- median(library.size)\n expr <- Matrix::t(Matrix::t(data.raw) / library.size) * scale.factor\n if (do.log) {\n data.norm <-log1p(expr)\n }\n if (do.sparse) {\n data.input <- as(data.norm, \"dgCMatrix\")\n }\n return(data.norm)\n}\n\n\n#' Scale the data\n#'\n#' @param data.use input data\n#' @param do.center whether center the values\n#' @export\n#'\nscaleData <- function(data.use, do.center = T) {\n data.use <- Matrix::t(scale(Matrix::t(data.use), center = do.center, scale = TRUE))\n return(data.use)\n}\n\n\n#' Scale a data matrix\n#'\n#' @param x data matrix\n#' @param scale the method to scale the data\n#' @param na.rm whether remove na\n#' @importFrom Matrix rowMeans colMeans rowSums colSums\n#' @return\n#' @export\n#'\n#' @examples\nscaleMat <- function(x, scale, na.rm=TRUE){\n\n av <- c(\"none\", \"row\", \"column\", 'r1', 'c1')\n i <- pmatch(scale, av)\n if(is.na(i) )\n stop(\"scale argument shoud take values: 'none', 'row' or 'column'\")\n scale <- av[i]\n\n switch(scale, none = x\n , row = {\n x <- sweep(x, 1L, rowMeans(x, na.rm = na.rm), '-',check.margin = FALSE)\n sx <- apply(x, 1L, sd, na.rm = na.rm)\n sweep(x, 1L, sx, \"/\", check.margin = FALSE)\n }\n , column = {\n x <- sweep(x, 2L, colMeans(x, na.rm = na.rm), '-',check.margin = FALSE)\n sx <- apply(x, 2L, sd, na.rm = na.rm)\n sweep(x, 2L, sx, \"/\", check.margin = FALSE)\n }\n , r1 = sweep(x, 1L, rowSums(x, na.rm = na.rm), '/', check.margin = FALSE)\n , c1 = sweep(x, 2L, colSums(x, na.rm = na.rm), '/', check.margin = FALSE)\n )\n}\n\n#' Downsampling single cell data using geometric sketching algorithm\n#'\n#' USERs need to install the python package `pip install geosketch` (https://github.com/brianhie/geosketch)\n#'\n#' @param object A data matrix (should have row names; samples in rows, features in columns) or a Seurat object.\n#'\n#' When object is a PCA or UMAP space, please set `do.PCA = FALSE`\n#'\n#' When object is a data matrix (cells in rows and genes in columns), it is better to use the highly variable genes. PCA will be done on this input data matrix.\n#' @param percent the percent of data to sketch\n#' @param idents A vector of identity classes to keep for sketching\n#' @param do.PCA whether doing PCA on the input data\n#' @param dimPC the number of components to use\n#' @importFrom reticulate import\n#' @return A vector of cell names to use for downsampling\n#' @export\n#'\nsketchData <- function(object, percent, idents = NULL, do.PCA = TRUE, dimPC = 30) {\n # pip install geosketch\n geosketch <- reticulate::import('geosketch')\n if (is(object,\"Seurat\")) {\n sketch.size <- as.integer(percent*ncol(object))\n if (!is.null(idents)) {\n object <- subset(object, idents = idents)\n }\n object <- object %>% #Seurat::NormalizeData(verbose = FALSE) %>%\n FindVariableFeatures(selection.method = \"vst\", nfeatures = 2000) %>%\n RunPCA(pc.genes = object@var.genes, npcs = dimPC, verbose = FALSE)\n\n X.pcs <- object@reductions$pca@cell.embeddings\n cells.all <- Cells(object)\n\n } else {\n # Get top PCs\n if (do.PCA) {\n X.pcs <- runPCA(object, dimPC = dimPC)\n } else {\n X.pcs <- object\n }\n\n # Sketch percent of data.\n sketch.size <- as.integer(percent*nrow(X))\n cells.all <- rownames(object)\n }\n sketch.index <- geosketch$gs(X.pcs, sketch.size)\n sketch.index <- unlist(sketch.index) + 1\n sketch.cells <- cells.all[sketch.index]\n return(sketch.cells)\n}\n\n\n#' Add the cell information into meta slot\n#'\n#' @param object CellChat object\n#' @param meta cell information to be added\n#' @param meta.name the name of column to be assigned\n#'\n#' @return\n#' @export\n#'\n#' @examples\naddMeta <- function(object, meta, meta.name = NULL) {\n if (is.null(x = meta.name) && is.atomic(x = meta)) {\n stop(\"'meta.name' must be provided for atomic meta types (eg. vectors)\")\n }\n if (inherits(x = meta, what = c(\"matrix\", \"Matrix\"))) {\n meta <- as.data.frame(x = meta)\n }\n\n if (is.null(x = meta.name)) {\n meta.name <- names(meta)\n } else {\n names(meta) <- meta.name\n }\n object@meta <- meta\n return(object)\n}\n\n\n#' Set the default identity of cells\n#' @param object CellChat object\n#' @param ident.use the name of the variable in object.meta;\n#' @param levels set the levels of factor\n#' @param display.warning whether display the warning message\n#' @return\n#' @export\n#'\n#' @examples\nsetIdent <- function(object, ident.use = NULL, levels = NULL, display.warning = TRUE){\n if (!is.null(ident.use)) {\n object@idents <- as.factor(object@meta[[ident.use]])\n }\n\n if (!is.null(levels)) {\n object@idents <- factor(object@idents, levels = levels)\n }\n if (\"0\" %in% as.character(object@idents)) {\n stop(\"Cell labels cannot contain `0`! \")\n }\n if (length(object@net) > 0) {\n if (all(dimnames(object@net$prob)[[1]] %in% levels(object@idents) )) {\n message(\"Reorder cell groups! \")\n cat(\"The cell group order before reordering is \", dimnames(object@net$prob)[[1]],'\\n')\n # idx <- match(dimnames(object@net$prob)[[1]], levels(object@idents))\n idx <- match(levels(object@idents), dimnames(object@net$prob)[[1]])\n object@net$prob <- object@net$prob[idx, , ]\n object@net$prob <- object@net$prob[, idx, ]\n object@net$pval <- object@net$pval[idx, , ]\n object@net$pval <- object@net$pval[, idx, ]\n cat(\"The cell group order after reordering is \", dimnames(object@net$prob)[[1]],'\\n')\n } else {\n message(\"Rename cell groups but do not change the order! \")\n cat(\"The cell group order before renaming is \", dimnames(object@net$prob)[[1]],'\\n')\n dimnames(object@net$prob) <- list(levels(object@idents), levels(object@idents), dimnames(object@net$prob)[[3]])\n dimnames(object@net$pval) <- dimnames(object@net$prob)\n cat(\"The cell group order after renaming is \", dimnames(object@net$prob)[[1]],'\\n')\n }\n if (display.warning) {\n warning(\"All the calculations after `computeCommunProb` should be re-run!!\n These include but not limited to `computeCommunProbPathway`,`aggregateNet`, and `netAnalysis_computeCentrality`.\")\n }\n\n\n }\n return(object)\n}\n\n\n#' Add a reduced space of the data into CellChat object\n#'\n#' @param object CellChat object from a single dataset\n#' @param dr A data frame (rows are cells with rownames) consisting of a low-dimensional space for visualization\n#' @param dr.name A char name of the reduction method for the input `dr`\n#' @param seu.obj A Seurat object with the reduced space of the data\n#' @param dr.use A char name of the reduction method to use when taking `seu.obj` as input. By default, all reduced space in `seu.obj` will be added in `object@dr`\n#' @param force.add Whether to force to add a new reduced space when a reduced space exists in `object@dr`\n#' @return\n#' @export\n#' @examples\n#' \\dontrun{\n#' cellChat <- addReduction(object = cellchat, dr = cell.embeddings, dr.name = \"umap\")\n#'\n#' cellChat <- addReduction(object = cellchat, seu.obj = seu.obj)\n#' }\naddReduction <- function(object, dr = NULL, dr.name = NULL, seu.obj = NULL, dr.use = NULL, force.add = FALSE) {\n if (length(names(object@dr)) > 0) {\n if (!force.add) {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please set `force.add = TRUE` if intending to add a new reduced space. \\n\"))\n }\n }\n if (!is.null(dr)) {\n if (is.null(dr.name)) {\n stop(\"When inputing `dr`, please also provide the `dr.name`! \\n\")\n }\n dr <- as.data.frame(dr)\n if (all(colnames(object@data.signaling) %in% rownames(dr))) {\n object@dr[[dr.name]] <- dr[colnames(object@data.signaling), ]\n } else {\n stop(\"Some cell barcodes in the CellChat object are not the rownames of the input `dr`. Please check the input `dr` and make sure it contains all cells in the CellChat analysis. \\n\")\n }\n } else if(!is.null(seu.obj)) {\n if (!is(seu.obj,\"Seurat\")) {\n stop(\"The input `seu.obj` can be only the Seurat object. \\n\")\n }\n reductions <- names(seu.obj@reductions)\n if (length(reductions) == 0) {\n stop(\"The input `seu.obj` does not contain any low-dimensional space. Please generate a low-dimensional space for visualization. \\n\")\n }\n if (!is.null(dr.use)) {\n reductions <- intersect(reductions, dr.use)\n }\n if (length(reductions) == 0) {\n stop(\"The input `dr.use` is not in the reduced space in `seu.obj`. \\n\")\n }\n for (i in 1:length(reductions)) {\n dr.name <- reductions[i]\n dr = seu.obj@reductions[[dr.name]]@cell.embeddings\n if (all(colnames(object@data.signaling) %in% rownames(dr))) {\n cat(paste0(dr.name, \" is now added in `object@dr` as a low-dimensional space. \\n\"))\n object@dr[[dr.name]] <- dr[colnames(object@data.signaling), ]\n } else {\n stop(\"Some cell barcodes in the CellChat object are not in the input `seu.obj`. Please check the input `seu.obj` and make sure it contains all cells in the CellChat analysis. \\n\")\n }\n }\n } else {\n stop(\"Please input either `dr` or `seu.obj`! \\n\")\n }\n return(object)\n}\n\n\n#' Update and re-order the cell group names after running `computeCommunProb`\n#'\n#' @param object CellChat object\n#' @param old.cluster.name A vector defining old cell group labels in `object@idents`; Default = NULL, which will use `levels(object@idents)`\n#' @param new.cluster.name A vector defining new cell group labels to rename\n#' @param new.order reset order of cell group labels\n#' @param new.cluster.metaname assign a name of the new labels, which will be the column name of new labels in `object@meta`\n#' @return An updated CellChat object\n#' @export\n#'\nupdateClusterLabels <- function(object, old.cluster.name = NULL, new.cluster.name = NULL, new.order = NULL, new.cluster.metaname = \"new.labels\") {\n if (is.null(old.cluster.name)) {\n old.cluster.name <- levels(object@idents)\n }\n if (new.cluster.metaname %in% colnames(object@meta)) {\n stop(\"Please define another `new.cluster.metaname` as it exists in `colnames(object@meta)`!\")\n }\n if (!is.null(new.cluster.name)) {\n labels.new <- plyr::mapvalues(object@idents, from = old.cluster.name, to = new.cluster.name)\n object@meta[[new.cluster.metaname]] <- labels.new\n object <- setIdent(object, ident.use = new.cluster.metaname, display.warning = FALSE)\n } else {\n new.cluster.metaname <- NULL\n cat(\"Only reorder cell groups but do not rename cell groups!\")\n }\n\n if (!is.null(new.order)) {\n object <- setIdent(object, ident.use = new.cluster.metaname, levels = new.order, display.warning = FALSE)\n }\n message(\"We now re-run computeCommunProbPathway`,`aggregateNet`, and `netAnalysis_computeCentrality`...\")\n object <- computeCommunProbPathway(object)\n ## calculate the aggregated network by counting the number of links or summarizing the communication probability\n object <- aggregateNet(object)\n # network importance analysis\n object <-netAnalysis_computeCentrality(object, slot.name = \"netP\")\n return(object)\n}\n\n\n\n\n\n#' Subset the expression data of signaling genes for saving computation cost\n#'\n#' @param object CellChat object\n#' @param features default = NULL: subset the expression data of signaling genes in CellChatDB.use\n#'\n#' @return An updated CellChat object by assigning a subset of the data into the slot `data.signaling`\n#' @export\n#'\nsubsetData <- function(object, features = NULL) {\n interaction_input <- object@DB$interaction\n if (object@options$datatype != \"RNA\") {\n if (\"annotation\" %in% colnames(interaction_input) == FALSE) {\n warning(\"A column named `annotation` is required in `object@DB$interaction` when running CellChat on spatial transcriptomics! The `annotation` column is now automatically added and all L-R pairs are assigned as `Secreted Signaling`, which means that these L-R pairs are assumed to mediate diffusion-based cellular communication.\")\n interaction_input$annotation <- \"Secreted Signaling\"\n }\n }\n if (\"annotation\" %in% colnames(interaction_input) == TRUE) {\n if (length(unique(interaction_input$annotation)) > 1) {\n interaction_input$annotation <- factor(interaction_input$annotation, levels = c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\", \"Cell-Cell Contact\"))\n interaction_input <- interaction_input[order(interaction_input$annotation), , drop = FALSE]\n interaction_input$annotation <- as.character(interaction_input$annotation)\n }\n object@DB$interaction <- interaction_input\n }\n\n if (is.null(features)) {\n DB <- object@DB\n gene.use_input <- extractGene(DB)\n gene.use <- intersect(gene.use_input, rownames(object@data))\n } else {\n gene.use <- intersect(features, rownames(object@data))\n }\n object@data.signaling <- object@data[rownames(object@data) %in% gene.use, ]\n return(object)\n}\n\n\n\n#' Identify over-expressed signaling genes associated with each cell group\n#'\n#' USERS can use customized gene set as over-expressed signaling genes by setting `object@var.features[[features.name]] <- features.sig`\n#' The Bonferroni corrected/adjusted p value can be obtained via `object@var.features[[paste0(features.name, \".info\")]]`. Note that by default `features.name = \"features\"`\n#'\n#' @param object CellChat object\n#' @param data.use a customed data matrix. Default: data.use = NULL and the expression matrix in the slot 'data.signaling' is used\n#' @param group.by cell group information; default is `object@idents`; otherwise it should be one of the column names of the meta slot\n#' @param idents.use a subset of cell groups used for analysis\n#' @param invert whether to invert the idents.use\n#' @param group.dataset dataset origin information in a merged CellChat object; set it as one of the column names of meta slot when identifying the highly enriched genes in one dataset for each cell group\n#' @param pos.dataset the dataset name used for identifying highly enriched genes in this dataset for each cell group\n#' @param group.DE.combined Whether to perform differential expression between conditions by ignoring cell group information. By default, group.DE.combined = FALSE, which will perform differential expression analysis between two biological conditions for each cell group;\n#' When group.DE.combined = TRUE, it will perform DE analysis by combining all cell groups together.\n#'\n#' @param features.name a char name used for storing the over-expressed signaling genes in `object@var.features[[features.name]]`\n#' @param only.pos Only return positive markers\n#' @param features features used for identifying Over Expressed genes. default use all features\n#' @param return.object whether to return the object; otherwise return a data frame consisting of over-expressed signaling genes associated with each cell group\n#' @param thresh.pc Threshold of the fraction of cells expressed in one cluster, i.e., thresh.pc = 0.1\n#' @param thresh.fc Threshold of Log Fold Change, i.e., thresh.pc = 0.1\n#' @param thresh.p Threshold of p-values, i.e., thresh.pc = 0.05\n#' @param do.DE Whether to perform differential expression analysis. By default do.DE = TRUE; When do.DE = FALSE, selecting over-expressed genes that are expressed in more than `min.cells` cells.\n#' @param do.fast If do.fast = TRUE, then perform a ultra-fast Wilcoxon test using presto package; otherwise using stats package. These two methods produce different logFC values, and the presto::wilcoxauc method gives smaller values.\n#' @param min.cells the minmum number of expressed cells required for the genes that are considered for cell-cell communication analysis\n#' @importFrom future nbrOfWorkers\n#' @importFrom pbapply pbsapply\n#' @importFrom future.apply future_sapply\n#' @importFrom stats sd wilcox.test p.adjust\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, two new elements named 'features.name' and paste0(features.name, \".info\") will be added into the list `object@var.features`\n#' `object@var.features[[features.name]]` is a vector consisting of the identified over-expressed signaling genes;\n#' `object@var.features[[paste0(features.name, \".info\")]]` is a data frame returned from the differential expression analysis\n#' @export\n#'\nidentifyOverExpressedGenes <- function(object, data.use = NULL, group.by = NULL, idents.use = NULL, invert = FALSE,\n group.dataset = NULL, pos.dataset = NULL, group.DE.combined = FALSE,\n features.name = \"features\", only.pos = TRUE, features = NULL, return.object = TRUE,\n thresh.pc = 0, thresh.fc = 0, thresh.p = 0.05, do.DE = TRUE, do.fast = TRUE, min.cells = 10) {\n if (!is.list(object@var.features)) {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n if (is.null(data.use)) {\n X <- object@data.signaling\n if (nrow(X) < 3) {stop(\"Please check `object@data.signaling` and ensure that you have run `subsetData` and that the data matrix `object@data.signaling` looks OK.\")}\n } else {\n X <- data.use\n }\n\n if (is.null(features)) {\n features.use <- row.names(X)\n } else {\n features.use <- intersect(features, row.names(X))\n }\n data.use <- X[features.use,]\n\n if (do.DE) {\n # select genes based on differential expression\n data.use <- as.matrix(data.use)\n\n if (is.null(group.by)) {\n labels <- object@idents\n if (!is.factor(labels)) {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n level.use <- levels(labels)[levels(labels) %in% unique(labels)]\n if (!is.null(idents.use)) {\n if (invert) {\n level.use <- level.use[!(level.use %in% idents.use)]\n } else {\n level.use <- level.use[level.use %in% idents.use]\n }\n }\n numCluster <- length(level.use)\n\n if (!is.null(group.dataset)) {\n labels.dataset <- as.character(object@meta[[group.dataset]])\n if (!(pos.dataset %in% unique(labels.dataset))) {\n cat(\"Please set pos.dataset to be one of the following dataset names: \", unique(as.character(labels.dataset)))\n stop()\n }\n labels.dataset[labels.dataset != pos.dataset] <- toString(setdiff(unique(labels.dataset), pos.dataset))\n labels.dataset <- factor(labels.dataset, levels = c(pos.dataset, setdiff(unique(labels.dataset), pos.dataset)))\n }\n\n if (do.fast) {\n presto.check <- rlang::is_installed(c(\"presto\"))\n if (!presto.check) {\n stop(\n \"For a faster implementation of the Wilcoxon Test, please install the presto package\",\n \"\\n--------------------------------------------\",\n \"\\n devtools::install_github('immunogenomics/presto')\",\n \"\\n--------------------------------------------\",\n \"\\n Otherwise, plase set `do.fast = FALSE` for running the standard Wilcoxon Test!\\n\"\n )\n }\n if (is.null(group.dataset)) {\n genes.de <- presto::wilcoxauc(data.use, labels, groups_use = level.use)\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"clusters\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100) %>% arrange(pvalues)\n\n } else if ((!is.null(group.dataset)) & (group.DE.combined == FALSE)) {\n genes.de <- data.frame()\n for (i in 1:numCluster) {\n idx <- which(labels == level.use[i])\n data.use.i <- data.use[ ,idx]\n labels.i <- labels.dataset[idx]\n genes.de.i <- presto::wilcoxauc(data.use.i, labels.i)\n # genes.de.i <- genes.de.i[1:(nrow(genes.de.i)/2),]\n genes.de.i$clusters <- level.use[i]\n genes.de <- rbind(genes.de, genes.de.i)\n }\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"datasets\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100)\n markers.all$datasets <- factor(markers.all$datasets, levels = levels(labels.dataset))\n markers.all <- markers.all[order(markers.all$datasets, markers.all$pvalues, -markers.all$logFC), ]\n } else if ((!is.null(group.dataset)) & (group.DE.combined == TRUE)) {\n genes.de.c <- presto::wilcoxauc(data.use, labels.dataset)\n genes.de.c <- genes.de.c[1:(nrow(genes.de.c)/2),]\n genes.de <- data.frame()\n for (i in 1:numCluster) {\n genes.de.c$clusters <- level.use[i]\n genes.de <- rbind(genes.de, genes.de.c)\n }\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"datasets\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100) %>% arrange(pvalues)\n\n }\n markers.all <- dplyr::select(markers.all, -c(\"logFC_abs\",\"statistic\",\"pct.max\"))\n\n if (only.pos & nrow(markers.all) > 0) {\n markers.all <- subset(markers.all, subset = logFC > 0)\n }\n markers.all$features <- as.character(markers.all$features)\n\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- unique(features.sig)\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n\n } else {\n\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n\n mean.fxn <- function(x) {\n return(log(x = mean(x = expm1(x = x)) + 1))\n }\n labels <- as.character(labels)\n genes.de <- vector(\"list\", length = numCluster)\n for (i in 1:numCluster) {\n features <- features.use\n if (is.null(group.dataset)) {\n cell.use1 <- which(labels == level.use[i])\n cell.use2 <- base::setdiff(1:length(labels), cell.use1)\n } else if ((!is.null(group.dataset)) & (group.DE.combined == FALSE)) {\n cell.use1 <- which((labels == level.use[i]) & (labels.dataset == pos.dataset))\n cell.use2 <- which((labels == level.use[i]) & (labels.dataset != pos.dataset))\n } else if ((!is.null(group.dataset)) & (group.DE.combined == TRUE)) {\n cell.use1 <- which(labels.dataset == pos.dataset)\n cell.use2 <- which(labels.dataset != pos.dataset)\n }\n\n # feature selection (based on percentages)\n thresh.min <- 0\n pct.1 <- round(\n x = rowSums(data.use[features, cell.use1, drop = FALSE] > thresh.min) /\n length(x = cell.use1),\n digits = 3\n )\n pct.2 <- round(\n x = rowSums(data.use[features, cell.use2, drop = FALSE] > thresh.min) /\n length(x = cell.use2),\n digits = 3\n )\n data.alpha <- cbind(pct.1, pct.2)\n colnames(x = data.alpha) <- c(\"pct.1\", \"pct.2\")\n alpha.min <- apply(X = data.alpha, MARGIN = 1, FUN = max)\n names(x = alpha.min) <- rownames(x = data.alpha)\n features <- names(x = which(x = alpha.min > thresh.pc))\n if (length(x = features) == 0) {\n #stop(\"No features pass thresh.pc threshold\")\n next\n }\n\n # feature selection (based on average difference)\n data.1 <- apply(X = data.use[features, cell.use1, drop = FALSE],MARGIN = 1,FUN = mean.fxn)\n data.2 <- apply(X = data.use[features, cell.use2, drop = FALSE],MARGIN = 1,FUN = mean.fxn)\n FC <- (data.1 - data.2)\n if (only.pos) {\n features.diff <- names(which(FC > thresh.fc))\n } else {\n features.diff <- names(which(abs(FC) > thresh.fc))\n }\n\n features <- intersect(x = features, y = features.diff)\n if (length(x = features) == 0) {\n # stop(\"No features pass thresh.fc threshold\")\n next\n }\n\n data1 <- data.use[features, cell.use1, drop = FALSE]\n data2 <- data.use[features, cell.use2, drop = FALSE]\n\n pvalues <- unlist(\n x = my.sapply(\n X = 1:nrow(x = data1),\n FUN = function(x) {\n # return(wilcox.test(data1[x, ], data2[x, ], alternative = \"greater\")$p.value)\n return(wilcox.test(data1[x, ], data2[x, ])$p.value)\n }\n )\n )\n\n pval.adj = stats::p.adjust(\n p = pvalues,\n method = \"bonferroni\",\n n = nrow(X)\n )\n genes.de[[i]] <- data.frame(clusters = level.use[i], features = as.character(rownames(data1)), pvalues = pvalues, logFC = FC[features], data.alpha[features,, drop = F],pvalues.adj = pval.adj, stringsAsFactors = FALSE)\n }\n\n markers.all <- data.frame()\n for (i in 1:numCluster) {\n gde <- genes.de[[i]]\n if (!is.null(gde)) {\n gde <- gde[order(gde$pvalues, -gde$logFC), ]\n gde <- subset(gde, subset = pvalues < thresh.p)\n if (nrow(gde) > 0) {\n markers.all <- rbind(markers.all, gde)\n }\n }\n }\n if (only.pos & nrow(markers.all) > 0) {\n markers.all <- subset(markers.all, subset = logFC > 0)\n }\n if (!is.null(group.dataset)) {\n markers.all$datasets[markers.all$logFC > 0] <- pos.dataset\n markers.all$datasets[markers.all$logFC < 0] <- setdiff(unique(labels.dataset), pos.dataset)\n markers.all$datasets <- factor(markers.all$datasets, levels = levels(labels.dataset))\n markers.all <- markers.all[order(markers.all$datasets, markers.all$pvalues, -markers.all$logFC), ]\n }\n markers.all$features <- as.character(markers.all$features)\n\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- features.sig\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n }\n\n } else {\n # select genes if they are exprssed in at least `min.cells` cells\n markers.all <- data.frame(features = as.character(rownames(data.use)), nCells = rowSums(data.use > 0))\n markers.all <- dplyr::filter(markers.all, nCells >= min.cells)\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- unique(features.sig)\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n }\n\n\n if (return.object) {\n return(object)\n } else {\n return(markers.all)\n }\n}\n\n\n#' Identify over-expressed ligands and (complex) receptors associated with each cell group\n#'\n#' This function identifies the over-expressed ligands and (complex) receptors based on the identified signaling genes from 'identifyOverExpressedGenes'.\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for storing the over-expressed ligands and receptors in `object@var.features[[paste0(features.name, \".LR\")]]`\n#' @param features a vector of features to use. default use all over-expressed genes in `object@var.features[[features.name]]`\n#' @param return.object whether returning a CellChat object. If FALSE, it will return a data frame containing over-expressed ligands and (complex) receptors associated with each cell group\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom dplyr select\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, a new element named paste0(features.name, \".LR\") will be added into the list `object@var.features`\n#' @export\n#'\nidentifyOverExpressedLigandReceptor <- function(object, features.name = \"features\", features = NULL, return.object = TRUE) {\n\n features.name.LR <- paste0(features.name, \".LR\")\n features.name <- paste0(features.name, \".info\")\n DB <- object@DB\n interaction_input <- DB$interaction\n complex_input <- DB$complex\n pairLR <- select(interaction_input, ligand, receptor)\n LR.use <- unique(c(pairLR$ligand, pairLR$receptor))\n if (is.null(features)) {\n if (is.list(object@var.features)) {\n markers.all <- object@var.features[[features.name]] # use the updated CellChat object 12/2020\n } else {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n\n } else {\n features.use <- features\n rm(features)\n markers.all <- subset(markers.all, subset = features %in% features.use)\n }\n\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n complexSubunits <- complex_input[, grepl(\"subunit\" , colnames(complex_input))]\n\n markers.all.new <- data.frame()\n for (i in 1:nrow(markers.all)) {\n if (markers.all$features[i] %in% LR.use) {\n markers.all.new <- rbind(markers.all.new, markers.all[i, , drop = FALSE])\n } else {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (markers.all$features[i] %in% complexsubunitsV) {\n return(x)\n }\n }\n )\n )\n complexSubunits.sig <- rownames(complexSubunits[index.sig,])\n markers.all.complex <- data.frame()\n for (j in 1:length(complexSubunits.sig)) {\n markers.all.complex <- rbind(markers.all.complex, markers.all[i, , drop = FALSE])\n }\n markers.all.complex$features <- complexSubunits.sig\n markers.all.new <- rbind(markers.all.new, markers.all.complex)\n }\n }\n\n object@var.features[[features.name.LR]] <- markers.all.new\n\n if (return.object) {\n return(object)\n } else {\n return(markers.all.new)\n }\n}\n\n\n\n#' Identify over-expressed ligand-receptor interactions (pairs) within the used CellChatDB\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for assess the results in `object@var.features[[features.name]]`\n#' @param features a vector of features to use. default use all over-expressed genes in `object@var.features[[features.name]]`\n#' @param variable.both variable.both = TRUE will require that both ligand and receptor from one pair are over-expressed;\n#'\n#' variable.both = FALSE will only require that either ligand or receptor from one pair is over-expressed, leading to more over-expressed ligand-receptor interactions (pairs) for further analysis.\n#' @param return.object whether returning a CellChat object. If FALSE, it will return a data frame containing the over-expressed ligand-receptor pairs\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom dplyr select\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, a new element named 'LRsig' will be added into the list `object@LR`\n#' @export\n#'\nidentifyOverExpressedInteractions <- function(object, features.name = \"features\", variable.both = TRUE, features = NULL, return.object = TRUE) {\n gene.use <- row.names(object@data.signaling)\n DB <- object@DB\n if (is.null(features)) {\n if (is.list(object@var.features)) {\n features.sig <- object@var.features[[features.name]] # use the updated CellChat object 12/2020\n } else {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n\n } else {\n features.sig <- features\n }\n\n interaction_input <- DB$interaction\n complex_input <- DB$complex\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n complexSubunits <- complex_input[, grepl(\"subunit\" , colnames(complex_input))]\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (length(intersect(complexsubunitsV, features.sig)) > 0 & all(complexsubunitsV %in% gene.use)) {\n return(x)\n }\n }\n )\n )\n complexSubunits.sig <- complexSubunits[index.sig,]\n\n index.use <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (all(complexsubunitsV %in% gene.use)) {\n return(x)\n }\n }\n )\n )\n complexSubunits.use <- complexSubunits[index.use,]\n\n pairLR <- select(interaction_input, ligand, receptor)\n\n if (variable.both) {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(pairLR),\n FUN = function(x) {\n if (all(unlist(pairLR[x,], use.names = F) %in% c(features.sig, rownames(complexSubunits.sig)))) {\n return(x)\n }\n }\n )\n )\n } else {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(pairLR),\n FUN = function(x) {\n # if (all(unlist(pairLR[x,], use.names = F) %in% c(features.sig, rownames(complexSubunits.sig)))) {\n if (all(unlist(pairLR[x,], use.names = F) %in% c(gene.use, rownames(complexSubunits.use))) & (length(intersect(unlist(pairLR[x,], use.names = F), c(features.sig, rownames(complexSubunits.sig)))) > 0)) {\n return(x)\n }\n }\n )\n )\n }\n\n pairLRsig <- interaction_input[index.sig, ]\n object@LR$LRsig <- pairLRsig\n cat(\"The number of highly variable ligand-receptor pairs used for signaling inference is\", nrow(pairLRsig), '\\n')\n if (return.object) {\n return(object)\n } else {\n return(pairLRsig)\n }\n}\n\n\n#' Smooth the gene expression data\n#'\n#' A diffusion process is used to smooth genes’ expression values based on their neighbors’ defined in a high-confidence experimentally validated protein-protein network.\n#'\n#' This function is useful when analyzing single-cell data with shallow sequencing depth because the projection reduces the dropout effects of signaling genes, in particular for possible zero expression of subunits of ligands/receptors\n#'\n#' @param object CellChat object\n#' @param method When method = \"netSmooth\", smoothing a gene’s expression values based on its neighbors defined in a high-confidence experimentally validated protein-protein network.\n#' @param adj adjacency matrix of protein-protein interaction network to use\n#' @param alpha numeric in [0,1] alpha = 0: no smoothing; a larger value alpha results in increasing levels of smoothing.\n#' @param normalizeAdjMatrix how to normalize the adjacency matrix\n#' possible values are 'rows' (in-degree)\n#' and 'columns' (out-degree)\n#' @return a smoothed gene expression matrix\n#' @export\n#'\n# This function is adapted from https://github.com/BIMSBbioinfo/netSmooth\nsmoothData <- function(object, method = c(\"netSmooth\"), adj = NULL, alpha=0.5, normalizeAdjMatrix=c('rows','columns')){\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n stop(\"`object@data.smooth` is missing. Please update the CellChat object via `updateCellChat`! \\n\")\n }\n data <- as.matrix(object@data.signaling)\n normalizeAdjMatrix <- match.arg(normalizeAdjMatrix)\n if (method == \"netSmooth\") {\n if (is.null(adj)) stop(\"Please provide the `adj`. \\n\")\n stopifnot(is(adj, 'matrix') | is(adj, 'sparseMatrix'))\n stopifnot((is.numeric(alpha) & (alpha > 0 & alpha < 1)))\n if(sum(Matrix::rowSums(adj)==0)>0) stop(\"PPI cannot have zero rows/columns\")\n if(sum(Matrix::colSums(adj)==0)>0) stop(\"PPI cannot have zero rows/columns\")\n }\n if(is.numeric(alpha)) {\n if(alpha<0 | alpha > 1) {\n stop('alpha must be between 0 and 1')\n }\n data.projected <- projectAndRecombine(data, adj, alpha,normalizeAdjMatrix=normalizeAdjMatrix)\n } else stop(\"unsupported alpha value: \", class(alpha))\n object@data.smooth <- data.projected\n return(object)\n}\n\n#' Perform network projecting on network when the network genes and the\n#' experiment genes aren't exactly the same.\n#'\n#' The gene network might be defined only on a subset of genes that are\n#' measured in any experiment. Further, an experiment might not measure all\n#' genes that are present in the network. This function projects the experiment\n#' data onto the gene space defined by the network prior to projecting. Then,\n#' it projects the projected data back into the original dimansions.\n#'\n#' @param gene_expression gene expession data to be projected\n#' [N_genes x M_samples]\n#' @param adj_matrix adjacenty matrix of network to perform projecting over.\n#' Will be column-normalized.\n#' Rownames and colnames should be genes.\n#' @param alpha network projecting parameter (1 - restart probability in random\n#' walk model.\n#' @param projecting.function must be a function that takes in data, adjacency\n#' matrix, and alpha. Will be used to perform the\n#' actual projecting.\n#' @param normalizeAdjMatrix which dimension (rows or columns) should the\n#' adjacency matrix be normalized by. rows\n#' corresponds to in-degree, columns to\n#' out-degree.\n#' @return matrix with network-projected gene expression data. Genes that are\n#' not present in projecting network will retain original values.\n#' @keywords internal\n#'\nprojectAndRecombine <- function(gene_expression, adj_matrix, alpha,\n projecting.function=randomWalkBySolve,\n normalizeAdjMatrix=c('rows','columns')) {\n normalizeAdjMatrix <- match.arg(normalizeAdjMatrix)\n gene_expression_in_A_space <- projectOnNetwork(gene_expression,rownames(adj_matrix))\n gene_expression_in_A_space_project <- projecting.function(gene_expression_in_A_space, adj_matrix, alpha, normalizeAdjMatrix)\n gene_expression_project <- projectFromNetworkRecombine(gene_expression, gene_expression_in_A_space_project)\n return(gene_expression_project)\n}\n\n\n#' Project the gene expression matrix onto a lower space\n#' of the genes defined in the projecting network\n#' @param gene_expression gene expression matrix\n#' @param new_features the genes in the network, on which to project\n#' the gene expression matrix\n#' @param missing.value value to assign to genes that are in network,\n#' but missing from gene expression matrix\n#' @return the gene expression matrix projected onto the gene space defined by new_features\n#' @keywords internal\nprojectOnNetwork <- function(gene_expression, new_features, missing.value=0) {\n # data_in_new_space = matrix(rep(0, length(new_features)*dim(gene_expression)[2]),nrow=length(new_features))\n data_in_new_space = matrix(0, ncol=dim(gene_expression)[2], nrow=length(new_features))\n rownames(data_in_new_space) <- new_features\n colnames(data_in_new_space) <- colnames(gene_expression)\n genes_in_both <- intersect(rownames(data_in_new_space),rownames(gene_expression))\n data_in_new_space[genes_in_both,] <- gene_expression[genes_in_both,]\n genes_only_in_network <- setdiff(new_features, rownames(gene_expression))\n data_in_new_space[genes_only_in_network,] <- missing.value\n return(data_in_new_space)\n}\n\n#' project data on graph by solving the linear equation (I - alpha*A) * E_sm = E * (1-alpha)\n\n#' @param E initial data matrix [NxM]\n#' @param A adjacency matrix of graph to network project on will be column-normalized.\n#' @param alpha projecting coefficient (1 - restart probability of random walk)\n#' @return network-projected gene expression\n#' @keywords internal\nrandomWalkBySolve <- function(E, A, alpha, normalizeAjdMatrix=c('rows','columns')) {\n normalizeAjdMatrix <- match.arg(normalizeAjdMatrix)\n if (normalizeAjdMatrix=='rows') {\n Anorm <- l1NormalizeRows(A)\n } else if (normalizeAjdMatrix=='columns') {\n Anorm <- l1NormalizeColumns(A)\n }\n eye <- diag(dim(A)[1])\n AA <- eye - alpha*Anorm\n BB <- (1-alpha) * E\n return(solve(AA, BB))\n}\n\n#' Column-normalize a sparse, symmetric matrix (using the l1 norm) so that each\n#' column sums to 1.\n#'\n#' @param A matrix\n#' @usage l1NormalizeColumns(A)\n#' @return column-normalized sparse matrix object\n#' @keywords internal\nl1NormalizeColumns <- function(A) {\n return(Matrix::t(Matrix::t(A)/Matrix::colSums(A)))\n}\n\n#' Row-normalize a sparse, symmetric matrix (using the l1 norm) so that each\n#' row sums to 1.\n#'\n#' @param A matrix\n#' @usage l1NormalizeRows(A)\n#' @return row-normalized sparse matrix object\n#' @keywords internal\nl1NormalizeRows <- function(A) {\n return(A/Matrix::rowSums(A))\n}\n\n#' Combine gene expression from projected space (that of the network) with the\n#' expression of genes that were not projected (not present in network)\n#' @keywords internal\n#' @param original_expression the non-projected expression\n#' @param projected_expression the projected gene expression, in the space\n#' of the genes defined by the network\n#' @return a matrix in the dimensions of original_expression, where values that\n#' are present in projected_expression are copied from there.\nprojectFromNetworkRecombine <- function(original_expression, projected_expression) {\n data_in_original_space <- original_expression\n genes_in_both <- intersect(rownames(original_expression),rownames(projected_expression))\n data_in_original_space[genes_in_both,] <- as.matrix(projected_expression[genes_in_both,])\n return(data_in_original_space)\n}\n\n\n#' Dimension reduction using PCA\n#'\n#' @param data.use input data (samples in rows, features in columns)\n#' @param do.fast whether do fast PCA\n#' @param dimPC the number of components to keep\n#' @param seed.use set a seed\n#' @param weight.by.var whether use weighted pc.scores\n#' @importFrom stats prcomp\n#' @importFrom irlba irlba\n#' @return\n#' @export\n#'\n#' @examples\nrunPCA <- function(data.use, do.fast = T, dimPC = 50, seed.use = 42, weight.by.var = T) {\n set.seed(seed = seed.use)\n if (do.fast) {\n dimPC <- min(dimPC, ncol(data.use) - 1)\n pca.res <- irlba::irlba(data.use, nv = dimPC)\n sdev <- pca.res$d/sqrt(max(1, nrow(data.use) - 1))\n if (weight.by.var){\n pc.scores <- pca.res$u %*% diag(pca.res$d)\n } else {\n pc.scores <- pca.res$u\n }\n } else {\n dimPC <- min(dimPC, ncol(data.use) - 1)\n pca.res <- stats::prcomp(x = data.use, rank. = dimPC)\n sdev <- pca.res$sdev\n if (weight.by.var) {\n pc.scores <- pca.res$x %*% diag(pca.res$sdev[1:dimPC]^2)\n } else {\n pc.scores <- pca.res$x\n }\n }\n rownames(pc.scores) <- rownames(data.use)\n colnames(pc.scores) <- paste0('PC', 1:ncol(pc.scores))\n return(pc.scores)\n}\n\n\n#' Run UMAP\n#' @param data.use input data matrix\n#' @param n_neighbors This determines the number of neighboring points used in\n#' local approximations of manifold structure. Larger values will result in more\n#' global structure being preserved at the loss of detailed local structure. In general this parameter should often be in the range 5 to 50.\n#' @param n_components The dimension of the space to embed into.\n#' @param metric This determines the choice of metric used to measure distance in the input space.\n#' @param n_epochs the number of training epochs to be used in optimizing the low dimensional embedding. Larger values result in more accurate embeddings. If NULL is specified, a value will be selected based on the size of the input dataset (200 for large datasets, 500 for small).\n#' @param learning_rate The initial learning rate for the embedding optimization.\n#' @param min_dist This controls how tightly the embedding is allowed compress points together.\n#' Larger values ensure embedded points are moreevenly distributed, while smaller values allow the\n#' algorithm to optimise more accurately with regard to local structure. Sensible values are in the range 0.001 to 0.5.\n#' @param spread he effective scale of embedded points. In combination with min.dist this determines how clustered/clumped the embedded points are.\n#' @param set_op_mix_ratio Interpolate between (fuzzy) union and intersection as the set operation used to combine local fuzzy simplicial sets to obtain a global fuzzy simplicial sets.\n#' @param local_connectivity The local connectivity required - i.e. the number of nearest neighbors\n#' that should be assumed to be connected at a local level. The higher this value the more connected\n#' the manifold becomes locally. In practice this should be not more than the local intrinsic dimension of the manifold.\n#' @param repulsion_strength Weighting applied to negative samples in low dimensional embedding\n#' optimization. Values higher than one will result in greater weight being given to negative samples.\n#' @param negative_sample_rate The number of negative samples to select per positive sample in the\n#' optimization process. Increasing this value will result in greater repulsive force being applied, greater optimization cost, but slightly more accuracy.\n#' @param a More specific parameters controlling the embedding. If NULL, these values are set automatically as determined by min. dist and spread.\n#' @param b More specific parameters controlling the embedding. If NULL, these values are set automatically as determined by min. dist and spread.\n#' @param seed.use Set a random seed. By default, sets the seed to 42.\n#' @param metric_kwds,angular_rp_forest,verbose other parameters used in UMAP\n#' @import reticulate\n#' @export\n#'\nrunUMAP <- function(\n data.use,\n n_neighbors = 30L,\n n_components = 2L,\n metric = \"correlation\",\n n_epochs = NULL,\n learning_rate = 1.0,\n min_dist = 0.3,\n spread = 1.0,\n set_op_mix_ratio = 1.0,\n local_connectivity = 1L,\n repulsion_strength = 1,\n negative_sample_rate = 5,\n a = NULL,\n b = NULL,\n seed.use = 42L,\n metric_kwds = NULL,\n angular_rp_forest = FALSE,\n verbose = FALSE){\n if (!reticulate::py_module_available(module = 'umap')) {\n stop(\"Cannot find UMAP, please install through pip (e.g. pip install umap-learn or reticulate::py_install(packages = 'umap-learn')).\")\n }\n set.seed(seed.use)\n reticulate::py_set_seed(seed.use)\n umap_import <- reticulate::import(module = \"umap\", delay_load = TRUE)\n umap <- umap_import$UMAP(\n n_neighbors = as.integer(n_neighbors),\n n_components = as.integer(n_components),\n metric = metric,\n n_epochs = n_epochs,\n learning_rate = learning_rate,\n min_dist = min_dist,\n spread = spread,\n set_op_mix_ratio = set_op_mix_ratio,\n local_connectivity = local_connectivity,\n repulsion_strength = repulsion_strength,\n negative_sample_rate = negative_sample_rate,\n a = a,\n b = b,\n metric_kwds = metric_kwds,\n angular_rp_forest = angular_rp_forest,\n verbose = verbose\n )\n Rumap <- umap$fit_transform\n umap_output <- Rumap(t(data.use))\n colnames(umap_output) <- paste0('UMAP', 1:ncol(umap_output))\n rownames(umap_output) <- colnames(data.use)\n return(umap_output)\n}\n\n.error_if_no_Seurat <- function() {\n if (!requireNamespace(\"Seurat\", quietly = TRUE)) {\n stop(\"Seurat installation required for working with Seurat objects\")\n }\n}\n\n\n#' Color interpolation\n#'\n#' This function is modified from https://rdrr.io/cran/circlize/src/R/utils.R\n#' Colors are linearly interpolated according to break values and corresponding colors through CIE Lab color space (`colorspace::LAB`) by default.\n#' Values exceeding breaks will be assigned with corresponding maximum or minimum colors.\n#'\n#' @param breaks A vector indicating numeric breaks\n#' @param colors A vector of colors which correspond to values in ``breaks``\n#' @param transparency A single value in ``[0, 1]``. 0 refers to no transparency and 1 refers to full transparency\n#' @param space color space in which colors are interpolated. Value should be one of \"RGB\", \"HSV\", \"HLS\", \"LAB\", \"XYZ\", \"sRGB\", \"LUV\", see `colorspace::color-class` for detail.\n#' @importFrom colorspace coords RGB HSV HLS LAB XYZ sRGB LUV hex\n#' @importFrom grDevices col2rgb\n#' @return It returns a function which accepts a vector of numeric values and returns interpolated colors.\n#' @export\n#' @examples\n#' \\dontrun{\n#' col_fun = colorRamp3(c(-1, 0, 1), c(\"green\", \"white\", \"red\"))\n#' col_fun(c(-2, -1, -0.5, 0, 0.5, 1, 2))\n#' }\ncolorRamp3 = function(breaks, colors, transparency = 0, space = \"LAB\") {\n\n if(length(breaks) != length(colors)) {\n stop(\"Length of `breaks` should be equal to `colors`.\\n\")\n }\n\n colors = colors[order(breaks)]\n breaks = sort(breaks)\n\n l = duplicated(breaks)\n breaks = breaks[!l]\n colors = colors[!l]\n\n if(length(breaks) == 1) {\n stop(\"You should have at least two distinct break values.\")\n }\n\n\n if(! space %in% c(\"RGB\", \"HSV\", \"HLS\", \"LAB\", \"XYZ\", \"sRGB\", \"LUV\")) {\n stop(\"`space` should be in 'RGB', 'HSV', 'HLS', 'LAB', 'XYZ', 'sRGB', 'LUV'\")\n }\n\n colors = t(grDevices::col2rgb(colors)/255)\n\n attr = list(breaks = breaks, colors = colors, transparency = transparency, space = space)\n\n if(space == \"LUV\") {\n i = which(apply(colors, 1, function(x) all(x == 0)))\n colors[i, ] = 1e-5\n }\n\n transparency = 1-ifelse(transparency > 1, 1, ifelse(transparency < 0, 0, transparency))[1]\n transparency_str = sprintf(\"%X\", round(transparency*255))\n if(nchar(transparency_str) == 1) transparency_str = paste0(\"0\", transparency_str)\n\n fun = function(x = NULL, return_rgb = FALSE, max_value = 1) {\n if(is.null(x)) {\n stop(\"Please specify `x`\\n\")\n }\n\n att = attributes(x)\n if(is.data.frame(x)) x = as.matrix(x)\n\n l_na = is.na(x)\n if(all(l_na)) {\n return(rep(NA, length(l_na)))\n }\n\n x2 = x[!l_na]\n\n x2 = ifelse(x2 < breaks[1], breaks[1],\n ifelse(x2 > breaks[length(breaks)], breaks[length(breaks)],\n x2\n ))\n ibin = .bincode(x2, breaks, right = TRUE, include.lowest = TRUE)\n res_col = character(length(x2))\n for(i in unique(ibin)) {\n l = ibin == i\n res_col[l] = .get_color(x2[l], breaks[i], breaks[i+1], colors[i, ], colors[i+1, ], space = space)\n }\n res_col = paste(res_col, transparency_str[1], sep = \"\")\n\n if(return_rgb) {\n res_col = t(grDevices::col2rgb(as.vector(res_col), alpha = TRUE)/255)\n return(res_col)\n } else {\n res_col2 = character(length(x))\n res_col2[l_na] = NA\n res_col2[!l_na] = res_col\n\n attributes(res_col2) = att\n return(res_col2)\n }\n }\n\n attributes(fun) = attr\n return(fun)\n}\n\n.restrict_in = function(x, lower, upper) {\n x[x > upper] = upper\n x[x < lower] = lower\n x\n}\n\n# x: vector\n# break1 single value\n# break2 single value\n# rgb1 vector with 3 elements\n# rgb2 vector with 3 elements\n.get_color = function(x, break1, break2, col1, col2, space) {\n\n col1 = colorspace::coords(as(colorspace::sRGB(col1[1], col1[2], col1[3]), space))\n col2 = colorspace::coords(as(colorspace::sRGB(col2[1], col2[2], col2[3]), space))\n\n res_col = matrix(ncol = 3, nrow = length(x))\n for(j in 1:3) {\n xx = (x - break2)*(col2[j] - col1[j]) / (break2 - break1) + col2[j]\n res_col[, j] = xx\n }\n\n res_col = get(space)(res_col)\n res_col = colorspace::coords(as(res_col, \"sRGB\"))\n res_col[, 1] = .restrict_in(res_col[,1], 0, 1)\n res_col[, 2] = .restrict_in(res_col[,2], 0, 1)\n res_col[, 3] = .restrict_in(res_col[,3], 0, 1)\n colorspace::hex(colorspace::sRGB(res_col))\n}\n\n#' Update the cell-cell communication array from a customized cell-cell-communication scores between different cell groups\n#'\n#' Users may also check the `updateCellChatDB` function for integrating other resources or utilizing a custom database\n#'\n#' @param object CellChat object\n#' @param net a data frame with at least five columns named as `source`,`target`,`ligand`,`receptor` and `score`, which defines the customized cell-cell-communication scores between different cell groups.\n#' a p-value column named `pval`, and additional columns named `interaction_name` and `interaction_name_2` can be also provided.\n#' @return a CellChat object with updated slot `net` and slot `DB` if db is not NULL.\n#' @export\n\nupdateCCC_score <- function(object, net) {\n df.net <- net\n if (all(c(\"source\",\"target\",\"ligand\",\"receptor\",\"score\") %in% colnames(df.net)) == FALSE) {\n stop(\"The input `net` must contain at least five columns named as source,target,ligand,receptor,score\")\n }\n if (all(c(\"interaction_name\") %in% colnames(df.net)) == FALSE) {\n df.net$interaction_name <- paste0(toupper(df.net$ligand), \"_\", toupper(df.net$receptor))\n }\n if (all(c(\"interaction_name_2\") %in% colnames(df.net)) == FALSE) {\n df.net$interaction_name_2 <- paste0(df.net$ligand, \" - \", df.net$receptor)\n }\n if (all(c(\"pval\") %in% colnames(df.net)) == FALSE) {\n df.net$pval <- rep(0, nrow(df.net))\n }\n df.net$prob <- df.net$score\n\n LR <- unique(df.net$interaction_name)\n cell.levels <- levels(object@idents)\n numCluster <- length(cell.levels)\n mat.prob.all <- array(0, dim = c(numCluster,numCluster,length(LR)))\n mat.pval.all <- mat.prob.all\n for (i in 1:length(LR)) {\n df.i <- df.net[df.net$interaction_name == LR[i], , drop = FALSE]\n mat.prob <- matrix(0, nrow = numCluster, ncol = numCluster)\n mat.pval <- mat.prob\n for (j in 1:nrow(df.i)) {\n idx.s <- which(df.i$source[j] == cell.levels)\n idx.t <- which(df.i$target[j] == cell.levels)\n mat.prob[idx.s, idx.t] <- df.i$prob[j]\n mat.pval[idx.s, idx.t] <- df.i$pval[j]\n }\n mat.prob.all[,,i] <- mat.prob\n mat.pval.all[,,i] <- mat.pval\n }\n\n dimnames(mat.prob.all) <- list(cell.levels, cell.levels, LR)\n dimnames(mat.pval.all) <- dimnames(mat.prob.all)\n net <- list(\"prob\" = mat.prob.all, \"pval\" = mat.pval.all)\n object@net <- net\n\n return(object)\n}\n\n#' Preprocessing multi-omics data and preparing the L-R database\n#'\n#' @param data.list a list consisting of multi-omics data (e.g., RNA & ADT)\n#' @param db one of the CellChatDB databases: CellChatDB.human, CellChatDB.mouse, CellChatDB.zebrafish\n#' @param do.sparse whether to use sparse format\n#' @export\n#'\npreProcMultiomics <- function(data.list, db, do.sparse = TRUE) {\n # normalize the data\n data.input.rna <- data.list[[1]]\n data.input.adt <- data.list[[2]]\n data.input.rna = data.input.rna/max(data.input.rna)\n data.input.adt = data.input.adt/max(data.input.adt)\n data.input.adt.temp = data.input.adt\n X = data.input.adt\n for (i in 1:nrow(X)) {\n data.input.adt.temp[i,] = (X[i,]-min(X[i,]))/(max(X[i,])-min(X[i,]))\n }\n data.input.adt[data.input.adt.temp < 0.5] <- 0\n if (do.sparse) {\n data.input = rbind(data.input.rna, as(data.input.adt, \"dgCMatrix\"))\n } else {\n data.input = rbind(as.matrix(data.input.rna), as.matrix(data.input.adt))\n }\n\n # create a new L-R database\n proteins <- rownames(data.input.adt)\n geneInfo.subset <- db$geneInfo[db$geneInfo$AntibodyName %in% proteins, ]\n proteins.nonmapping <- setdiff(proteins, geneInfo.subset$AntibodyName)\n if (length(proteins.nonmapping) > 0) {\n warning(cat(\"The following antibodies are not found in `CellChatDB$geneInfo$AntibodyName`: \", toString(proteins.nonmapping), \"! Please manually add them via the function `updateCellChatDB`. \\n\"))\n }\n out <- extractLRfromGenes(geneSet = geneInfo.subset$Symbol, db)\n LR.use <- out$LR.use\n idx <- match(LR.use$ligand, geneInfo.subset$Symbol)\n LR.use$ligand[!is.na(idx)] <- geneInfo.subset$AntibodyName[idx[!is.na(idx)]]\n idx <- match(LR.use$receptor, geneInfo.subset$Symbol)\n LR.use$receptor[!is.na(idx)] <- geneInfo.subset$AntibodyName[idx[!is.na(idx)]]\n\n db.use <- db\n db.use$interaction <- LR.use\n db.use$geneInfo <- dplyr::add_row(db.use$geneInfo, Symbol = geneInfo.subset$AntibodyName)\n\n return(list(data.input = data.input, db.use = db.use))\n}\n\n\n \n"], ["/CellChat/R/database.R", "#' Show the description of CellChatDB databse\n#'\n#' @param CellChatDB CellChatDB databse\n#' @param nrow the number of rows in the plot\n#' @importFrom dplyr group_by summarise n %>%\n#'\n#' @return\n#' @export\n#'\nshowDatabaseCategory <- function(CellChatDB, nrow = 1) {\n interaction_input <- CellChatDB$interaction\n geneIfo <- CellChatDB$geneInfo\n df <- interaction_input %>% group_by(annotation) %>% summarise(value=n())\n #df$group <- factor(df$annotation, levels = unique(df$annotation))\n df$group <- factor(df$annotation, levels = c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\"))\n gg1 <- pieChart(df)\n binary <- (interaction_input$ligand %in% geneIfo$Symbol) & (interaction_input$receptor %in% geneIfo$Symbol)\n df <- data.frame(group = rep(\"Heterodimers\", dim(interaction_input)[1]),stringsAsFactors = FALSE)\n df$group[binary] <- rep(\"Others\",sum(binary),1)\n df <- df %>% group_by(group) %>% summarise(value=n())\n df$group <- factor(df$group, levels = c(\"Heterodimers\",\"Others\"))\n gg2 <- pieChart(df)\n\n kegg <- grepl(\"KEGG\", interaction_input$evidence)\n df <- data.frame(group = rep(\"Literature\", dim(interaction_input)[1]),stringsAsFactors = FALSE)\n df$group[kegg] <- rep(\"KEGG\",sum(kegg),1)\n df <- df %>% group_by(group) %>% summarise(value=n())\n df$group <- factor(df$group, levels = c(\"KEGG\",\"Literature\"))\n gg3 <- pieChart(df)\n\n gg <- cowplot::plot_grid(gg1, gg2, gg3, nrow = nrow, align = \"h\", rel_widths = c(1, 1,1))\n return(gg)\n}\n\n\n#' Plot pie chart\n#'\n#' @param df a dataframe\n#' @param label.size a character\n#' @param color.use the name of the variable in CellChatDB interaction_input\n#' @param title the title of plot\n#' @import ggplot2\n#' @importFrom scales percent\n#' @importFrom dplyr arrange desc mutate\n#' @importFrom ggrepel geom_text_repel\n#' @return\n#' @export\n#'\npieChart <- function(df, label.size = 2.5, color.use = NULL, title = \"\") {\n df %>% arrange(dplyr::desc(value)) %>%\n mutate(prop = scales::percent(value/sum(value))) -> df\n\n gg <- ggplot(df, aes(x=\"\", y=value, fill=group)) +\n geom_bar(stat=\"identity\", width=1) +\n coord_polar(\"y\", start=0)+theme_void() +\n ggrepel::geom_text_repel(aes(label = prop), size= label.size, show.legend = F, position = position_stack(vjust=0.5))\n # ggrepel::geom_text_repel(aes(label = prop), size= label.size, show.legend = F, nudge_x = 0)\n gg <- gg + theme(legend.position=\"bottom\", legend.direction = \"vertical\")\n\n if(!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values=color.use)\n # gg <- gg + scale_color_manual(color.use)\n }\n\n if (!is.null(title)) {\n gg <- gg + guides(fill = guide_legend(title = title))\n }\n gg\n}\n\n\n#' Subset the ligand-receptor interactions for given specific signals in CellChatDB\n#'\n#' @param signaling a character vector\n#' @param pairLR.use a dataframe containing ligand-receptor interactions\n#' @param key the keyword to match\n#' @param matching.exact whether perform exact matching\n#' @param pair.only whether only return ligand-receptor pairs without cofactors\n#' @importFrom future.apply future_sapply\n#' @importFrom dplyr select\n#' @return\n#' @export\nsearchPair <- function(signaling = c(), pairLR.use, key = c(\"pathway_name\",\"ligand\"), matching.exact = FALSE, pair.only = TRUE) {\n key <- match.arg(key)\n pairLR = future.apply::future_sapply(\n X = 1:length(signaling),\n FUN = function(x) {\n if (!matching.exact) {\n index <- grep(signaling[x], pairLR.use[[key]])\n } else {\n index <- which(pairLR.use[[key]] %in% signaling[x])\n }\n if (length(index) > 0) {\n if (pair.only) {\n pairLR <- dplyr::select(pairLR.use[index, ], interaction_name, pathway_name, ligand, receptor)\n } else {\n pairLR <- pairLR.use[index, ]\n }\n return(pairLR)\n } else {\n stop(cat(paste(\"Cannot find \", signaling[x], \".\", \"Please input a correct name!\"),'\\n'))\n }\n }\n )\n if (pair.only) {\n pairLR0 <- vector(\"list\", length(signaling))\n for (i in 1:length(signaling)) {\n pairLR0[[i]] <- matrix(unlist(pairLR[c(4*i-3, 4*i-2, 4*i-1, 4*i)]), ncol=4, byrow=F)\n }\n pairLR <- do.call(rbind, pairLR0)\n dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]][1:4]\n rownames(pairLR) <- pairLR[,1]\n } else {\n pairLR0 <- vector(\"list\", length(signaling))\n for (i in 1:length(signaling)) {\n pairLR0[[i]] <- matrix(unlist(pairLR[(i*ncol(pairLR.use)-(ncol(pairLR.use)-1)):(i*ncol(pairLR.use))]), ncol=ncol(pairLR.use), byrow=F)\n }\n pairLR <- do.call(rbind, pairLR0)\n dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]]\n rownames(pairLR) <- pairLR[,1]\n }\n return(as.data.frame(pairLR, stringsAsFactors = FALSE))\n}\n\n#' Subset CellChatDB databse by only including interactions of interest\n#'\n#' @param CellChatDB CellChatDB databse\n#' @param search a character vector, which is a subset of c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\"); Setting search = NULL & non_protein = FALSE will return all signaling except for \"Non-protein Signaling\".\n#'\n#' When `key` is a vector, the `search` should be a list with the size being `length(key)`, where each element is a character vector.\n#' @param key a character vector and each element should be one of the column names of the interaction_input from CellChatDB.\n#' @param non_protein whether to use the non-protein signaling for CellChat analysis. By default, non_protein = FALSE because most of non-protein signaling are the special synaptic signaling interactions that can only be used when inferring neuron-neuron communication.\n#'\n#' @return\n#' @export\n#'\nsubsetDB <- function(CellChatDB, search = c(), key = \"annotation\", non_protein = FALSE) {\n interaction_input <- CellChatDB$interaction\n if (is.null(search) & non_protein == FALSE & any(key == \"annotation\")) {\n search <- c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\")\n } else if (is.null(search) & non_protein == TRUE & any(key == \"annotation\")) {\n search <- c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\")\n }\n\n if (\"Non-protein Signaling\" %in% unlist(search)) {\n non_protein = TRUE\n message(\"The non-protein signaling is now included for CellChat analysis, which is usually used for neuron-neuron and metabolic communication!\")\n }\n if (non_protein == FALSE) {\n interaction_input <- subset(interaction_input, annotation != \"Non-protein Signaling\")\n }\n if (all(key %in% colnames(interaction_input)) == FALSE) {\n stop(\"Each element of the `key` should be one of the column names of the interaction_input from CellChatDB\")\n }\n if (length(key) == 1) {\n interaction_input <- interaction_input[interaction_input[[key]] %in% search, ]\n } else {\n if (!is.list(search)) {\n stop(\"When `key` is a vector, the `search` should be a list. \")\n }\n idx.use <- TRUE\n for (i in 1:length(key)) {\n idx.use <- idx.use & (interaction_input[[key[i]]] %in% search[[i]])\n }\n interaction_input <- interaction_input[idx.use, , drop = FALSE]\n }\n\n CellChatDB$interaction <- interaction_input\n return(CellChatDB)\n}\n\n\n\n#' Extract the genes involved in CellChatDB\n#'\n#' @param CellChatDB CellChatDB databse used in the analysis\n#'\n#' @return\n#' @export\n#' @importFrom dplyr select\n#'\nextractGene <- function(CellChatDB) {\n interaction_input <- CellChatDB$interaction\n complex_input <- CellChatDB$complex\n cofactor_input <- CellChatDB$cofactor\n geneIfo <- CellChatDB$geneInfo\n # check whether all gene names in complex_input and cofactor_input are official gene symbol in geneIfo\n checkGeneSymbol(geneSet = unlist(complex_input), geneIfo)\n checkGeneSymbol(geneSet = unlist(cofactor_input), geneIfo)\n\n geneL <- unique(interaction_input$ligand)\n geneR <- unique(interaction_input$receptor)\n geneLR <- c(geneL, geneR)\n checkGeneSymbol(geneSet = geneLR[geneLR %in% rownames(complex_input) == \"FALSE\"], geneIfo)\n\n geneL <- extractGeneSubset(geneL, complex_input, geneIfo)\n geneR <- extractGeneSubset(geneR, complex_input, geneIfo)\n geneLR <- c(geneL, geneR)\n\n cofactor <- c(interaction_input$agonist, interaction_input$antagonist, interaction_input$co_A_receptor, interaction_input$co_I_receptor)\n cofactor <- unique(cofactor[cofactor != \"\"])\n cofactorsubunits <- select(cofactor_input[match(cofactor, rownames(cofactor_input), nomatch=0),], starts_with(\"cofactor\"))\n cofactorsubunitsV <- unlist(cofactorsubunits)\n geneCofactor <- unique(cofactorsubunitsV[cofactorsubunitsV != \"\"])\n\n gene.use <- unique(c(geneLR, geneCofactor))\n return(gene.use)\n\n}\n\n\n#' Extract the gene name\n#'\n#' @param geneSet gene set\n#' @param complex_input complex in CellChatDB databse\n#' @param geneIfo official gene symbol\n#'\n#' @return\n#' @importFrom dplyr select starts_with\n#' @export\nextractGeneSubset <- function(geneSet, complex_input, geneIfo) {\n complex <- geneSet[which(geneSet %in% geneIfo$Symbol == \"FALSE\")]\n geneSet <- intersect(geneSet, geneIfo$Symbol)\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complex <- intersect(complex, rownames(complexsubunits))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n geneSet <- unique(c(geneSet, complexsubunitsV))\n return(geneSet)\n}\n\n\n#' Extract the signaling gene names from ligand-receptor pairs\n#'\n#' @param pairLR data frame must contain columns named `ligand` and `receptor`\n#' @param object a CellChat object\n#' @param complex_input complex in CellChatDB databse\n#' @param geneInfo official gene symbol\n#' @param combined whether combining the ligand genes and receptor genes\n#'\n#' @return\n#' @export\nextractGeneSubsetFromPair <- function(pairLR, object = NULL, complex_input = NULL, geneInfo = NULL, combined = TRUE) {\n if (!all(c(\"ligand\", \"receptor\") %in% colnames(pairLR))) {\n stop(\"The input data frame must contain columns named `ligand` and `receptor`\")\n }\n if (is.null(object)) {\n if (is.null(complex_input) | is.null(geneInfo)) {\n stop(\"Either `object` or `complex_input` and `geneInfo` should be provided!\")\n } else {\n complex <- complex_input\n }\n } else {\n complex <- object@DB$complex\n geneInfo <- object@DB$geneInfo\n }\n geneL <- unique(pairLR$ligand)\n geneR <- unique(pairLR$receptor)\n geneL <- extractGeneSubset(geneL, complex, geneInfo)\n geneR <- extractGeneSubset(geneR, complex, geneInfo)\n geneLR <- c(geneL, geneR)\n if (combined) {\n return(geneLR)\n } else {\n return(list(geneL = geneL, geneR = geneR))\n }\n}\n\n\n\n#' check the official Gene Symbol\n#'\n#' @param geneSet gene set to check\n#' @param geneIfo official Gene Symbol\n#' @return\n#' @export\n#'\ncheckGeneSymbol <- function(geneSet, geneIfo) {\n geneSet <- unique(geneSet[geneSet != \"\"])\n genes_notOfficial <- geneSet[geneSet %in% geneIfo$Symbol == \"FALSE\"]\n if (length(genes_notOfficial) > 0) {\n cat(\"Issue identified!! Please check the official Gene Symbol of the following genes: \", \"\\n\", genes_notOfficial, \"\\n\")\n }\n return(FALSE)\n}\n\n#' Extract L-R pairs associated with a given gene set\n#'\n#' @param geneSet a vector of genes\n#' @param db one of the CellChatDB databases (e.g., CellChatDB.human, CellChatDB.mouse...)\n#' @export\n#'\nextractLRfromGenes <- function(geneSet, db) {\n interaction_input <- db$interaction\n complex_input <- db$complex\n geneIfo <- db$geneInfo\n geneSet1 <- intersect(geneSet, geneIfo$Symbol)\n idx1 <- which(interaction_input$ligand %in% geneSet1)\n idx2 <- which(interaction_input$receptor %in% geneSet1)\n idx <- unique(c(idx1, idx2)); idx <- setdiff(idx,0)\n LR.use <- interaction_input[idx,,drop = FALSE]\n genes.use <- extractGeneSubsetFromPair(LR.use, complex_input = complex_input, geneInfo = geneIfo)\n return(list(LR.use = LR.use, genes.use=genes.use))\n}\n\n\n#' Update CellChatDB by integrating new L-R pairs from other resources or adding more information\n#'\n#' @param db a data frame of the customized ligand-receptor database with at least two columns named as `ligand` and `receptor`. We highly suggest users to provide a column of pathway information named `pathway_name` associated with each L-R pair.\n#' Other optional columns include `interaction_name` and `interaction_name_2`. The default columns of CellChatDB can be checked via `colnames(CellChatDB.human$interaction)`.\n#' @param gene_info a data frame with at least one column named as `Symbol`. \"When setting gene_info = NULL, the input `species_target` should be provided: either `human` or `mouse`.\n#' @param other_info a list consisting of other information including a dataframe named as `complex` and a dataframe named as `cofactor`. This additional information is not necessary. If other_info is provided, the `complex` and `cofactor` are dataframes with defined rownames.\n#' @param gene_info_columnNew a data frame with at least two columns named as `Symbol` and `AntibodyName`, which will add a new column named `AntibodyName` into `db$geneInfo`.\n#' @param trim.pathway whether to delete the interactions with missing pathway names when the column `pathway_name` is provided in `db`.\n#' @param merged whether merging the input database with the existing CellChatDB. setting merged = TRUE, the input `species_target` should be provided: either `human` or `mouse`.\n#' @param species_target the target species for output: either `human` or `mouse`.\n#' @return a list consisting of the customized L-R database for further CellChat analysis\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # integrating new L-R pairs from other resources or utilizing a custom database `db.user`\n#' db.new <- updateCellChatDB(db = db.user, gene_info = gene_info)\n#' db.new <- updateCellChatDB(db = db.user, gene_info = NULL, species_target = \"human\")\n#' # Alternatively, users can integrate the customized L-R pairs into the built-in CellChatDB\n#' db.new <- updateCellChatDB(db = db.user, merged = TRUE, species_target = \"human\")\n#' # Add new columns (e.g., AntibodyName) into gene_info\n#' db.new.human <- updateCellChatDB(db = CellChatDB.human$interaction, gene_info = CellChatDB.human$geneInfo, other_info=list(complex = CellChatDB.human$complex, cofactor = CellChatDB.human$cofactor),gene_info_columnNew = gene_info_columnNew)\n#'\n#' # Users can now use this new database in CellChat analysis\n#' cellchat@DB <- db.new\n#'}\nupdateCellChatDB <- function(db, gene_info = NULL, other_info = NULL, gene_info_columnNew = NULL, trim.pathway = FALSE, merged = FALSE, species_target = NULL) {\n db <- dplyr::mutate(db, across(everything(), as.character))\n if (all(c(\"ligand\",\"receptor\") %in% colnames(db)) == FALSE) {\n stop(\"The input `db` must contain at least two columns named as ligand,receptor\")\n }\n if (all(c(\"pathway_name\") %in% colnames(db)) == FALSE) {\n warning(\"The pathway_name associated with each L-R pair is not provided in `db`. We suggest to provide this information so that the versatile functionalities of CellChat can be fully used! \\n\")\n db$pathway_name <- rep(\"\", nrow(db))\n } else {\n pathway.missing <- which(db$pathway_name == \"\")\n if (length(pathway.missing) > 0) {\n if (trim.pathway) {\n cat(paste0(\"The pathway names of \", length(pathway.missing) ,\" interactions are missing and the corresponding interactions are now deleted. \\n\"))\n db <- db[-pathway.missing, , drop = FALSE]\n } else {\n warning(paste0(\"The pathway names of \", length(pathway.missing) ,\" interactions are missing and it may cause error in the downstream analysis. Setting `trim.pathway = TRUE` to avoid such possible errors. \\n\"))\n }\n }\n }\n if (all(c(\"interaction_name\") %in% colnames(db)) == FALSE) {\n db$interaction_name <- paste0(toupper(db$ligand), \"_\", toupper(db$receptor))\n }\n if (all(c(\"interaction_name_2\") %in% colnames(db)) == FALSE) {\n db$interaction_name_2 <- paste0(db$ligand, \" - \", db$receptor)\n }\n if (\"agonist\" %in% colnames(db) == FALSE) {\n db$agonist <- rep(\"\", nrow(db))\n }\n if (\"antagonist\" %in% colnames(db) == FALSE) {\n db$antagonist <- rep(\"\", nrow(db))\n }\n if (\"co_A_receptor\" %in% colnames(db) == FALSE) {\n db$co_A_receptor <- rep(\"\", nrow(db))\n }\n if (\"co_I_receptor\" %in% colnames(db) == FALSE) {\n db$co_I_receptor <- rep(\"\", nrow(db))\n }\n ## construct database\n idx.remove <- duplicated(db$interaction_name)\n if (sum(idx.remove) > 0) {\n warning(paste0(sum(idx.remove), \" duplicated interaction_names are identified and the corresponding interactions are now deleted. \\n\"))\n db <- db[-which(idx.remove), ]\n }\n\n # build the interaction file\n interaction_input <- db\n rownames(interaction_input) <- interaction_input$interaction_name\n cols.default <- c(\"interaction_name\",\"pathway_name\",\"ligand\",\"receptor\",\"agonist\",\"antagonist\",\"co_A_receptor\",\"co_I_receptor\",\"annotation\",\"interaction_name_2\")\n cols.common <- intersect(cols.default,colnames(interaction_input))\n cols.specific <- setdiff(colnames(interaction_input), cols.default)\n interaction_input <- dplyr::select(interaction_input, c(cols.common, cols.specific))\n\n # build the complex file\n if (!is.null(other_info)) {\n if (\"complex\" %in% names(other_info) == TRUE) {\n complex_input <- other_info$complex\n if (all(colnames(complex_input) %in% paste0(\"subunit_\", seq_len(100))) == FALSE) {\n stop(\"The colnames of the input `other_info$complex` should be `subunit_1`,`subunit_2`,...\")\n }\n } else {\n complex_input <- data.frame()\n }\n # build the cofactor file\n if (\"cofactor\" %in% names(other_info) == TRUE) {\n cofactor_input <- other_info$cofactor\n if (all(colnames(cofactor_input) %in% paste0(\"cofactor\", seq_len(100))) == FALSE) {\n stop(\"The colnames of the input `other_info$cofactor` should be `cofactor1`,`cofactor2`,...\")\n }\n } else {\n cofactor_input <- data.frame()\n }\n } else {\n complex_input <- data.frame()\n cofactor_input <- data.frame()\n }\n\n # build the geneInfo file\n if (!is.null(gene_info)) {\n if (\"Symbol\" %in% colnames(gene_info) == FALSE) {\n stop(\"The input `gene_info` must contain at least one column named as `Symbol`\")\n }\n } else {\n if (is.null(species_target)) {\n stop(\"When setting gene_info = NULL, the input `species_target` should be provided: either `human` or `mouse`. \")\n }\n if (species_target == \"human\") {\n gene_info <- CellChatDB.human$geneInfo\n } else if (species_target == \"mouse\") {\n gene_info <- CellChatDB.mouse$geneInfo\n }\n }\n geneInfo_input <- gene_info\n\n if (merged == TRUE) {\n if (is.null(species_target)) {\n stop(\"When setting merged = TRUE, the input `species_target` should be provided: either `human` or `mouse`. \")\n }\n if (species_target == \"human\") {\n db.cellchat <- CellChatDB.human\n cat(\"Starting to merge the input database with CellChatDB.human... \\n\")\n } else if (species_target == \"mouse\") {\n db.cellchat <- CellChatDB.mouse\n cat(\"Starting to merge the input database with CellChatDB.mouse... \\n\")\n }\n\n # build the interaction file\n interaction_input.cellchat <- db.cellchat$interaction\n interaction_input.cellchat$source.merged <- \"CellChatDB\"\n interaction_input$source.merged <- \"User\"\n cols.common <- intersect(colnames(interaction_input), colnames(interaction_input.cellchat))\n interaction_input <- interaction_input[, cols.common]\n interaction_input.cellchat <- interaction_input.cellchat[, cols.common]\n interaction_input.merged <- rbind(interaction_input.cellchat, interaction_input)\n idx.remove <- duplicated(interaction_input.merged$interaction_name)\n if (sum(idx.remove) > 0) {\n interaction_input.merged <- interaction_input.merged[-which(idx.remove), ]\n }\n\n # build the complex file\n complex_input.cellchat <- db.cellchat$complex\n num.subunit <- max(ncol(complex_input), ncol(complex_input.cellchat))\n if (ncol(complex_input) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(complex_input)))\n complex_input <- cbind(complex_input, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(complex_input)))))\n colnames(complex_input) <- paste0(\"subunit_\", seq_len(num.subunit))\n }\n if (ncol(complex_input.cellchat) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(complex_input.cellchat)))\n complex_input.cellchat <- cbind(complex_input.cellchat, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(complex_input.cellchat)))))\n colnames(complex_input.cellchat) <- paste0(\"subunit_\", seq_len(num.subunit))\n }\n complex_input.merged <- rbind(complex_input.cellchat, complex_input)\n idx.remove <- duplicated(rownames(complex_input.merged))\n if (sum(idx.remove) > 0) {\n complex_input.merged <- complex_input.merged[-which(idx.remove), ]\n }\n\n # build the cofactor file\n cofactor_input.cellchat <- db.cellchat$cofactor\n num.subunit <- max(ncol(cofactor_input), ncol(cofactor_input.cellchat))\n if (ncol(cofactor_input) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(cofactor_input)))\n cofactor_input <- cbind(cofactor_input, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(cofactor_input)))))\n colnames(cofactor_input) <- paste0(\"cofactor\", seq_len(num.subunit))\n }\n if (ncol(cofactor_input.cellchat) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(cofactor_input.cellchat)))\n cofactor_input.cellchat <- cbind(cofactor_input.cellchat, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(cofactor_input.cellchat)))))\n colnames(cofactor_input.cellchat) <- paste0(\"cofactor\", seq_len(num.subunit))\n }\n cofactor_input.merged <- rbind(cofactor_input.cellchat, cofactor_input)\n idx.remove <- duplicated(rownames(cofactor_input.merged))\n if (sum(idx.remove) > 0) {\n cofactor_input.merged <- cofactor_input.merged[-which(idx.remove), ]\n }\n\n interaction_input <- interaction_input.merged\n complex_input <- complex_input.merged\n cofactor_input <- cofactor_input.merged\n }\n\n if (!is.null(gene_info_columnNew)) {\n checkGeneSymbol(gene_info_columnNew$Symbol, geneInfo_input)\n idx <- match(gene_info_columnNew$Symbol, geneInfo_input$Symbol)\n geneInfo_input$AntibodyName <- NA\n geneInfo_input$AntibodyName[idx[!is.na(idx)]] <- gene_info_columnNew$AntibodyName[!is.na(idx)]\n }\n db.new <- list()\n db.new$interaction <- interaction_input\n db.new$complex <- complex_input\n db.new$cofactor <- cofactor_input\n db.new$geneInfo <- geneInfo_input\n\n return(db.new)\n}\n"], ["/CellChat/R/CellChat_class.R", "\n#' The CellChat Class\n#'\n#' The CellChat object is created from a single-cell transcriptomic data matrix, Seurat V3 or SingleCellExperiment object.\n#' When inputting an data matrix, it takes a digital data matrices as input. Genes should be in rows and cells in columns. rownames and colnames should be included.\n#' The class provides functions for data preprocessing, intercellular communication network inference, communication network analysis, and visualization.\n#'\n#'\n#'# Class definitions\n#' @importFrom methods setClassUnion\n#' @importClassesFrom Matrix dgCMatrix\nsetClassUnion(name = 'AnyMatrix', members = c(\"matrix\", \"dgCMatrix\"))\nsetClassUnion(name = 'AnyFactor', members = c(\"factor\", \"list\"))\n\n#' The key slots used in the CellChat object are described below.\n#'\n#' @slot data.raw raw count data matrix\n#' @slot data normalized data matrix for CellChat analysis (Genes should be in rows and cells in columns)\n#' @slot data.signaling a subset of normalized matrix only containing signaling genes\n#' @slot data.scale scaled data matrix\n#' @slot data.smooth smoothed data\n#' @slot images a list of information of spatial transcriptomics data\n#' @slot net a three-dimensional array P (K×K×N), where K is the number of cell groups and N is the number of ligand-receptor pairs. Each row of P indicates the communication probability originating from the sender cell group to other cell groups.\n#' @slot netP a three-dimensional array representing cel-cell communication networks on a signaling pathway level\n#' @slot DB ligand-receptor interaction database used in the analysis (a subset of CellChatDB)\n#' @slot LR a list of information related with ligand-receptor pairs\n#' @slot meta data frame storing the information associated with each cell\n#' @slot idents a factor defining the cell identity used for all analysis. It becomes a list for a merged CellChat object\n#' @slot var.features A list: one element is a vector consisting of the identified over-expressed signaling genes; one element is a data frame returned from the differential expression analysis\n#' @slot dr List of the reduced 2D coordinates, one per method, e.g., umap/tsne/dm\n#' @slot options List of miscellaneous data, such as parameters used throughout analysis, and a indicator whether the CellChat object is a single or merged\n#'\n#' @exportClass CellChat\n#' @importFrom Rcpp evalCpp\n#' @importFrom methods setClass\n# #' @useDynLib CellChat\nCellChat <- methods::setClass(\"CellChat\",\n slots = c(data.raw = 'AnyMatrix',\n data = 'AnyMatrix',\n data.signaling = \"AnyMatrix\",\n data.scale = \"matrix\",\n data.smooth = \"AnyMatrix\",\n images = \"list\",\n net = \"list\",\n netP = \"list\",\n meta = \"data.frame\",\n idents = \"AnyFactor\",\n DB = \"list\",\n LR = \"list\",\n var.features = \"list\",\n dr = \"list\",\n options = \"list\")\n)\n#' show method for CellChat\n#'\n#' @param CellChat object\n#' @param show show the object\n#' @param object object\n#' @docType methods\n#'\nsetMethod(f = \"show\", signature = \"CellChat\", definition = function(object) {\n if (object@options$mode == \"single\") {\n cat(\"An object of class\", class(object), \"created from a single dataset\", \"\\n\", nrow(object@data), \"genes.\\n\", ncol(object@data), \"cells. \\n\")\n } else if (object@options$mode == \"merged\") {\n cat(\"An object of class\", class(object), \"created from a merged object with multiple datasets\", \"\\n\", nrow(object@data.signaling), \"signaling genes.\\n\", ncol(object@data.signaling), \"cells. \\n\")\n }\n if (object@options$datatype == \"RNA\") {\n cat(\"CellChat analysis of single cell RNA-seq data! \\n\")\n } else {\n cat(\"CellChat analysis of\", object@options$datatype, \"data! The input spatial locations are \\n\")\n print(head(object@images$coordinates))\n }\n\n\n invisible(x = NULL)\n})\n\n\n\n#' Create a new CellChat object from a data matrix, Seurat or SingleCellExperiment object\n#'\n#' @param object a normalized (NOT count) data matrix (genes by cells), Seurat or SingleCellExperiment object\n#' @param meta a data frame (rows are cells with rownames) consisting of cell information, which will be used for defining cell groups.\n#' If input is a Seurat or SingleCellExperiment object, the meta data in the object will be used\n#' @param group.by a char name of the variable in meta data, defining cell groups.\n#' If input is a data matrix and group.by is NULL, the input `meta` should contain a column named 'labels',\n#' If input is a Seurat or SingleCellExperiment object, USER must provide `group.by` to define the cell groups. e.g, group.by = \"ident\" for Seurat object\n#' @param datatype By default datatype = \"RNA\"; when running CellChat on spatial imaging data, set datatype = \"spatial\" and input `spatial.factors`\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param spatial.factors a data frame containing two distance factors `ratio` and `tol`, which is dependent on spatial transcriptomics technologies (and specific datasets).\n#'\n#' USER must input this data frame when datatype = \"spatial\". spatial.factors must contain an element named `ratio`, which is the conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns). For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates,\n#'\n#' and another element named `tol`, which is the tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um. If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the cell center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance. Of note, CellChat does not need an accurate tolerance factor, which is used for determining whether considering the cell-pair as spatially proximal if their distance is greater than `interaction.range` but smaller than \"`interaction.range` + `tol`\".\n#'\n#'\n#' @param assay Assay to use when the input is a Seurat or SingleCellExperiment object. NB: The data in the `integrated` assay in Seurat is not suitable for CellChat analysis because it contains negative values.\n#' @param do.sparse whether use sparse format\n#'\n#' @return\n#' @export\n#' @importFrom methods as new\n#' @examples\n#' \\dontrun{\n#' Create a CellChat object from single-cell transcriptomics data\n#' # Input is a data matrix\n#' ## create a dataframe consisting of the cell labels\n#' meta = data.frame(labels = cell.labels, row.names = names(cell.labels))\n#' cellChat <- createCellChat(object = data.input, meta = meta, group.by = \"labels\")\n#'\n#' # input is a Seurat object\n#' ## use the default cell identities of Seurat object\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"ident\", assay = \"RNA\")\n#' ## use other meta information as cell groups\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"seurat.clusters\")\n#'\n#' # input is a SingleCellExperiment object\n#' cellChat <- createCellChat(object = sce.obj, group.by = \"sce.clusters\")\n#'\n#' # input is a AnnData object\n#' sce <- zellkonverter::readH5AD(file = \"adata.h5ad\")\n#' assayNames(sce) # retrieve all the available assays within sce object\n#' counts <- assay(sce, \"X\") # add a new assay entry \"logcounts\" if not available and make sure this is the original count data matrix\n#' library.size <- Matrix::colSums(counts)\n#' logcounts(sce) <- log1p(Matrix::t(Matrix::t(counts)/library.size) * 10000)\n#' meta <- as.data.frame(SingleCellExperiment::colData(sce))\n#' cellChat <- createCellChat(object = sce, group.by = \"sce.clusters\")\n#'\n#'\n#' Create a CellChat object from spatial transcriptomics data\n#' # Input is a data matrix\n#' cellChat <- createCellChat(object = data.input, meta = meta, group.by = \"labels\",\n#' datatype = \"spatial\", coordinates = coordinates, spatial.factors = spatial.factors)\n#'\n#' # input is a Seurat object\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"ident\", assay = \"SCT\",\n#' datatype = \"spatial\", spatial.factors = spatial.factors)\n#'\n#' }\ncreateCellChat <- function(object, meta = NULL, group.by = NULL,\n datatype = c(\"RNA\", \"spatial\"), coordinates = NULL, spatial.factors = NULL,\n assay = NULL, do.sparse = T) {\n datatype <- match.arg(datatype)\n # data matrix as input\n if (inherits(x = object, what = c(\"matrix\", \"Matrix\", \"dgCMatrix\", \"dgRMatrix\",\"CsparseMatrix\"))) {\n print(\"Create a CellChat object from a data matrix\")\n data <- object\n if (is.null(group.by)) {\n group.by <- \"labels\"\n }\n }\n # Seurat object as input\n if (is(object,\"Seurat\")) {\n .error_if_no_Seurat()\n print(\"Create a CellChat object from a Seurat object\")\n if (is.null(assay)) {\n assay = Seurat::DefaultAssay(object)\n if (assay == \"integrated\") {\n warning(\"The data in the `integrated` assay is not suitable for CellChat analysis! Please use the `RNA`, `SCT` or `Spatial` assay! \")\n }\n cat(paste0(\"The `data` slot in the default assay is used. The default assay is \", assay),'\\n')\n }\n if (packageVersion(\"Seurat\") < \"5.0.0\") {\n # data <- Seurat::GetAssayData(object, assay = assay, slot = \"data\") # normalized data matrix\n data <- object[[assay]]@data\n } else {\n data <- object[[assay]]$data\n }\n if (min(data) < 0) {\n stop(\"The data matrix contains negative values. Please ensure the normalized data matrix is used.\")\n }\n if (is.null(meta)) {\n cat(\"The `meta.data` slot in the Seurat object is used as cell meta information\",'\\n')\n meta <- object@meta.data\n meta$ident <- Seurat::Idents(object)\n }\n if (is.null(group.by)) {\n group.by <- \"ident\"\n }\n if (datatype %in% c(\"spatial\")) {\n if (is.null(coordinates)) {\n coordinates <- Seurat::GetTissueCoordinates(object, scale = NULL, cols = c(\"imagerow\", \"imagecol\"))\n }\n }\n\n\n }\n # SingleCellExperiment object as input\n if (is(object,\"SingleCellExperiment\")) {\n print(\"Create a CellChat object from a SingleCellExperiment object\")\n if (is.null(assay)) {\n assay = \"logcounts\"\n }\n if (assay %in% SummarizedExperiment::assayNames(object)) {\n cat(paste0(\"The data in the \", assay, \" assay is used! \"),'\\n')\n data <- SummarizedExperiment::assay(object, assay)\n } else {\n stop(\"SingleCellExperiment object must contain an assay named `logcounts` or the input assay name! Please check the available assaynames via `assayNames(object)`. \\n\")\n }\n if (is.null(meta)) {\n cat(\"The `colData` assay in the SingleCellExperiment object is used as cell meta information\",'\\n')\n meta <- as.data.frame(SingleCellExperiment::colData(object))\n }\n if (is.null(group.by)) {\n stop(\"`group.by` should be defined!\")\n }\n }\n\n if (!inherits(x = data, what = c(\"dgCMatrix\")) & do.sparse) {\n if (inherits(x = data, what = c(\"dgRMatrix\"))) {\n data <- as(data, \"CsparseMatrix\")\n }\n data <- as(data, \"dgCMatrix\")\n }\n\n if (!is.null(meta)) {\n if (inherits(x = meta, what = c(\"matrix\", \"Matrix\",\"DataFrame\"))) {\n meta <- as.data.frame(x = meta)\n }\n if (!is.data.frame(meta)) {\n stop(\"The input `meta` should be a data frame\")\n }\n if (!identical(rownames(meta), colnames(data))) {\n cat(\"The cell barcodes in 'meta' is \", head(rownames(meta)),'\\n')\n warning(\"The cell barcodes in 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of 'mata'!\")\n rownames(meta) <- colnames(data)\n }\n } else {\n meta <- data.frame()\n }\n if (datatype %in% c(\"spatial\")) {\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n if (is.null(spatial.factors) | !(\"ratio\" %in% names(spatial.factors)) | !(\"tol\" %in% names(spatial.factors))) {\n stop(\"spatial.factors with colnames `ratio` and `tol` should be provided!\")\n } else {\n images = list(\"coordinates\" = coordinates,\n \"spatial.factors\" = spatial.factors)\n }\n cat(\"Create a CellChat object from spatial transcriptomics data...\",'\\n')\n } else {\n images <- list()\n }\n\n object <- methods::new(Class = \"CellChat\",\n data = data,\n images = images,\n meta = meta)\n\n if (!is.null(meta) & nrow(meta) > 0) {\n if (!(\"samples\" %in% colnames(meta))) {\n warning(\"The 'meta' data does not have a column named `samples`. We now add this column and all cells are assumed to belong to `sample1`! \\n\")\n meta$samples <- \"sample1\"\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n } else if (is.factor(meta$samples) == FALSE) {\n warning(\"The 'meta$samples' is not a factor. We now force it as a factor! \\n\")\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n }\n\n cat(\"Set cell identities for the new CellChat object\", '\\n')\n if (!(group.by %in% colnames(meta))) {\n stop(\"The 'group.by' is not a column name in the `meta`, which will be used for cell grouping.\")\n }\n object <- setIdent(object, ident.use = group.by) # set \"labels\" as default cell identity\n cat(\"The cell groups used for CellChat analysis are \", toString(levels(object@idents)), '\\n')\n }\n\n object@options$mode <- \"single\"\n object@options$datatype <- datatype\n return(object)\n}\n\n\n#' Merge CellChat objects\n#'\n#' @param object.list A list of multiple CellChat objects\n#' @param add.names A vector containing the name of each dataset\n#' @param merge.data whether merging the data for ALL genes. Default only merges the data of signaling genes\n#' @param cell.prefix whether prefix cell names\n#' @importFrom methods slot new\n#'\n#' @return\n#' @export\n#'\n#' @examples\nmergeCellChat <- function(object.list, add.names = NULL, merge.data = FALSE, cell.prefix = FALSE) {\n if (is.null(add.names)) {\n add.names <- paste(\"Dataset\",1:length(object.list),sep = \"_\")\n }\n slot.name <- c(\"net\", \"netP\", \"idents\" ,\"LR\", \"var.features\", \"images\")\n slot.combined <- vector(\"list\", length(slot.name))\n names(slot.combined) <- slot.name\n for (i in 1:length(slot.name)) {\n object.slot <- vector(\"list\", length(object.list))\n for (j in 1:length(object.list)) {\n object.slot[[j]] <- slot(object.list[[j]], slot.name[i])\n }\n slot.combined[[i]] <- object.slot\n names(slot.combined[[i]]) <- add.names\n }\n\n if (cell.prefix) {\n warning(\"Prefix cell names!\")\n for (i in 1:length(object.list)) {colnames(object.list[[i]]@data) <- paste(colnames(object.list[[i]]@data), add.names[i], sep = \"_\")}\n } else {\n cell.names <- c()\n for (i in 1:length(object.list)) {\n cell.names <- c(cell.names, colnames(object.list[[i]]@data))\n }\n if (sum(duplicated(cell.names))) {\n stop(\"Duplicated cell names were detected across datasets!! Please set cell.prefix = TRUE\")\n }\n }\n\n meta.use <- colnames(object.list[[1]]@meta)\n for (i in 2:length(object.list)) {\n meta.use <- meta.use[meta.use %in% colnames(object.list[[i]]@meta)]\n }\n\n dataset.name <- c()\n cell.names <- c()\n meta.joint <- data.frame()\n for (i in 1:length(object.list)) {\n dataset.name <- c(dataset.name, rep(add.names[i], length(colnames(object.list[[i]]@data))))\n cell.names <- c(cell.names, colnames(object.list[[i]]@data))\n meta.joint <- rbind(meta.joint, object.list[[i]]@meta[ , meta.use, drop = FALSE])\n }\n if (!identical(rownames(meta.joint), cell.names)) {\n cat(\"The cell barcodes in merged 'meta' is \", head(rownames(meta.joint)),'\\n')\n warning(\"The cell barcodes in merged 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of merged 'mata'!\")\n rownames(meta.joint) <- cell.names\n }\n\n #dataset.name <- data.frame(dataset.name = dataset.name, row.names = cell.names)\n meta.joint$datasets <- factor(dataset.name, levels = add.names)\n\n genes.use <- rownames(object.list[[1]]@data)\n for (i in 2:length(object.list)) {\n genes.use <- genes.use[genes.use %in% rownames(object.list[[i]]@data)]\n }\n data.joint <- c()\n for (i in 1:length(object.list)) {\n data.joint <- cbind(data.joint, object.list[[i]]@data[genes.use, ])\n }\n gene.signaling.joint = unique(unlist(lapply(object.list, function(x) rownames(x@data.signaling))))\n data.signaling.joint <- data.joint[rownames(data.joint) %in% gene.signaling.joint, ]\n\n idents.joint <- c()\n idents.levels <- c()\n for (i in 1:length(object.list)) {\n idents.joint <- c(idents.joint, as.character(object.list[[i]]@idents))\n idents.levels <- union(idents.levels, levels(object.list[[i]]@idents))\n }\n names(idents.joint) <- cell.names\n idents.joint <- factor(idents.joint, levels = idents.levels)\n slot.combined$idents$joint <- idents.joint\n\n if (merge.data) {\n message(\"Merge the following slots: 'data','data.signaling','images','net', 'netP','meta', 'idents', 'var.features', 'DB', and 'LR'.\")\n merged.object <- methods::new(\n Class = \"CellChat\",\n data = data.joint,\n data.signaling = data.signaling.joint,\n images = slot.combined$images,\n net = slot.combined$net,\n netP = slot.combined$netP,\n meta = meta.joint,\n idents = slot.combined$idents,\n var.features = slot.combined$var.features,\n LR = slot.combined$LR,\n DB = object.list[[1]]@DB)\n } else {\n message(\"Merge the following slots: 'data.signaling','images','net', 'netP','meta', 'idents', 'var.features' , 'DB', and 'LR'.\")\n merged.object <- methods::new(\n Class = \"CellChat\",\n data.signaling = data.signaling.joint,\n images = slot.combined$images,\n net = slot.combined$net,\n netP = slot.combined$netP,\n meta = meta.joint,\n idents = slot.combined$idents,\n var.features = slot.combined$var.features,\n LR = slot.combined$LR,\n DB = object.list[[1]]@DB)\n }\n merged.object@options$mode <- \"merged\"\n\n datatype.joint <- c()\n for (j in 1:length(object.list)) {\n datatype.joint <- union(datatype.joint, slot(object.list[[j]], \"options\")$datatype)\n }\n if (length(datatype.joint) == 1){\n merged.object@options$datatype <- datatype.joint\n } else {\n message(\"The data types in these objects are \", datatype.joint,'\\n')\n stop(\"Comparison analysis is not suggested for different types of data.\")\n }\n return(merged.object)\n}\n\n\n\n#' Update a single CellChat object\n#'\n#' Update a single previously calculated CellChat object for spatial transcriptomics data analysis (version < 2.1.0)\n#'\n#' Update a single previously calculated CellChat object (version < 1.6.0)\n#'\n#' version < 0.5.0: `object@var.features` is now `object@var.features$features`; `object@net$sum` is now `object@net$weight` if `aggregateNet` has been run.\n#'\n#' version 1.6.0: a `object@images` slot is added and `datatype` is added in `object@options$datatype`\n#'\n#' version 2.1.0: a column named `slices` is added in `meta` data for spatial transcriptomics data analysis.\n#'\n#' version 2.1.1: `images$scale.factors` is changed to `images$spatial.factors` for spatial transcriptomics data analysis.\n#'\n#' version 2.1.2: the column `slices` in `object@meta` is renamed as `samples` in order to identify consistent signaling across samples for cell-cell communication analysis.\n#'\n#' version 2.1.3: the slot `object@data.project` is renamed as `object@data.smooth`.\n#'\n#' @param object CellChat object\n#'\n#' @return a updated CellChat object\n#' @export\n#'\nupdateCellChat <- function(object) {\n DB <- object@DB\n # interaction_input <- DB$interaction\n # if ((\"category\" %in% colnames(interaction_input) == FALSE) & (\"annotation\" %in% colnames(interaction_input) == TRUE)) {\n # message(\"Change the column name `annotation` in object@DB$interaction to `category` since CellChat v2\")\n # colnames(interaction_input) <- plyr::mapvalues(colnames(interaction_input),from = c(\"annotation\"), to = c(\"category\"), warn_missing = TRUE)\n # DB$interaction <- interaction_input\n # }\n if (is.character(object@var.features)) {\n message(\"Update slot 'var.features' from a vector to a list\")\n var.features.new <- list(features = object@var.features)\n } else {\n var.features.new <- object@var.features\n }\n if (\"sum\" %in% names(object@net)) {\n net <- object@net\n net$weight <- net$sum\n } else {\n net <- object@net\n }\n if (!(\"mode\" %in% names(object@options))) {\n object@options$mode <- \"single\"\n }\n if (!(\"datatype\" %in% names(object@options))) {\n object@options$datatype <- \"RNA\"\n images = list()\n } else {\n images = object@images\n }\n meta = object@meta\n if (\"slices\" %in% colnames(meta)) {\n meta$samples <- meta$slices\n meta$slices = NULL\n }\n if (!(\"samples\" %in% colnames(meta))) {\n warning(\"The 'meta' data does not have a column named `samples`. We now add this column and all cells are assumed to belong to `sample1`!\")\n meta$samples <- \"sample1\"\n meta$samples <- factor(meta$samples)\n } else if (is.factor(meta$samples) == FALSE) {\n warning(\"The 'meta$samples' is not a factor. We now force it as a factor!\")\n meta$samples <- factor(meta$samples)\n }\n if (object@options$datatype %in% c(\"spatial\")) {\n if (\"scale.factors\" %in% names(object@images)) {\n images$spatial.factors <- as.data.frame(images$scale.factors)\n images$scale.factors <- NULL\n }\n }\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n data.smooth <- object@data.project\n } else {\n data.smooth <- object@data.smooth\n }\n object.new <- methods::new(\n Class = \"CellChat\",\n data.raw = object@data.raw,\n data = object@data,\n data.signaling = object@data.signaling,\n data.scale = object@data.scale,\n data.smooth = data.smooth,\n images = images,\n net = net,\n netP = object@netP,\n meta = meta,\n idents = object@idents,\n DB = DB,\n LR = object@LR,\n var.features = var.features.new,\n dr = object@dr,\n options = object@options\n )\n return(object.new)\n}\n\n#' Update a CellChat object by lifting up the cell groups to the same cell labels across all datasets\n#'\n#' This function is useful when comparing inferred communications across different datasets with different cellular compositions\n#'\n#' @param object A single or merged CellChat object\n#' @param group.new A char vector giving the cell labels to lift up. The order of cell labels in the vector will be used for setting the new cell identity.\n#'\n#' If the input is a merged CellChat object and group.new = NULL, it will use the cell labels from one dataset with the maximum number of cell groups\n#'\n#' If the input is a single CellChat object, `group.new` must be defined.\n#'\n#' @return a updated CellChat object\n#'\n#' @export\n#'\nliftCellChat <- function(object, group.new = NULL) {\n if (object@options$mode == \"merged\") {\n idents <- object@idents[1:(length(object@idents)-1)]\n if (is.null(group.new)) {\n group.max.all <- unique(unlist(sapply(idents, levels)))\n group.num <- sapply(idents, nlevels)\n group.num.max <- max(group.num)\n group.max <- levels(idents[[which(group.num == group.num.max)]])\n if (length(group.max) != length(group.max.all)) {\n stop(\"CellChat object cannot lift up due to the missing cell groups in any dataset. Please define the parameter `group.new`!\")\n }\n } else {\n group.max <- group.new\n group.num.max <- length(group.new)\n }\n message(paste0(\"The CellChat object will be lifted up using the cell labels \", paste(group.max, collapse=\", \")))\n for (i in 1:length(idents)) {\n cat(\"Update slots object@net, object@netP, object@idents in dataset \", names(object@idents)[i],'\\n')\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net[[i]]\n group.i <- levels(idents[[i]])\n # group.existing <- group.max[group.max %in% group.i]\n group.existing <- group.i[group.i %in% group.max]\n group.existing.index <- which(group.max %in% group.existing)\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max),\n dimnames = list(group.max, group.max))\n values.new[group.existing.index, group.existing.index] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"pairwiseRank\")) {\n for (k in 1:length(values)) {\n values.new1 <- vector(\"list\", group.num.max)\n values.new1[group.existing.index] <- values[[k]]\n temp <- values[[k]][[1]]\n temp$prob <- 0; temp$pval <- 1\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new1[[kk]] <- temp\n }\n names(values.new1) <- group.max\n values[[k]] <- values.new1\n }\n values.new <- vector(\"list\", group.num.max)\n values.new[group.existing.index] <- values\n temp <- lapply(values.new1, function(x) {\n x$prob <- 0; x$pval <- 1\n return(x)\n })\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new[[kk]] <- temp\n }\n names(values.new) <- group.max\n }\n net[[net.j]] <- values.new\n }\n object@net[[i]] <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n netP <- object@netP[[i]]\n for (netP.j in names(netP)) {\n values <- netP[[netP.j]]\n if (netP.j %in% c(\"pathways\")) {\n values.new <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"prob\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"centr\")) {\n for (k in 1:length(values)) {\n values.new <- lapply(values, function(x) {\n values.new2 <- lapply(x, function(x) {\n values.new1 = as.vector(matrix(0, nrow = 1, ncol = group.num.max))\n values.new1[group.existing.index] <- x\n names(values.new1) <- group.max\n return(values.new1)\n })\n names(values.new2) <- names(x)\n return(values.new2)\n })\n names(values.new) <- names(values)\n }\n netP[[netP.j]] <- values.new\n }\n\n }\n object@netP[[i]] <- netP\n # cat(\"Update slot object@idents...\", '\\n')\n # idents[[i]] <- factor(group.max, levels = group.max)\n idents[[i]] <- factor(idents[[i]], levels = group.max)\n }\n object@idents[1:(length(object@idents)-1)] <- idents\n } else {\n if (is.null(group.new)) {\n stop(\"Please define the parameter `group.new`!\")\n } else {\n group.max <- as.character(group.new)\n group.num.max <- length(group.new)\n message(paste0(\"The CellChat object will be lifted up using the cell labels \", paste(group.max, collapse=\", \")))\n }\n cat(\"Update slots object@net, object@netP, object@idents in a single dataset...\", '\\n')\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net\n idents <- object@idents\n group.i <- levels(idents)\n # group.existing <- group.max[group.max %in% group.i]\n group.existing <- group.i[group.i %in% group.max]\n group.existing.index <- which(group.max %in% group.existing)\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max),\n dimnames = list(group.max, group.max))\n values.new[group.existing.index, group.existing.index] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"pairwiseRank\")) {\n for (k in 1:length(values)) {\n values.new1 <- vector(\"list\", group.num.max)\n values.new1[group.existing.index] <- values[[k]]\n temp <- values[[k]][[1]]\n temp$prob <- 0; temp$pval <- 1\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new1[[kk]] <- temp\n }\n names(values.new1) <- group.max\n values[[k]] <- values.new1\n }\n values.new <- vector(\"list\", group.num.max)\n values.new[group.existing.index] <- values\n temp <- lapply(values.new1, function(x) {\n x$prob <- 0; x$pval <- 1\n return(x)\n })\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new[[kk]] <- temp\n }\n names(values.new) <- group.max\n }\n net[[net.j]] <- values.new\n }\n object@net <- net\n\n\n # cat(\"Update slot object@netP...\", '\\n')\n netP <- object@netP\n for (netP.j in names(netP)) {\n values <- netP[[netP.j]]\n if (netP.j %in% c(\"pathways\")) {\n values.new <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"prob\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"centr\")) {\n for (k in 1:length(values)) {\n values.new <- lapply(values, function(x) {\n values.new2 <- lapply(x, function(x) {\n values.new1 = as.vector(matrix(0, nrow = 1, ncol = group.num.max))\n values.new1[group.existing.index] <- x\n names(values.new1) <- group.max\n return(values.new1)\n })\n names(values.new2) <- names(x)\n return(values.new2)\n })\n names(values.new) <- names(values)\n }\n }\n netP[[netP.j]] <- values.new\n }\n object@netP <- netP\n\n # cat(\"Update slot object@idents...\", '\\n')\n idents <- factor(idents, levels = group.max)\n object@idents <- idents\n }\n\n return(object)\n}\n\n\n#' Subset CellChat object using a portion of cells\n#'\n#' @param object A CellChat object (either an object from a single dataset or a merged objects from multiple datasets)\n#' @param cells.use a char vector giving the cell barcodes to subset. If cells.use = NULL, USER must define `idents.use`\n#' @param idents.use a subset of cell groups used for analysis\n#' @param group.by cell group information; default is `object@idents`; otherwise it should be one of the column names of the meta slot\n#' @param invert whether invert the idents.use\n#' @param thresh threshold of the p-value for determining significant interaction. A parameter as an input of the function `computeCommunProbPathway`\n#' @importFrom methods slot new\n#'\n#' @return\n#' @export\n#'\nsubsetCellChat <- function(object, cells.use = NULL, idents.use = NULL, group.by = NULL, invert = FALSE, thresh = 0.05) {\n if (!is.null(idents.use)) {\n if (is.null(group.by)) {\n labels <- object@idents\n if (object@options$mode == \"merged\") {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n level.use0 <- levels(labels)\n level.use <- levels(labels)[levels(labels) %in% unique(labels)]\n\n if (invert) {\n level.use <- level.use[!(level.use %in% idents.use)]\n } else {\n level.use <- level.use[level.use %in% idents.use]\n }\n cells.use.index <- which(as.character(labels) %in% level.use)\n cells.use <- names(labels)[cells.use.index]\n } else if (!is.null(cells.use)) {\n labels <- object@idents\n if (object@options$mode == \"merged\") {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n level.use0 <- levels(labels)\n level.use <- levels(labels)[levels(labels) %in% unique(as.character(labels[cells.use]))]\n cells.use.index <- which(names(labels) %in% cells.use)\n } else {\n stop(\"USER should define either `cells.use` or `idents.use`!\")\n }\n cat(\"The subset of cell groups used for CellChat analysis are \", level.use, '\\n')\n\n if (nrow(object@data) > 0) {\n data.subset <- object@data[, cells.use.index]\n } else {\n data.subset <- matrix(0, nrow = 0, ncol = 0)\n }\n if (nrow(object@data.smooth) > 0) {\n data.smooth.subset <- object@data.smooth[, cells.use.index]\n } else {\n data.smooth.subset <- matrix(0, nrow = 0, ncol = 0)\n }\n data.signaling.subset <- object@data.signaling[, cells.use.index]\n\n meta.subset <- object@meta[cells.use.index, , drop = FALSE]\n\n\n if (object@options$mode == \"merged\") {\n idents <- object@idents[1:(length(object@idents)-1)]\n group.existing <- level.use0[level.use0 %in% level.use]\n group.existing.index <- which(level.use0 %in% level.use)\n net.subset <- vector(\"list\", length = length(object@net))\n netP.subset <- vector(\"list\", length = length(object@netP))\n idents.subset <- vector(\"list\", length = length(idents))\n names(net.subset) <- names(object@net)\n names(netP.subset) <- names(object@netP)\n names(idents.subset) <- names(object@idents[1:(length(object@idents)-1)])\n images.subset <- vector(\"list\", length = length(idents))\n names(images.subset) <- names(object@idents[1:(length(object@idents)-1)])\n\n for (i in 1:length(idents)) {\n cat(\"Update slots object@images, object@net, object@netP, object@idents in dataset \", names(object@idents)[i],'\\n')\n images <- object@images[[i]]\n for (images.j in names(images)) {\n values <- images[[images.j]]\n if (images.j %in% c(\"coordinates\")) {\n values.new <- values[cells.use.index, ]\n images[[images.j]] <- values.new\n }\n if (images.j %in% c(\"distance\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n images[[images.j]] <- values.new\n }\n }\n images.subset[[i]] <- images\n\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net[[i]]\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- values[group.existing.index, group.existing.index, , drop = FALSE]\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n net[[net.j]] <- values.new\n }\n # net[[net.j]] <- values.new\n }\n net.subset[[i]] <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n # netP <- object@netP[[i]]\n # for (netP.j in names(netP)) {\n # values <- netP[[netP.j]]\n # if (netP.j %in% c(\"pathways\")) {\n # values.new <- values\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"prob\")) {\n # values.new <- values[group.existing.index, group.existing.index, ]\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"centr\")) {\n # for (k in 1:length(values)) {\n # values.new <- lapply(values, function(x) {\n # values.new2 <- lapply(x, function(x) {\n # values.new1 <- x[group.existing.index]\n # names(values.new1) <- group.existing\n # return(values.new1)\n # })\n # names(values.new2) <- names(x)\n # return(values.new2)\n # })\n # names(values.new) <- names(values)\n # }\n # }\n # netP[[netP.j]] <- values.new\n # }\n netP = computeCommunProbPathway(net = net.subset[[i]], pairLR.use = object@LR[[i]]$LRsig, thresh = thresh)\n netP$centr = netAnalysis_computeCentrality(net = net.subset[[i]]$prob)\n netP.subset[[i]] <- netP\n idents.subset[[i]] <- idents[[i]][names(idents[[i]]) %in% cells.use]\n idents.subset[[i]] <- factor(idents.subset[[i]], levels = levels(idents[[i]])[levels(idents[[i]]) %in% level.use])\n }\n idents.subset$joint <- factor(object@idents$joint[cells.use.index], levels = level.use)\n\n } else {\n cat(\"Update slots object@images, object@net, object@netP in a single dataset...\", '\\n')\n\n group.existing <- level.use0[level.use0 %in% level.use]\n group.existing.index <- which(level.use0 %in% level.use)\n\n images <- object@images\n for (images.j in names(images)) {\n values <- images[[images.j]]\n if (images.j %in% c(\"coordinates\")) {\n values.new <- values[cells.use.index, ]\n images[[images.j]] <- values.new\n }\n if (images.j %in% c(\"distance\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n images[[images.j]] <- values.new\n }\n }\n images.subset <- images\n\n\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- values[group.existing.index, group.existing.index, , drop = FALSE]\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n net[[net.j]] <- values.new\n }\n }\n net.subset <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n # netP <- object@netP\n # for (netP.j in names(netP)) {\n # values <- netP[[netP.j]]\n # if (netP.j %in% c(\"pathways\")) {\n # values.new <- values\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"prob\")) {\n # values.new <- values[group.existing.index, group.existing.index, ]\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"centr\")) {\n # for (k in 1:length(values)) {\n # values.new <- lapply(values, function(x) {\n # values.new2 <- lapply(x, function(x) {\n # values.new1 <- x[group.existing.index]\n # names(values.new1) <- group.existing\n # return(values.new1)\n # })\n # names(values.new2) <- names(x)\n # return(values.new2)\n # })\n # names(values.new) <- names(values)\n # }\n # }\n # netP[[netP.j]] <- values.new\n # }\n netP = computeCommunProbPathway(net = net.subset, pairLR.use = object@LR$LRsig, thresh = thresh)\n netP$centr = netAnalysis_computeCentrality(net = net.subset$prob)\n netP.subset <- netP\n idents.subset <- object@idents[cells.use.index]\n idents.subset <- factor(idents.subset, levels = level.use)\n }\n\n\n object.subset <- methods::new(\n Class = \"CellChat\",\n data = data.subset,\n data.signaling = data.signaling.subset,\n data.smooth = data.smooth.subset,\n images = images.subset,\n net = net.subset,\n netP = netP.subset,\n meta = meta.subset,\n idents = idents.subset,\n var.features = object@var.features,\n LR = object@LR,\n DB = object@DB,\n options = object@options\n )\n return(object.subset)\n}\n\n\n"], ["/CellChat/R/RcppExports.R", "# Generated by using Rcpp::compileAttributes() -> do not edit by hand\n# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393\n\nComputeSNN <- function(nn_ranked, prune) {\n .Call(`_CellChat_ComputeSNN`, nn_ranked, prune)\n}\n\n"], ["/CellChat/R/data.R", "#' Ligand-receptor interactions in CellChat database for mouse\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.mouse\"\n\n#' Ligand-receptor interactions in CellChat database for human\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.human\"\n\n#' Mouse Protein-Protein interactions\n#'\n#' An adjacency matrix of the high confidence known experimental interactions\n#' between mouse proteins on STRINGdb.\n#'\n#' @format A square matrix where A_{ij}=1 if protein i interacts with protein j\n#' @source \\url{http://www.string-db.org/}\n\"PPI.mouse\"\n\n#' Ligand-receptor interactions in CellChat database for Zebrafish\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.zebrafish\"\n\n#' Human Protein-Protein interactions\n#'\n#' An adjacency matrix of the high confidence known experimental interactions\n#' between human proteins on STRINGdb.\n#'\n#' @format A square matrix where A_{ij}=1 if protein i interacts with protein j\n#' @source \\url{http://www.string-db.org/}\n\"PPI.human\"\n"], ["/CellChat/R/CellChat-package.R", "## usethis namespace: start\n#' @useDynLib CellChat, .registration = TRUE\n## usethis namespace: end\nNULL\n\n## usethis namespace: start\n#' @importFrom Rcpp sourceCpp\n## usethis namespace: end\nNULL\n"]], "task_instance_info": {"created_time": "2025-08-21 00:57:36", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = 0.5,\n sources.use = NULL, targets.use = NULL, signaling = NULL,\n color.use = NULL, color.use.pattern = NULL, color.use.signaling = \"grey50\",\n do.order = FALSE, main.title = NULL,\n font.size = 2.5, font.size.title = 12) {}", "code_description": "This code segment functions to: Process structured data to generate a flow-based visualization representing associations between cell groups and signaling pathways by aggregating contribution metrics, applying scaling transformations, and rendering hierarchical relationships through positional encoding."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nnetAnalysis_river <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = 0.5,\n sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE,\n color.use = NULL, color.use.pattern = NULL, color.use.signaling = \"grey50\",\n title.name = NULL, font.size = 10, font.size.title = 10, show.legend = TRUE,\n nCol = NULL, ...) {\n pattern <- match.arg(pattern)\n prob <- slot(object, slot.name)$prob\n pval <- slot(object, slot.name)$pval\n pval[is.na(pval)] <- 1\n prob[pval > 0.05] <- 0\n if (is.null(rownames(prob))) {\n stop(\"Row names not found in the probability matrix!\")\n }\n \n # Prepare network data\n net <- apply(prob, 3, function(x) sum(x > cutoff))\n net <- net[net > 0]\n df <- reshape2::melt(net, value.name = \"contribution\")\n colnames(df) <- c(\"pathway\",\"contribution\")\n \n # Add cell group information\n df$source <- sub(\".*--\", \"\", df$pathway)\n df$target <- sub(\"--.*\", \"\", df$pathway)\n \n # Filter interactions\n if (!is.null(sources.use)) df <- df[df$source %in% sources.use,]\n if (!is.null(targets.use)) df <- df[df$target %in% targets.use,]\n if (!is.null(idents.use)) df <- df[df$source %in% idents.use | df$target %in% idents.use,]\n if (remove.isolate) {\n df <- df[df$contribution > 0,]\n }\n \n # Prepare alluvial plot data\n lodes <- ggalluvial::to_lodes_form(df, axes = 1:3, diffuse = TRUE)\n \n # Set colors\n if (is.null(color.use)) color.use <- scPalette(length(unique(c(df$source, df$target))))\n if (is.null(color.use.pattern)) color.use.pattern <- color.use\n if (is.null(color.use.signaling)) color.use.signaling <- \"grey50\"\n \n # Create base plot\n gg <- ggplot(lodes, aes(x = x, stratum = stratum, alluvium = alluvium,\n y = contribution, fill = stratum)) +\n ggalluvial::geom_flow(alpha = 0.6, width = 0.3) +\n ggalluvial::geom_stratum(width = 0.35) +\n theme_classic() +\n scale_x_discrete(expand = c(0,0)) +\n scale_y_continuous(expand = c(0,0)) +\n theme(axis.text.x = element_text(angle = 45, hjust = 1, size = font.size),\n axis.title = element_blank(),\n plot.title = element_text(size = font.size.title, hjust = 0.5),\n legend.position = ifelse(show.legend, \"right\", \"none\")) +\n scale_fill_manual(values = c(color.use.pattern, color.use.signaling))\n \n if (!is.null(title.name)) {\n gg <- gg + ggtitle(title.name)\n }\n \n if (!is.null(nCol)) {\n gg <- gg + facet_wrap(~group, ncol = nCol)\n }\n \n return(gg)\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 00-58-50"}, "editdistance_info": {"edit_distance": 12.6838, "calculate_time": "2025-08-21 00:58:50", "true_code_clean": "function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = 0.5,\n sources.use = NULL, targets.use = NULL, signaling = NULL,\n color.use = NULL, color.use.pattern = NULL, color.use.signaling = \"grey50\",\n do.order = FALSE, main.title = NULL,\n font.size = 2.5, font.size.title = 12){\n message(\"Please make sure you have load `library(ggalluvial)` when running this function\")\n requireNamespace(\"ggalluvial\")\n res.pattern <- methods::slot(object, slot.name)$pattern[[pattern]]\n data1 = res.pattern$pattern$cell\n data2 = res.pattern$pattern$signaling\n if (is.null(color.use.pattern)) {\n nPatterns <- length(unique(data1$Pattern))\n if (pattern == \"outgoing\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(1,nPatterns*2, by = 2)]\n } else if (pattern == \"incoming\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(2,nPatterns*2, by = 2)]\n }\n }\n if (is.null(main.title)) {\n if (pattern == \"outgoing\") {\n main.title = \"Outgoing communication patterns of secreting cells\"\n } else if (pattern == \"incoming\") {\n main.title = \"Incoming communication patterns of target cells\"\n }\n }\n if (is.null(data2)) {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n if (is.null(color.use)) {\n color.use <- scPalette(nCellGroup)\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n gg <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10))+\n ggtitle(main.title)\n } else {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n cells.level = levels(object@idents)\n if (is.null(color.use)) {\n color.use <- scPalette(length(cells.level))[cells.level %in% unique(plot.data$CellGroup)]\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n if (!is.null(sources.use)) {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% sources.use)\n }\n if (!is.null(targets.use)) {\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% targets.use)\n }\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n StatStratum <- ggalluvial::StatStratum\n gg1 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10)) +\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n data2$Contribution[data2$Contribution < cutoff] <- 0\n plot.data <- data2\n nPatterns<-length(unique(plot.data$Pattern))\n nSignaling<-length(unique(plot.data$Signaling))\n if (length(color.use.signaling) == 1) {\n color.use.all <- c(color.use.pattern, rep(color.use.signaling, nSignaling))\n } else {\n color.use.all <- c(color.use.pattern, color.use.signaling)\n }\n if (!is.null(signaling)) {\n plot.data <- plot.data[plot.data$Signaling %in% signaling, ]\n }\n plot.data.long <- ggalluvial::to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"Signaling\"]], plot.data[[\"Pattern\"]]), sum)\n mat[is.na(mat)] <- 0; mat <- mat[-which(rowSums(mat) == 0), ]\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(colnames(mat),names(cluster)[order.name]))\n }\n gg2 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"Pattern\", \"Signaling\")),y= Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"forward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) + \n scale_x_discrete(limits = c(), labels=c(\"Patterns\", \"Signaling\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size= 10))+\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n gg <- cowplot::plot_grid(gg1, gg2,align = \"h\", nrow = 1)\n title <- cowplot::ggdraw() + cowplot::draw_label(main.title,size = font.size.title)\n gg <- cowplot::plot_grid(title, gg, ncol=1, rel_heights=c(0.1, 1))\n }\n return(gg)\n}", "predict_code_clean": "netAnalysis_river <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = 0.5,\n sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE,\n color.use = NULL, color.use.pattern = NULL, color.use.signaling = \"grey50\",\n title.name = NULL, font.size = 10, font.size.title = 10, show.legend = TRUE,\n nCol = NULL, ...) {\n pattern <- match.arg(pattern)\n prob <- slot(object, slot.name)$prob\n pval <- slot(object, slot.name)$pval\n pval[is.na(pval)] <- 1\n prob[pval > 0.05] <- 0\n if (is.null(rownames(prob))) {\n stop(\"Row names not found in the probability matrix!\")\n }\n net <- apply(prob, 3, function(x) sum(x > cutoff))\n net <- net[net > 0]\n df <- reshape2::melt(net, value.name = \"contribution\")\n colnames(df) <- c(\"pathway\",\"contribution\")\n df$source <- sub(\".*--\", \"\", df$pathway)\n df$target <- sub(\"--.*\", \"\", df$pathway)\n if (!is.null(sources.use)) df <- df[df$source %in% sources.use,]\n if (!is.null(targets.use)) df <- df[df$target %in% targets.use,]\n if (!is.null(idents.use)) df <- df[df$source %in% idents.use | df$target %in% idents.use,]\n if (remove.isolate) {\n df <- df[df$contribution > 0,]\n }\n lodes <- ggalluvial::to_lodes_form(df, axes = 1:3, diffuse = TRUE)\n if (is.null(color.use)) color.use <- scPalette(length(unique(c(df$source, df$target))))\n if (is.null(color.use.pattern)) color.use.pattern <- color.use\n if (is.null(color.use.signaling)) color.use.signaling <- \"grey50\"\n gg <- ggplot(lodes, aes(x = x, stratum = stratum, alluvium = alluvium,\n y = contribution, fill = stratum)) +\n ggalluvial::geom_flow(alpha = 0.6, width = 0.3) +\n ggalluvial::geom_stratum(width = 0.35) +\n theme_classic() +\n scale_x_discrete(expand = c(0,0)) +\n scale_y_continuous(expand = c(0,0)) +\n theme(axis.text.x = element_text(angle = 45, hjust = 1, size = font.size),\n axis.title = element_blank(),\n plot.title = element_text(size = font.size.title, hjust = 0.5),\n legend.position = ifelse(show.legend, \"right\", \"none\")) +\n scale_fill_manual(values = c(color.use.pattern, color.use.signaling))\n if (!is.null(title.name)) {\n gg <- gg + ggtitle(title.name)\n }\n if (!is.null(nCol)) {\n gg <- gg + facet_wrap(~group, ncol = nCol)\n }\n return(gg)\n}"}} {"repo_name": "CellChat", "file_name": "/CellChat/R/app.R", "inference_info": {"prefix_code": "#' Generate a Shiny App for interactive exploration of CellChat's outputs\n#'\n#' @param object CellChat object\n#' @param ... Other parameters of `shinyApp` function from shiny R package\n#' @return A Shiny app object on the basis of one CellChat object\n#' @export\n#' @importFrom stringr str_split_1\n# #' @importFrom plotly subplot plot_ly ggplotly add_markers highlight highlight_key plotlyOutput layout\n# #' @importFrom bsicons bs_icon\n#' @import shiny bslib\n#'\nrunCellChatApp <- function(object,...) {\n # ##########################################################################\n # set some global options\n # ##########################################################################\n options(stringsAsFactors = FALSE)\n\n # ##########################################################################\n # some useful elements for ui.R\n # ##########################################################################\n choices_cell_groups <-levels(object@idents)\n names(choices_cell_groups) <- levels(object@idents)\n\n choices_pathways <- object@netP$pathways\n names(choices_pathways) <- object@netP$pathways\n\n # all signaling gene names\n choices_gene_names <- CellChat::extractGene(object@DB)\n # all ligand-receptor pair names\n #choices_pairLR_use <- object@DB$interaction$interaction_name\n if (\"LRs\" %in% names(object@net)) {\n choices_pairLR_use <- object@net$LRs\n } else {\n thresh = 0.05\n prob <- object@net$prob\n prob[object@net$pval > thresh] <- 0\n LR <- dimnames(prob)[[3]]\n LR.sig <- LR[apply(prob, 3, sum) != 0]\n choices_pairLR_use <- LR.sig\n }\n\n\n # Palettes (sequential)\n choices_palettes_sequential <- stringr::str_split_1(\"Blues, BuGn, BuPu, GnBu, Greens, Greys, Oranges, OrRd, PuBu, PuBuGn, PuRd, Purples, RdPu, Reds, YlGn, YlGnBu, YlOrBr, YlOrRd\",\", \")\n names(choices_palettes_sequential) <- choices_palettes_sequential\n choices_palettes_diverging <- stringr::str_split_1(\"BrBG, PiYG, PRGn, PuOr, RdBu, RdGy, RdYlBu, RdYlGn, Spectral\",\", \")\n names(choices_palettes_diverging) <- choices_palettes_diverging\n\n # ##########################################################################\n # interactive visualization\n # ##########################################################################\n\n # interactive Heatmap\n # [Colors (ggplot2)](http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/)\n plotly_netVisual_heatmap <- function(obj_heatmap,palette.heatmap,direction.heatmap=1) {\n gg_heatmap <- obj_heatmap@matrix %>%\n as.data.frame() %>%\n mutate(row = rownames(.)) %>%\n tidyr::pivot_longer(\n data = .,\n cols = colnames(.)[-length(colnames(.))],\n names_to = \"column\",\n values_to = \"value\"\n ) %>%\n ggplot() +\n geom_tile(aes(row, column, fill = value),\n width = 0.95,\n height = 0.95) +\n # guides(fill=guide_legend(title=obj_heatmap@row_title))+\n labs(title = '',\n x = '',\n y = obj_heatmap@row_title,\n # I can't set the direction of the legend title, I thick it's a bug\n # fill = obj_heatmap@column_title,\n ) +\n scale_fill_distiller(\n palette = palette.heatmap,\n na.value = 'white',\n direction = direction.heatmap,\n ) +\n theme_minimal()+\n theme(axis.title.y = element_text(size = 14))\n\n # ggplot transpose the matrix, so we need use colSums to calc the 'rowSums'\n # of the matrix\n gg_right <- obj_heatmap@matrix %>%\n colSums(abs(.)) %>%\n tibble(row_sum = ., sources_name = names(.)) %>%\n ggplot() +\n geom_bar(aes(x = sources_name, y = row_sum, fill = sources_name),\n stat = 'identity') +\n labs(title = '',\n x = '',\n y = '',) +\n guides(fill = FALSE) +\n scale_fill_brewer(palette = \"Set1\", direction = 1) +\n theme_minimal() +\n coord_flip()\n\n gg_top <- obj_heatmap@matrix %>%\n rowSums(abs(.)) %>%\n tibble(col_sum = ., sources_name = names(.)) %>%\n ggplot() +\n # use fill to set the columns' colors\n geom_bar(aes(x = sources_name, y = col_sum, fill = sources_name),\n stat = 'identity') +\n labs(title = obj_heatmap@column_title,\n x = '',\n y = '',) +\n guides(fill = FALSE)+\n scale_fill_brewer(palette = \"Set1\", direction = 1) +\n # theme() function should be used behind the theme_*()\n theme_minimal()+\n theme(plot.title = element_text(hjust = 0.5,size = 14))\n\n return(plotly::subplot(\n gg_top,\n plotly::plotly_empty(),\n gg_heatmap,\n gg_right,\n nrows = 2,\n heights = c(0.2, 0.8),\n widths = c(0.8, 0.2),\n margin = 0,\n shareX = TRUE,\n shareY = TRUE,\n titleX = TRUE,\n titleY = TRUE\n )\n )\n }\n\n # interactive DimPlot\n plotly_DimPlot <- ", "suffix_code": "\n\n # interactive FeaturePlot\n # https://plotly.com/r/subplots/\n plotly_FeaturePlot <- function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n reduction = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE){\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(\"Please make sure `object@dr` contains a low-dimensional space of the data and specify the dimensionality reduction to use.\")\n }\n }\n\n samples <- object@meta$samples\n cell_labels <- object@idents\n data <- as.matrix(object@data)\n meta <- object@meta\n coords <- as.data.frame(coords)\n if (ncol(coords) >= 2) {\n coords <- coords[, c(1,2)]\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n\n # add idents info\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = -1))(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n }\n else {\n colormap <- color.heatmap\n }\n if (is.null(features) &\n is.null(signaling) & is.null(pairLR.use)) {\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)) {\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)) {\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)) {\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n df <- data.frame(x = coords[, 1], y = coords[, 2],\n cell_labels = cell_labels)\n\n\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n geneLR.return = TRUE,\n enriched.only = enriched.only,\n thresh = thresh\n )\n feature.use <- res$geneLR\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex,\n object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex,\n object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n }\n else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) >\n 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n }\n else if (length(intersect(feature.use, colnames(meta))) >\n 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[, feature.use, drop = FALSE])\n }\n else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \", cutoff, \"to the values...\",\n \"\\n\")\n data.use[data.use <= cutoff] <- 0\n }\n\n\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 0.95) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_colour_gradientn(\n colours = colormap,\n guide = guide_colorbar(\n title = NULL,\n ticks = T,\n label = T,\n barwidth = 0.5\n ),\n na.value = \"grey90\"\n ) +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + ggtitle(feature.name) +\n theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n # g <- g + coord_fixed() +\n # scale_y_reverse()\n\n gg[[i]] <- g %>% plotly::ggplotly(height = 400)\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n # print(annotations_pos)\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',annotations = annotations)\n }\n else {\n gg <- plotly::ggplotly(gg[[1]])\n }\n }\n else {\n # do.binary\n set_individual_legend <- function(plt) {\n # plt is a plotly plot obj\n plt_build <- plotly::plotly_build(plt)\n\n # get the num of traces\n len_legend <- length(plt_build$x$data)\n\n for (i in 1:len_legend) {\n # set legendgroup\n plt_build$x$data[[i]]$legendgroup <- feature.name\n # set legendtitle\n plt_build$x$data[[i]]$legendgrouptitle <- list(text=feature.name,font=list(size=12))\n }\n return(plt_build)\n }\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n enriched.only = enriched.only,\n thresh = thresh\n )\n LR.pair <- object@LR$LRsig[res$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL\n rownames(dataR) <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \")\n }\n gg <- vector(\"list\", numFeature)\n\n # set subplot title pos\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 1) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i,] > cutoff\n idx2 = dataR[i,] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\", ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i], geneR[i],\n \"Both\", \"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i], geneR[i], \"Both\",\n \"None\")\n if (length(setdiff(levels(group), unique(group))) >\n 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group),\n unique(group)))\n }\n df$feature.data <- group\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + guides(color = guide_legend(override.aes = list(size = legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n # g <- g + coord_fixed() +\n # scale_y_reverse()\n\n # cat(feature.name)\n gg[[i]] <- g %>% plotly::ggplotly(\n type = 'scatter',\n mode='markers+text',\n ) %>% set_individual_legend()\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',\n annotations = annotations,\n legend = list(tracegroupgap = 10,title=list(text=''))\n )\n }\n else {\n gg <- plotly::ggplotly(gg[[1]],\n type = 'scatter',\n mode = 'markers') %>%\n plotly::layout(legend = list(title = list(text = '')))\n }\n }\n return(gg)\n }\n\n # interactive spatialDimPlot\n plotly_spatialDimPlot <- function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1)\n {\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[, group.by]\n labels <- factor(labels)\n }\n\n coordinates <- as.data.frame(object@images$coordinates)\n samples <- object@meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n\n\n cells.level <- levels(labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n if (is.null(sources.use) & is.null(targets.use)) {\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n }\n else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use,\n \"Others\"))\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use,\n targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n # print(color.use)->return a color vector\n coordinates$cell_labels <- labels\n\n py <- plotly::highlight_key(coordinates,~cell_labels) %>%\n plotly::plot_ly(x = ~x_cent, y = ~y_cent,marker = list(size = point.size)) %>%\n plotly::add_markers(color=~cell_labels,alpha=alpha,colors=color.use) %>%\n plotly::layout(\n title = title.name,\n yaxis = list(\n autorange = \"reversed\",\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n showline = FALSE\n ),\n xaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n showline = FALSE\n )\n ) %>%\n plotly::highlight(on = \"plotly_click\",\n off = \"plotly_relayout\")\n\n return(py)\n }\n\n # interactive spatialFeaturePlot\n # https://plotly.com/r/subplots/\n plotly_spatialFeaturePlot <- function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE){\n coords <- as.data.frame(object@images$coordinates)\n samples <- object@meta$samples\n cell_labels <- object@idents\n data <- as.matrix(object@data)\n meta <- object@meta\n\n if (ncol(coords) == 2) {\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coords = coords\n coords[,1] = temp_coords[,2]\n coords[,2] = temp_coords[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n # add idents info\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = -1))(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n }\n else {\n colormap <- color.heatmap\n }\n if (is.null(features) &\n is.null(signaling) & is.null(pairLR.use)) {\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)) {\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)) {\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)) {\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n df <- data.frame(x = coords[, 1], y = coords[, 2],\n cell_labels = cell_labels)\n\n\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n geneLR.return = TRUE,\n enriched.only = enriched.only,\n thresh = thresh\n )\n feature.use <- res$geneLR\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex,\n object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex,\n object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n }\n else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) >\n 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n }\n else if (length(intersect(feature.use, colnames(meta))) >\n 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[, feature.use, drop = FALSE])\n }\n else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \", cutoff, \"to the values...\",\n \"\\n\")\n data.use[data.use <= cutoff] <- 0\n }\n\n\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 0.95) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_colour_gradientn(\n colours = colormap,\n guide = guide_colorbar(\n title = NULL,\n ticks = T,\n label = T,\n barwidth = 0.5\n ),\n na.value = \"grey90\"\n ) +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + ggtitle(feature.name) +\n theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n g <- g + coord_fixed() +\n scale_y_reverse()\n\n gg[[i]] <- g %>% plotly::ggplotly(height = 400)\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n # print(annotations_pos)\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',annotations = annotations)\n }\n else {\n gg <- plotly::ggplotly(gg[[1]])\n }\n }\n else {\n # do.binary\n set_individual_legend <- function(plt) {\n # plt is a plotly plot obj\n plt_build <- plotly::plotly_build(plt)\n\n # get the num of traces\n len_legend <- length(plt_build$x$data)\n\n for (i in 1:len_legend) {\n # set legendgroup\n plt_build$x$data[[i]]$legendgroup <- feature.name\n # set legendtitle\n plt_build$x$data[[i]]$legendgrouptitle <- list(text=feature.name,font=list(size=12))\n }\n return(plt_build)\n }\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n enriched.only = enriched.only,\n thresh = thresh\n )\n LR.pair <- object@LR$LRsig[res$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL\n rownames(dataR) <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \")\n }\n gg <- vector(\"list\", numFeature)\n\n # set subplot title pos\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 1) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i,] > cutoff\n idx2 = dataR[i,] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\", ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i], geneR[i],\n \"Both\", \"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i], geneR[i], \"Both\",\n \"None\")\n if (length(setdiff(levels(group), unique(group))) >\n 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group),\n unique(group)))\n }\n df$feature.data <- group\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + guides(color = guide_legend(override.aes = list(size = legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n g <- g + coord_fixed() +\n scale_y_reverse()\n\n # cat(feature.name)\n gg[[i]] <- g %>% plotly::ggplotly(\n type = 'scatter',\n mode='markers+text',\n ) %>% set_individual_legend()\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',\n annotations = annotations,\n legend = list(tracegroupgap = 10,title=list(text=''))\n )\n }\n else {\n gg <- plotly::ggplotly(gg[[1]],\n type = 'scatter',\n mode = 'markers') %>%\n plotly::layout(legend = list(title = list(text = '')))\n }\n }\n return(gg)\n }\n\n\n\n # ##########################################################################\n # Shiny App's UI\n # ##########################################################################\n ui <- fluidPage(\n theme = bslib::bs_theme(version = 5),\n # ##########################################################################\n # meta info of the HTML pages\n # ##########################################################################\n tags$head(\n # title\n tags$title(\"Interactive CellChat Explorer\"),\n # icon\n tags$link(rel = \"shortcut icon\", type = \"image/x-icon\", href = \"favicon.ico\"),\n tags$link(rel=\"stylesheet\",href=\"https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css\"),\n ),\n tags$body(\n # ##########################################################################\n # logo and title of the website\n # ##########################################################################\n tags$nav(class=\"navbar navbar-light bg-light\",\n div(class=\"container-fluid justify-content-center\",\n tags$a(\n class=\"navbar-brand\",href=\"http://www.cellchat.org/\",\n img(src=\"https://s2.loli.net/2023/08/08/2qjSoRACDtHByOY.png\",class=\"d-inline\",alt=\"\",height=\"30\"),\n tags$p(\"Interactive CellChat Explorer\",class=\"fs-1 d-inline\")\n )\n\n )),\n # ##########################################################################\n # 1.Basic exploration of spatial-resolved gene expression\n # ##########################################################################\n\n # Visualize cell groups and signaling expression\n h3(tags$i(class=\"bi bi-1-square-fill\"),\n \"Visualize cell groups and signaling expression\",class=\"h3\"),\n bslib::card(\n bslib::card_header(\n h6(tags$i(class=\"bi bi-bookmark\"),\n \"Dim Plot\",class=\"h6\")),\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n sliderInput(\n \"dimplot_point_size\",\n label = \"Point size\",\n min = 3,\n max = 8,\n step = 0.5,\n value = 3\n ),\n sliderInput(\n \"dimplot_alpha\",\n label = \"Alpha\",\n min = 0,\n max = 1,\n step = 0.2,\n value = 1\n ),\n )\n ),\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"DimPlot\",\n width = 664,height = 498)\n )\n\n ),\n\n ),\n\n # gene expression distribution\n # https://shiny.posit.co/r/gallery/widgets/datatables-options/\n # https://shiny.posit.co/r/gallery/widgets/selectize-examples/\n navset_card_tab(\n title = h6(tags$i(class=\"bi bi-bookmark-dash\"),\n \"Feature Plot\",class=\"h6\"),\n sidebar = NULL,\n # content\n nav_panel(\n title = \"use gene names\",\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectizeInput(\n inputId = 'selectize_gene_names',\n label = 'Gene Names',\n choices = NULL,\n multiple = TRUE,\n # options = list(maxItems = 4)\n ),\n numericInput(\n \"nrows_feature_plot1\",\n label = \"nrows\",\n min = 1,\n step = 1,\n value = 1,\n ),\n ),\n\n accordion_panel(\n title = \"Color\",\n icon = tags$i(class=\"bi bi-palette-fill\"),\n selectInput(\n \"direction_feature_plot1\",\n label = \"direction\",\n choices = list(\"1\"=1,\"-1\"=-1),\n selected = 1,\n multiple = F\n ),\n selectInput(\n \"palette_feature_plot1\",\n label = \"palette\",\n choices = c(choices_palettes_diverging,choices_palettes_sequential),\n selected = \"Reds\",\n multiple = F\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n numericInput(\n \"cut.off_feature_plot1\",\n label = \"cut.off\",\n min = 0,\n step = 0.1,\n value = 0,\n ),\n sliderInput(\n \"point.size_feature_plot1\",\n label = \"point.size\",\n min = 0,\n max = 2,\n step = 0.1,\n value = 0.4\n )\n )\n\n ),\n # nav content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"gene_expression_distribution\",width = 664,height = 498),\n ),\n )\n ),\n nav_panel(\n title = \"use L-R pairs\",\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectizeInput(\n inputId = 'selectize_pairLR_use',\n label = 'pairLR_use',\n choices = NULL,\n multiple = T\n ),\n numericInput(\n \"nrows_feature_plot2\",\n label = \"nrows\",\n min = 1,\n step = 1,\n value = 1,\n ),\n checkboxInput(\n \"do.binary_feature_plot\",\n label = \"do.binary\",\n value = TRUE),\n ),\n accordion_panel(\n title = \"Color\",\n icon = tags$i(class=\"bi bi-palette-fill\"),\n selectInput(\n \"direction_feature_plot2\",\n label = \"direction\",\n choices = list(\"1\"=1,\"-1\"=-1),\n selected = 1,\n multiple = F\n ),\n selectInput(\n \"palette_feature_plot2\",\n label = \"palette\",\n choices = c(choices_palettes_diverging,choices_palettes_sequential),\n selected = \"Reds\",\n multiple = F\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n numericInput(\n \"cut.off_feature_plot2\",\n label = \"cut.off\",\n min = 0,\n step = 0.1,\n value = 0,\n ),\n sliderInput(\n \"point.size_feature_plot2\",\n label = \"point.size\",\n min = 0,\n max = 2,\n step = 0.1,\n value = 0.4\n )\n )\n ),\n # nav content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"gene_expression_distribution2\",width = 664,height = 498)\n )\n ),\n )\n ),\n\n # ##########################################################################\n # 2.Examine signaling between cell groups\n # ##########################################################################\n h2(tags$i(class=\"bi bi-2-square-fill\"),\n \"Examine signaling between cell groups\"),\n navset_card_tab(\n title = NULL,\n sidebar = NULL,\n nav_panel(\"Heatmap\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"The number of interactions/interaction strength between any two cell groups\",\n class=\"h6\"),\n hr(),\n\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"measure_heatmap\",\n label = \"measurement\",\n choices = list(\"count\" = \"count\", \"weight\" = \"weight\"),\n selected = \"count\"\n ),\n selectInput(\n \"palette_heatmap\",\n label = \"palette (sequential)\",\n choices = choices_palettes_sequential,\n selected = \"Blues\"\n ),\n # Sets the order of colours in the scale. If 1, the default, colours are as output by RColorBrewer::brewer.pal(). If -1, the order of colours is reversed.\n selectInput(\n \"direction_heatmap\",\n label = \"direction\",\n choices = list(\n \"1\"=1,\n \"-1\"=-1\n ),\n selected = 1,\n )\n\n # refer to: https://ggplot2.tidyverse.org/reference/scale_brewer.html\n ),\n ),\n\n # content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"netVisual_heatmap\",width = 664,height = 498)\n )\n )\n ),\n\n # the enriched signaling among one selected pair of cell groups\n nav_panel(\"rankNet\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"The enriched signaling\",\n class=\"h6\"),\n hr(),\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"select1_cell_group\",\n label = \"cell groups for sources.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[1],\n multiple = TRUE\n ),\n selectInput(\n \"select2_cell_group\",\n label = \"cell groups for targets.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[2],\n multiple = TRUE\n ),\n\n # selectInput(\n # \"measure_ranknet\",\n # label = \"measurement\",\n # choices = list(\"count\" = \"count\", \"weight\" = \"weight\"),\n # selected = \"count\"\n # ),\n selectInput(\n \"slot.name_ranknet\",\n label = \"slot.name\",\n choices = list(\"net\" = \"net\", \"netP\" = \"netP\"),\n selected = \"netP\"\n ),\n # selectInput(\n # \"palette_ranknet\",\n # label = \"palette (sequential)\",\n # choices = choices_palettes_sequential,\n # selected = \"Blues\"\n # ),\n ),\n ),\n\n # content\n plotly::plotlyOutput(outputId = \"rankNet\")\n )\n ),\n nav_panel(\"Contribution Plot\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"Contribution of each L-R pair to overall signaling\",\n class = \"h6\"),\n hr(),\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"pathway_contribution_plot\",\n label = \"a pathway to show\",\n choices = choices_pathways,\n selected = choices_pathways[1]\n ),\n selectInput(\n \"select3_cell_group\",\n label = \"a cell group for sources.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[1]\n ),\n selectInput(\n \"select4_cell_group\",\n label = \"a cell group for targets.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[2]\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n sliderInput(\n \"font.size_contribution_plot\",\n label = \"font.size\",\n min = 10,\n max=30,\n step = 5,\n value = 20\n )\n )\n ),\n\n # content\n plotOutput(outputId = \"netAnalysis_contribution\"),\n )\n ),\n ),\n\n # Contribution of each L-R pair to overall signaling\n # width = 3.2inch, height = 1.5inch,\n # height might change dependent on dataset\n\n ## Examine individual signaling pathway\n ## (the following four plots will be appeared based on user's input)\n h2(tags$i(class=\"bi bi-3-square-fill\"),\n \"Examine individual signaling pathway\"),\n navset_card_tab(\n title = h6(\"Plots\",class=\"h6\"),\n sidebar = accordion(\n selectizeInput(\n inputId = 'selectize_pathway',\n label = 'Select a pathway to show',\n choices = NULL,\n multiple = FALSE\n ),\n hr(),\n accordion_panel(\n title = \"Circle plot\",\n icon = tags$i(class=\"bi bi-circle-fill\"),\n # edge.width.max = 5, vertex.size.max = 12, vertex.label.cex = 0.8\n sliderInput(\n \"slider_Circle_plot_edge.width.max\",\n label = \"edge.width.max\",\n min = 5,\n max = 15,\n value = 8,\n step = 1\n ),\n sliderInput(\n \"slider_Circle_plot_vertex.size.max\",\n label = \"vertex.size.max\",\n min = 8,\n max = 16,\n value = 12,\n step = 2),\n sliderInput(\n \"slider_Circle_plot_vertex.label.cex\",\n label = \"vertex.label.cex\",\n min = 1,\n max = 2,\n value = 1,\n step = 0.2\n ),\n ),\n accordion_panel(\n title = \"Spatial plot\",\n icon = tags$i(class=\"bi bi-layers-half\"),\n # edge.width.max = 5, vertex.size.max = 1,\n # point.size = 2.5,\n # alpha.image = 0.2, vertex.label.cex = 5\n sliderInput(\n \"slider_Spatial_plot_edge.width.max\",\n label = \"edge.width.max\",\n min = 2,\n max = 8,\n value = 5,\n step = 1\n ),\n sliderInput(\n \"slider_Spatial_plot_vertex.size.max\",\n label = \"vertex.size.max\",\n min = 2,\n max = 8,\n value = 5,\n step = 1),\n sliderInput(\n \"slider_Spatial_plot_vertex.label.cex\",\n label = \"vertex.label.cex\",\n min = 5,\n max = 10,\n value = 8,\n step = 1\n ),\n\n sliderInput(\n \"slider_Spatial_plot_point.size\",\n label = \"point.size\",\n min = 1,\n max = 3,\n value = 2.4,\n step = 0.2\n ),\n sliderInput(\n \"slider_Spatial_plot_alpha.image\",\n label = \"alpha.image\",\n min = 0,\n max = 1,\n value = 0.2,\n step = 0.05\n ),\n ),\n accordion_panel(\n title = \"Contribution of each L-R pair\",\n icon = tags$i(class=\"bi bi-bar-chart-fill\"),\n ),\n ),\n\n # nav tab\n nav_panel(\n title = \"Circle plot\",\n div(class=\"d-flex justify-content-center\",\n plotOutput(outputId = \"Circle_plot\",\n height = \"780px\",width = \"580px\")\n )\n ),\n nav_panel(\n title = \"Spatial plot\",\n div(class=\"d-flex justify-content-center\",\n plotOutput(outputId = \"Spatial_plot\",\n height = \"780px\",width = \"580px\")\n )\n ),\n nav_panel(\n title = \"Contribution of each L-R pair\",\n plotly::plotlyOutput(outputId = \"LR_pair_contribution\",\n height = \"900px\")\n ),\n\n ),\n # body\n\n ),\n # page\n )\n # ##########################################################################\n # Shiny App's Server\n # ##########################################################################\n server <- function(input, output, session) {\n ############################################################################\n if (object@options$datatype == \"RNA\") {\n output$DimPlot <- plotly::renderPlotly({\n plotly_DimPlot(\n object,\n point.size = input$dimplot_point_size,\n alpha = input$dimplot_alpha,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"DimPlot\",\n width = 800,\n height = 600\n ))\n })\n } else {\n output$spatialDimPlot <- plotly::renderPlotly({\n plotly_spatialDimPlot(\n object,\n point.size = input$dimplot_point_size,\n alpha = input$dimplot_alpha,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialDimPlot\",\n width = 800,\n height = 600\n ))\n })\n }\n\n\n observe({\n updateSelectizeInput(\n session,\n \"selectize_gene_names\",\n # selected = c(\"Wnt10a\", \"Fzd1\", \"Lrp6\"),\n selected = choices_gene_names[1:2],\n # selected = c(\"Wnt10a\", \"Fzd1\", \"Lrp6\",\"Ror2\",\n # \"Nrp1\",\"Nrp2\",\"Bmpr2\",\"Ret\"),\n choices = choices_gene_names,\n server = TRUE\n )\n })\n # output$out6 <- renderPrint(input$selectize_gene_names)\n\n if (object@options$datatype == \"RNA\") {\n output$gene_expression_distribution <- plotly::renderPlotly(plotly_FeaturePlot(\n object,\n features = input$selectize_gene_names,\n plot_nrows = input$nrows_feature_plot1,\n point.size = input$point.size_feature_plot1,\n cutoff = input$cut.off_feature_plot1,\n color.heatmap = input$palette_feature_plot1,\n direction = input$direction_feature_plot1,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"FeaturePlot (use gene names)\",\n width = 600,\n height = 600\n ))\n )\n } else {\n output$gene_expression_distribution <- plotly::renderPlotly(plotly_spatialFeaturePlot(\n object,\n features = input$selectize_gene_names,\n plot_nrows = input$nrows_feature_plot1,\n point.size = input$point.size_feature_plot1,\n cutoff = input$cut.off_feature_plot1,\n color.heatmap = input$palette_feature_plot1,\n direction = input$direction_feature_plot1,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialFeaturePlot (use gene names)\",\n width = 600,\n height = 600\n ))\n )\n }\n\n\n observe({\n updateSelectizeInput(\n session,\n \"selectize_pairLR_use\",\n selected = choices_pairLR_use[1],\n # selected = c(\"WNT10A_FZD1_LRP6\",\"WNT10A_FZD10_LRP6\",\"BMP2_BMPR1A_ACVR2A\"),\n choices = choices_pairLR_use,\n server = TRUE\n )\n })\n # output$out7 <- renderPrint(input$selectize_pairLR_use)\n if (object@options$datatype == \"RNA\") {\n output$gene_expression_distribution2 <- plotly::renderPlotly({\n plotly_FeaturePlot(\n object,\n pairLR.use = input$selectize_pairLR_use,\n point.size = input$point.size_feature_plot2,\n do.binary = input$do.binary_feature_plot,\n cutoff = input$cut.off_feature_plot2,\n enriched.only = F,\n color.heatmap = input$palette_feature_plot2,\n direction = input$direction_feature_plot2,\n plot_nrows = as.numeric(input$nrows_feature_plot2)\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"FeaturePlot(use pairLRs)\",\n width = 600,\n height = 600\n ))\n })\n } else {\n output$gene_expression_distribution2 <- plotly::renderPlotly({\n plotly_spatialFeaturePlot(\n object,\n pairLR.use = input$selectize_pairLR_use,\n point.size = input$point.size_feature_plot2,\n do.binary = input$do.binary_feature_plot,\n cutoff = input$cut.off_feature_plot2,\n enriched.only = F,\n color.heatmap = input$palette_feature_plot2,\n direction = input$direction_feature_plot2,\n plot_nrows = as.numeric(input$nrows_feature_plot2)\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialFeaturePlot(use pairLRs)\",\n width = 600,\n height = 600\n ))\n })\n }\n\n\n ############################################################################\n output$netVisual_heatmap <- plotly::renderPlotly({\n suppressWarnings({\n netVisual_heatmap(object,\n measure = input$measure_heatmap,\n ) %>%\n plotly_netVisual_heatmap(\n palette.heatmap = input$palette_heatmap,\n direction.heatmap = input$direction_heatmap)\n })\n })\n\n output$rankNet <- plotly::renderPlotly({\n rankNet(\n object,\n mode = \"single\",\n measure = \"weight\",\n sources.use = input$select1_cell_group,\n targets.use = input$select2_cell_group,\n slot.name = input$slot.name_ranknet\n ) %>%\n plotly::ggplotly()\n })\n\n output$netAnalysis_contribution <- renderPlot({\n netAnalysis_contribution(\n object,\n signaling = input$pathway_contribution_plot,\n sources.use = input$select3_cell_group,\n targets.use = input$select4_cell_group,\n font.size = input$font.size_contribution_plot,\n font.size.title = input$font.size_contribution_plot,\n )\n },res = 96)\n ############################################################################\n observe({\n updateSelectizeInput(\n session,\n \"selectize_pathway\",\n selected = choices_pathways[1],\n choices = choices_pathways,\n server = TRUE\n )\n })\n output$Circle_plot <- renderPlot({\n netVisual_aggregate(\n object,\n signaling = input$selectize_pathway,\n layout = \"circle\",\n edge.width.max = input$slider_Circle_plot_edge.width.max,\n vertex.size.max = input$slider_Circle_plot_vertex.size.max,\n vertex.label.cex = input$slider_Circle_plot_vertex.label.cex\n )\n },res = 96)\n output$Spatial_plot <- renderPlot({\n netVisual_aggregate(\n object,\n signaling = input$selectize_pathway,\n layout = \"spatial\",\n edge.width.max = input$slider_Spatial_plot_edge.width.max,\n vertex.size.max = input$slider_Spatial_plot_vertex.size.max,\n vertex.label.cex = input$slider_Spatial_plot_vertex.label.cex,\n alpha.image = input$slider_Spatial_plot_alpha.image,\n point.size = input$slider_Spatial_plot_point.size,\n )\n })\n output$LR_pair_contribution <- plotly::renderPlotly({\n netAnalysis_contribution(\n object,\n signaling = input$selectize_pathway,\n font.size = 12,\n font.size.title = 14\n )\n })\n ############################################################################\n }\n\n\n # Running a Shiny app\n shinyApp(ui = ui, server = server,...)\n}\n", "middle_code": "function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n reduction = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1)\n {\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[, group.by]\n labels <- factor(labels)\n }\n if (length(names(object@dr)) == 0) {\n stop(\"Please check `addReduction` to add a new reduced space into `object@dr`. \\n\")\n }\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please specify the dimensionality reduction to use. \\n\"))\n }\n }\n coordinates <- as.data.frame(coords)\n samples <- object@meta$samples\n if (ncol(coordinates) >= 2) {\n coordinates <- coordinates[, c(1,2)]\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n cells.level <- levels(labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n if (is.null(sources.use) & is.null(targets.use)) {\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n }\n else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use,\n \"Others\"))\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use,\n targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n coordinates$cell_labels <- labels\n py <- plotly::highlight_key(coordinates,~cell_labels) %>%\n plotly::plot_ly(x = ~x_cent, y = ~y_cent,marker = list(size = point.size)) %>%\n plotly::add_markers(color=~cell_labels,alpha=alpha,colors=color.use) %>%\n plotly::layout(\n title = title.name,\n yaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n ),\n xaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n )\n ) %>%\n plotly::highlight(on = \"plotly_click\",\n off = \"plotly_relayout\")\n return(py)\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/CellChat/R/visualization.R", "#' ggplot theme in CellChat\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#' @importFrom ggplot2 theme_classic element_rect theme element_blank element_line element_text\nCellChat_theme_opts <- function() {\n theme(strip.background = element_rect(colour = \"white\", fill = \"white\")) +\n theme_classic() +\n theme(panel.border = element_blank()) +\n theme(axis.line.x = element_line(color = \"black\")) +\n theme(axis.line.y = element_line(color = \"black\")) +\n theme(panel.grid.minor.x = element_blank(), panel.grid.minor.y = element_blank()) +\n theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_blank()) +\n theme(panel.background = element_rect(fill = \"white\")) +\n theme(legend.key = element_blank()) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))\n}\n\n\n#' Generate ggplot2 colors\n#'\n#' @param n number of colors to generate\n#' @importFrom grDevices hcl\n#' @export\n#'\nggPalette <- function(n) {\n hues = seq(15, 375, length = n + 1)\n grDevices::hcl(h = hues, l = 65, c = 100)[1:n]\n}\n\n#' Generate colors from a customed color palette\n#'\n#' @param n number of colors\n#'\n#' @return A color palette for plotting\n#' @importFrom grDevices colorRampPalette\n#'\n#' @export\n#'\nscPalette <- function(n) {\n colorSpace <- c('#E41A1C','#377EB8','#4DAF4A','#984EA3','#F29403','#F781BF','#BC9DCC','#A65628','#54B0E4','#222F75','#1B9E77','#B2DF8A',\n '#E3BE00','#FB9A99','#E7298A','#910241','#00CDD1','#A6CEE3','#CE1261','#5E4FA2','#8CA77B','#00441B','#DEDC00','#DCF0B9','#8DD3C7','#999999')\n if (n <= length(colorSpace)) {\n colors <- colorSpace[1:n]\n } else {\n colors <- grDevices::colorRampPalette(colorSpace)(n)\n }\n return(colors)\n}\n\n#' Visualize the inferred cell-cell communication network\n#'\n#' Automatically save plots in the current working directory.\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param top the fraction of interactions to show (0 < top <= 1)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max.individual the maximum weight of edge when plotting the individual L-R netwrok; defualt = max(net)\n#' @param edge.weight.max.aggregate the maximum weight of edge when plotting the aggregated signaling pathway network\n#' @param edge.width.max The maximum edge width for visualization\n#' @param layout \"hierarchy\", \"circle\" or \"chord\"\n#' @param height height of plot\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param pt.title font size of the text\n#' @param title.space the space between the title and plot\n#' @param vertex.label.cex The label size of vertex in the network\n#' @param out.format the format of output figures: svg, png and pdf\n#'\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the network mediated by ligand-receptor using \"circle\" or \"chord\"\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x, text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`. NB: some parameters might be not supported\n#' @importFrom svglite svglite\n#' @importFrom grDevices dev.off pdf\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#'\nnetVisual <- function(object, signaling, signaling.name = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max.individual = NULL, edge.weight.max.aggregate = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, pt.title = 12, title.space = 6, vertex.label.cex = 0.8,from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n out.format = c(\"svg\",\"png\"),\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n if (is.null(edge.weight.max.individual)) {\n edge.weight.max.individual = max(prob)\n }\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.null(edge.weight.max.aggregate)) {\n edge.weight.max.aggregate = max(prob.sum)\n }\n\n if (layout == \"hierarchy\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_individual.svg\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_individual.png\"), width = 8, height = nRow*height, units = \"in\",res = 300)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name, \"_hierarchy_individual.pdf\"), width = 8, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_individual.pdf\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n\n\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_aggregate.svg\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_aggregate.png\"), width = 7, height = 1*height, units = \"in\",res = 300)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name, \"_hierarchy_aggregate.pdf\"), width = 7, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_aggregate.pdf\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n\n } else if (layout == \"circle\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"spatial\") {\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"chord\") {\n if (is.element(\"svg\", out.format)) {\n\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n }\n\n}\n\n\n#' Visualize the inferred signaling network of signaling pathways by aggregating all L-R pairs\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param layout \"hierarchy\", \"circle\", \"chord\" or \"spatial\"\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param pt.title font size of the text\n#' @param title.space the space between the title and plot\n#' @param vertex.label.cex The label size of vertex in the network\n#'\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x,text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`,`netVisual_spatial`. NB: some parameters might be not supported\n#' @importFrom grDevices recordPlot\n#'\n#' @return an object of class \"recordedplot\" or ggplot\n#' @export\n#'\n#'\nnetVisual_aggregate <- function(object, signaling, signaling.name = NULL, color.use = NULL, thresh = 0.05, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"),\n pt.title = 12, title.space = 6, vertex.label.cex = 0.8,\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20,\n ...) {\n layout <- match.arg(layout)\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n\n if (layout == \"hierarchy\") {\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.null(edge.weight.max)) {\n edge.weight.max = max(prob.sum)\n }\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n } else if (layout == \"circle\") {\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n gg <- netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n } else if (layout == \"spatial\") {\n prob.sum <- apply(prob, c(1,2), sum)\n if (vertex.weight == \"incoming\"){\n if (length(slot(object, \"netP\")$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n vertex.weight = object@netP$centr[[signaling]]$indeg\n } else if (vertex.weight == \"outgoing\"){\n if (length(slot(object, \"netP\")$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n vertex.weight = object@netP$centr[[signaling]]$outdeg\n }\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n\n } else if (layout == \"chord\") {\n prob.sum <- apply(prob, c(1,2), sum)\n gg <- netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y= legend.pos.y)\n }\n\n return(gg)\n\n}\n\n\n\n#' Visualize the inferred signaling network of individual L-R pairs\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param pairLR.use a char vector or a data frame consisting of one column named \"interaction_name\", defining the L-R pairs of interest\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector.\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex in the network\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param graphics.init whether do graphics initiation using par(...). If graphics.init=FALSE, USERS can use par() in a more fexible way\n#' @param layout \"hierarchy\", \"circle\" or \"chord\"\n#' @param height height of plot\n#' @param thresh threshold of the p-value for determining significant interaction\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n# #' @param vertex.size Deprecated. Use `vertex.weight`\n\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the figures using \"circle\" or \"chord\"\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x, text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`. NB: some parameters might be not supported\n#' @importFrom grDevices dev.off pdf\n#'\n#' @return an object of class \"recordedplot\"\n#' @export\n#'\n#'\nnetVisual_individual <- function(object, signaling, signaling.name = NULL, pairLR.use = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex = 0.8,\n weight.scale = TRUE, edge.weight.max = NULL, edge.width.max=8, graphics.init = TRUE,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, #from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n # if (!is.null(vertex.size)) {\n # warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n # }\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n if (!is.null(pairLR.use)) {\n if (is.data.frame(pairLR.use)) {\n pairLR.name <- intersect(pairLR.name, as.character(pairLR.use$interaction_name))\n } else {\n pairLR.name <- intersect(pairLR.name, as.character(pairLR.use))\n }\n\n if (length(pairLR.name) == 0) {\n stop(\"There is no significant communication for the input L-R pairs!\")\n }\n }\n\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n if (is.null(edge.weight.max)) {\n edge.weight.max = max(prob)\n }\n\n if (layout == \"hierarchy\") {\n if (graphics.init) {\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n }\n\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i,...)\n }\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n\n } else if (layout == \"circle\") {\n # par(mfrow=c(nRow,1))\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n gg[[i]] <- netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n } else if (layout == \"spatial\") {\n # par(mfrow=c(nRow,1))\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n gg[[i]] <- netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n } else if (layout == \"chord\") {\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n gg[[i]] <- netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y)\n }\n }\n return(gg)\n}\n\n\n\n#' Hierarchy plot of cell-cell communications sending to cell groups in vertex.receiver\n#'\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net a weighted matrix defining the signaling network\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether rescale the edge weights\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.dist the distance between labels and dot position\n#' @param space.v the space between different columns in the plot\n#' @param space.h the space between different rows in the plot\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param alpha.edge the transprency of edge\n#' @param label.edge whether label edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_\n#' @importFrom grDevices adjustcolor recordPlot\n#' @importFrom shape Arrows\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_hierarchy1 <- function(net, vertex.receiver, color.use = NULL, title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight=20, vertex.weight.max = NULL, vertex.size.max = NULL,\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6,\n label.dist = 2.8, space.v = 1.5, space.h = 1.6, shape= NULL, label.edge=FALSE,edge.curved=0, margin=0.2,\n vertex.label.cex=0.6,vertex.label.color= \"black\",arrow.width=1,arrow.size = 0.2,edge.label.color='black',edge.label.cex=0.5, vertex.size = NULL){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n cells.level <- rownames(net)\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n if (is.null(color.use)) {\n color.use <- scPalette(nrow(net))\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+6\n\n m <- length(vertex.receiver)\n net2 <- net\n reorder.row <- c(vertex.receiver, setdiff(1:nrow(net),vertex.receiver))\n net2 <- net2[reorder.row,vertex.receiver]\n # Expand out to symmetric (M+N)x(M+N) matrix\n m1 <- nrow(net2); n1 <- ncol(net2)\n net3 <- rbind(cbind(matrix(0, m1, m1), net2), matrix(0, n1, m1+n1))\n\n row.names(net3) <- c(row.names(net)[vertex.receiver], row.names(net)[setdiff(1:m1,vertex.receiver)], rep(\"\",m))\n colnames(net3) <- row.names(net3)\n color.use3 <- c(color.use[vertex.receiver], color.use[setdiff(1:m1,vertex.receiver)], rep(\"#FFFFFF\",length(vertex.receiver)))\n color.use3.frame <- c(color.use[vertex.receiver], color.use[setdiff(1:m1,vertex.receiver)], color.use[vertex.receiver])\n\n if (length(vertex.weight) != 1) {\n vertex.weight = c(vertex.weight[vertex.receiver], vertex.weight[setdiff(1:m1,vertex.receiver)],vertex.weight[vertex.receiver])\n }\n if (is.null(shape)) {\n shape <- c(rep(\"circle\",m), rep(\"circle\", m1-m), rep(\"circle\",m))\n }\n\n g <- graph_from_adjacency_matrix(net3, mode = \"directed\", weighted = T)\n edge.start <- ends(g, es=E(g), names=FALSE)\n coords <- matrix(NA, nrow(net3), 2)\n coords[1:m,1] <- 0; coords[(m+1):m1,1] <- space.h; coords[(m1+1):nrow(net3),1] <- space.h/2;\n coords[1:m,2] <- seq(space.v, 0, by = -space.v/(m-1)); coords[(m+1):m1,2] <- seq(space.v, 0, by = -space.v/(m1-m-1));coords[(m1+1):nrow(net3),2] <- seq(space.v, 0, by = -space.v/(n1-1));\n coords_scale<-coords\n\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use3[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use3.frame[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n E(g)$label<-E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n # E(g)$width<-0.3+edge.max.width/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n E(g)$width<- 0.3+E(g)$weight/edge.weight.max*edge.width.max\n }else{\n E(g)$width<-0.3+edge.width.max*E(g)$weight\n }\n\n E(g)$arrow.width<-arrow.width\n E(g)$arrow.size<-arrow.size\n E(g)$label.color<-edge.label.color\n E(g)$label.cex<-edge.label.cex\n E(g)$color<-adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n\n label.dist <- c(rep(space.h*label.dist,m), rep(space.h*label.dist, m1-m),rep(0, nrow(net3)-m1))\n label.locs <- c(rep(-pi, m), rep(0, m1-m),rep(-pi, nrow(net3)-m1))\n # text.pos <- cbind(c(-space.h/1.5, space.h/10, space.h/1.2), space.v-space.v/10)\n text.pos <- cbind(c(-space.h/1.5, space.h/22, space.h/1.5), space.v-space.v/7)\n igraph::add.vertex.shape(\"fcircle\", clip=igraph::igraph.shape.noclip,plot=mycircle, parameters=list(vertex.frame.color=1, vertex.frame.width=1))\n plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin,rescale=T,vertex.shape=\"fcircle\", vertex.frame.width = c(rep(1,m1), rep(2,nrow(net3)-m1)),\n vertex.label.degree=label.locs, vertex.label.dist=label.dist, vertex.label.family=\"Helvetica\")\n text(text.pos, c(\"Source\",\"Target\",\"Source\"), cex = 0.8, col = c(\"#c51b7d\",\"#c51b7d\",\"#2f6661\"))\n arrow.pos1 <- c(-space.h/1.5, space.v-space.v/4, space.h/100000, space.v-space.v/4)\n arrow.pos2 <- c(space.h/1.5, space.v-space.v/4, space.h/20, space.v-space.v/4)\n shape::Arrows(arrow.pos1[1], arrow.pos1[2], arrow.pos1[3], arrow.pos1[4], col = \"#c51b7d\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n shape::Arrows(arrow.pos2[1], arrow.pos2[2], arrow.pos2[3], arrow.pos2[4], col = \"#2f6661\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n if (!is.null(title.name)) {\n title.pos = c(space.h/8, space.v)\n text(title.pos[1],title.pos[2],paste0(title.name, \" signaling network\"), cex = 1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Hierarchy plot of cell-cell communication sending to cell groups not in vertex.receiver\n#'\n#' This function loads the significant interactions as a weighted matrix, and colors\n#' represent different types of cells as a structure. The width of edges represent the strength of the communication.\n#'\n#' @param net a weighted matrix defining the signaling network\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether rescale the edge weights\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.dist the distance between labels and dot position\n#' @param space.v the space between different columns in the plot\n#' @param space.h the space between different rows in the plot\n#' @param label.edge Whether or not shows the label of edges (number of connections between different cell types)\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_\n#' @importFrom grDevices adjustcolor recordPlot\n#' @importFrom shape Arrows\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_hierarchy2 <-function(net, vertex.receiver, color.use = NULL, title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight=20, vertex.weight.max = NULL, vertex.size.max = NULL,\n edge.weight.max = NULL, edge.width.max=8,alpha.edge = 0.6,\n label.dist = 2.8, space.v = 1.5, space.h = 1.6, shape= NULL, label.edge=FALSE,edge.curved=0, margin=0.2,\n vertex.label.cex=0.6,vertex.label.color= \"black\",arrow.width=1,arrow.size = 0.2,edge.label.color='black',edge.label.cex=0.5, vertex.size = NULL){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- levels(object@idents)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- levels(object@idents)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- levels(object@idents)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n\n if (is.null(color.use)) {\n color.use <- scPalette(nrow(net))\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+6\n\n m <- length(vertex.receiver)\n m0 <- nrow(net)-length(vertex.receiver)\n net2 <- net\n reorder.row <- c(setdiff(1:nrow(net),vertex.receiver), vertex.receiver)\n net2 <- net2[reorder.row,vertex.receiver]\n # Expand out to symmetric (M+N)x(M+N) matrix\n m1 <- nrow(net2); n1 <- ncol(net2)\n net3 <- rbind(cbind(matrix(0, m1, m1), net2), matrix(0, n1, m1+n1))\n row.names(net3) <- c(row.names(net)[setdiff(1:m1,vertex.receiver)],row.names(net)[vertex.receiver], rep(\"\",m))\n colnames(net3) <- row.names(net3)\n color.use3 <- c(color.use[setdiff(1:m1,vertex.receiver)],color.use[vertex.receiver], rep(\"#FFFFFF\",length(vertex.receiver)))\n color.use3.frame <- c(color.use[setdiff(1:m1,vertex.receiver)], color.use[vertex.receiver], color.use[vertex.receiver])\n\n\n if (length(vertex.weight) != 1) {\n vertex.weight = c(vertex.weight[setdiff(1:m1,vertex.receiver)], vertex.weight[vertex.receiver], vertex.weight[vertex.receiver])\n }\n if (is.null(shape)) {\n shape <- rep(\"circle\",nrow(net3))\n }\n\n g <- graph_from_adjacency_matrix(net3, mode = \"directed\", weighted = T)\n edge.start <- ends(g, es=igraph::E(g), names=FALSE)\n coords <- matrix(NA, nrow(net3), 2)\n coords[1:m0,1] <- 0; coords[(m0+1):m1,1] <- space.h; coords[(m1+1):nrow(net3),1] <- space.h/2;\n coords[1:m0,2] <- seq(space.v, 0, by = -space.v/(m0-1)); coords[(m0+1):m1,2] <- seq(space.v, 0, by = -space.v/(m1-m0-1));coords[(m1+1):nrow(net3),2] <- seq(space.v, 0, by = -space.v/(n1-1));\n coords_scale<-coords\n\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use3[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use3.frame[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n # E(g)$width<-0.3+edge.max.width/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n igraph::E(g)$color<-adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n\n label.dist <- c(rep(space.h*label.dist,m), rep(space.h*label.dist, m1-m),rep(0, nrow(net3)-m1))\n label.locs <- c(rep(-pi, m0), rep(0, m1-m0),rep(-pi, nrow(net3)-m1))\n #text.pos <- cbind(c(-space.h/1.5, space.h/10, space.h/1.2), space.v-space.v/10)\n text.pos <- cbind(c(-space.h/1.5, space.h/22, space.h/1.5), space.v-space.v/7)\n igraph::add.vertex.shape(\"fcircle\", clip=igraph::igraph.shape.noclip,plot=mycircle, parameters=list(vertex.frame.color=1, vertex.frame.width=1))\n plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin,rescale=T,vertex.shape=\"fcircle\", vertex.frame.width = c(rep(1,m1), rep(2,nrow(net3)-m1)),\n vertex.label.degree=label.locs, vertex.label.dist=label.dist, vertex.label.family=\"Helvetica\")\n text(text.pos, c(\"Source\",\"Target\",\"Source\"), cex = 0.8, col = c(\"#c51b7d\",\"#2f6661\",\"#2f6661\"))\n\n arrow.pos1 <- c(-space.h/1.5, space.v-space.v/4, space.h/100000, space.v-space.v/4)\n arrow.pos2 <- c(space.h/1.5, space.v-space.v/4, space.h/20, space.v-space.v/4)\n shape::Arrows(arrow.pos1[1], arrow.pos1[2], arrow.pos1[3], arrow.pos1[4], col = \"#c51b7d\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n shape::Arrows(arrow.pos2[1], arrow.pos2[2], arrow.pos2[3], arrow.pos2[4], col = \"#2f6661\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n\n if (!is.null(title.name)) {\n title.pos = c(space.h/8, space.v)\n text(title.pos[1],title.pos[2],paste0(title.name, \" signaling network\"), cex = 1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Circle plot of cell-cell communication network\n#'\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net A weighted matrix representing the connections\n#' @param color.use Colors represent different cell groups\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.edge Whether or not shows the label of edges\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param layout The layout specification. It must be a call to a layout\n#' specification function.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param text.x,text.y the x- and y-coordinates to add the text\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_ in_circle\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_circle <-function(net, color.use = NULL,title.name = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex=1,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6, label.edge = FALSE,edge.label.color='black',edge.label.cex=0.8,\n edge.curved=0.2,shape='circle',layout=in_circle(), margin=0.2, vertex.size = NULL,\n arrow.width=1,arrow.size = 0.2,\n text.x = 0, text.y = 1.5){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use)) | (!is.null(idents.use)) ) {\n if (is.null(rownames(net))) {\n stop(\"The input weighted matrix should have rownames!\")\n }\n cells.level <- rownames(net)\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n df.net <- filter(df.net, (source %in% idents.use) | (target %in% idents.use))\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (is.null(color.use)) {\n color.use = scPalette(nrow(net))\n names(color.use) <- rownames(net)\n } else {\n if (is.null(names(color.use))) {\n stop(\"The input `color.use` should be a named vector! \\n\")\n }\n }\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx.isolate <- intersect(idx1, idx2)\n if (length(idx.isolate) > 0) {\n net <- net[-idx.isolate, ]\n net <- net[, -idx.isolate]\n color.use = color.use[-idx.isolate]\n if (length(unique(vertex.weight)) > 1) {\n vertex.weight <- vertex.weight[-idx.isolate]\n }\n }\n }\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edge.start <- igraph::ends(g, es=igraph::E(g), names=FALSE)\n coords<-layout_(g,layout)\n if(nrow(coords)!=1){\n coords_scale=scale(coords)\n }else{\n coords_scale<-coords\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n\n loop.angle<-ifelse(coords_scale[igraph::V(g),1]>0,-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]),pi-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]))\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n #E(g)$width<-0.3+edge.width.max/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n igraph::E(g)$color<- grDevices::adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n igraph::E(g)$loop.angle <- rep(0, length(igraph::E(g)))\n\n if(sum(edge.start[,2]==edge.start[,1])!=0){\n igraph::E(g)$loop.angle[which(edge.start[,2]==edge.start[,1])]<-loop.angle[edge.start[which(edge.start[,2]==edge.start[,1]),1]]\n }\n radian.rescale <- function(x, start=0, direction=1) {\n c.rotate <- function(x) (x + start) %% (2 * pi) * direction\n c.rotate(scales::rescale(x, c(0, 2 * pi), range(x)))\n }\n label.locs <- radian.rescale(x=1:length(igraph::V(g)), direction=-1, start=0)\n label.dist <- vertex.weight/max(vertex.weight)+2\n plot(g,edge.curved=edge.curved,vertex.shape=shape,layout=coords_scale,margin=margin, vertex.label.dist=label.dist,\n vertex.label.degree=label.locs, vertex.label.family=\"Helvetica\", edge.label.family=\"Helvetica\") # \"sans\"\n if (!is.null(title.name)) {\n text(text.x,text.y,title.name, cex = 1.1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n\n#' generate circle symbol\n#'\n#' @param coords coordinates of points\n#' @param v vetex\n#' @param params parameters\n#' @importFrom graphics symbols\n#' @return\nmycircle <- function(coords, v=NULL, params) {\n vertex.color <- params(\"vertex\", \"color\")\n if (length(vertex.color) != 1 && !is.null(v)) {\n vertex.color <- vertex.color[v]\n }\n vertex.size <- 1/200 * params(\"vertex\", \"size\")\n if (length(vertex.size) != 1 && !is.null(v)) {\n vertex.size <- vertex.size[v]\n }\n vertex.frame.color <- params(\"vertex\", \"frame.color\")\n if (length(vertex.frame.color) != 1 && !is.null(v)) {\n vertex.frame.color <- vertex.frame.color[v]\n }\n vertex.frame.width <- params(\"vertex\", \"frame.width\")\n if (length(vertex.frame.width) != 1 && !is.null(v)) {\n vertex.frame.width <- vertex.frame.width[v]\n }\n\n mapply(coords[,1], coords[,2], vertex.color, vertex.frame.color,\n vertex.size, vertex.frame.width,\n FUN=function(x, y, bg, fg, size, lwd) {\n symbols(x=x, y=y, bg=bg, fg=fg, lwd=lwd,\n circles=size, add=TRUE, inches=FALSE)\n })\n}\n\n\n#' Spatial plot of cell-cell communication network\n#'\n#' Autocrine interactions are omitted on this plot. Group centroids may be not accurate for some data due to complex geometry.\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net A weighted matrix representing the connections\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param meta a data frame with at least two columns named `labels` and `samples`.\n#' `meta$labels` is a vector giving the group label of each cell/spot. `meta$samples` is a factor vector defining the sample labels of each dataset. The length should be the same as the number of rows in `coordinates`.\n#' @param sample.use the sample used for visualization, which should be the element in `meta$samples`.\n#' @param color.use Colors represent different cell groups\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param remove.loop whether remove the self-loop in the communication network. Default: TRUE\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param alpha.edge the transprency of edge\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param arrow.angle The width of arrows\n#' @param alpha.image the transparency of individual spots\n# #' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param point.size the size of spots\n#' @param legend.size the size of legend\n#' @importFrom igraph graph_from_adjacency_matrix get.edgelist ends E V\n#' @import ggplot2\n#' @importFrom ggnetwork geom_nodetext_repel\n#' @return an object of ggplot\n#' @export\nnetVisual_spatial <-function(net, coordinates, meta, sample.use = NULL, color.use = NULL,title.name = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE, remove.loop = TRUE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex = 5,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, edge.curved=0.2, alpha.edge = 0.6, arrow.angle = 5, arrow.size = 0.2, alpha.image = 0.15, point.size = 1.5, legend.size = 5){\n cells.level <- rownames(net)\n labels <- meta$labels\n samples <- meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n num_cluster <- length(cells.level)\n node_coords <- matrix(0, nrow = num_cluster, ncol = 2)\n for (i in c(1:num_cluster)) {\n node_coords[i,1] <- median(coordinates[as.character(labels) == cells.level[i], 1])\n node_coords[i,2] <- median(coordinates[as.character(labels) == cells.level[i], 2])\n }\n rownames(node_coords) <- cells.level\n\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use)) | (!is.null(idents.use)) ) {\n if (is.null(rownames(net))) {\n stop(\"The input weighted matrix should have rownames!\")\n }\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n df.net <- filter(df.net, (source %in% idents.use) | (target %in% idents.use))\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n\n if (remove.loop) {\n diag(net) <- 0\n }\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n node_coords <- node_coords[-idx, ]\n cells.level <- cells.level[-idx]\n }\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edgelist <- get.edgelist(g)\n # loop_curve = c()\n # for (i in c(1:nrow(edgelist))) {\n # if (edgelist[i,1] == edgelist[i,2]){\n # loop_curve = c(loop_curve ,i)\n # }\n # }\n # edgelist <- edgelist[-loop_curve,]\n\n edges <- data.frame(node_coords[edgelist[,1],,drop =FALSE], node_coords[edgelist[,2],,drop =FALSE])\n colnames(edges) <- c(\"X1\",\"Y1\",\"X2\",\"Y2\")\n node_coords = data.frame(node_coords)\n node_idents = factor(cells.level, levels = cells.level)\n node_family = data.frame(node_coords,node_idents)\n if (is.null(color.use)) {\n color.use = scPalette(length(igraph::V(g)))\n names(color.use) <- cells.level\n }\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n # width of edge\n if (weight.scale == TRUE) {\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n gg <- ggplot(data=node_family,aes(X1, X2)) +\n geom_curve(aes(x=X1, y=Y1, xend = X2, yend = Y2), data=edges, size = igraph::E(g)$width, curvature = edge.curved, alpha = alpha.edge, arrow = arrow(angle = arrow.angle, type = \"closed\",length = unit(arrow.size, \"inches\")),colour=color.use[edgelist[,1]]) +\n geom_point(aes(X1, X2,colour = node_idents), data=node_family, size = vertex.weight,show.legend = TRUE) +scale_color_manual(values = color.use) +\n guides(color = guide_legend(override.aes = list(size=legend.size))) +\n xlab(NULL) + ylab(NULL) +\n coord_fixed() + theme(aspect.ratio = 1)+ theme(legend.key = element_blank()) +\n theme(panel.background = element_blank(),axis.ticks = element_blank(), panel.border = element_blank(),axis.text=element_blank(),legend.title = element_blank())\n\n gg <- gg + geom_point(aes(x_cent, y_cent), data = coordinates,colour = color.use[labels],alpha = alpha.image, size = point.size, show.legend = FALSE)\n gg <- gg + scale_y_reverse()\n if (vertex.label.cex > 0){\n gg <- gg + ggnetwork::geom_nodetext_repel(aes(label = node_idents), color=\"black\", size = vertex.label.cex)\n }\n if (!is.null(title.name)){\n gg <- gg + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0))\n }\n\n gg\n return(gg)\n\n}\n\n\n\n\n\n\n#' Circle plot showing differential cell-cell communication network between two datasets\n#'\n#' The width of edges represent the relative number of interactions or interaction strength.\n#' Red (or blue) colored edges represent increased (or decreased) signaling in the second dataset compared to the first one.\n#'\n#' @param object A merged CellChat objects\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param color.use Colors represent different cell groups\n#' @param color.edge Colors for indicating whether the signaling is increased (`color.edge[1]`) or decreased (`color.edge[2]`)\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.edge Whether or not shows the label of edges\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param layout The layout specification. It must be a call to a layout\n#' specification function.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n# #' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_ in_circle\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_diffInteraction <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\", \"count.merged\", \"weight.merged\"), color.use = NULL, color.edge = c('#b2182b','#2166ac'), title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = 15, vertex.label.cex=1,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6, label.edge = FALSE,edge.label.color='black',edge.label.cex=0.8,\n edge.curved=0.2,shape='circle',layout=in_circle(), margin=0.2,\n arrow.width=1,arrow.size = 0.2){\n options(warn = -1)\n measure <- match.arg(measure)\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n if (measure %in% c(\"count\", \"count.merged\")) {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure %in% c(\"weight\", \"weight.merged\")) {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n net <- net.diff\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- rownames(net.diff)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n net[is.na(net)] <- 0\n }\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n net[abs(net) < stats::quantile(abs(net), probs = 1-top, na.rm= T)] <- 0\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edge.start <- igraph::ends(g, es=igraph::E(g), names=FALSE)\n coords<-layout_(g,layout)\n if(nrow(coords)!=1){\n coords_scale=scale(coords)\n }else{\n coords_scale<-coords\n }\n if (is.null(color.use)) {\n color.use = scPalette(length(igraph::V(g)))\n }\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n\n loop.angle<-ifelse(coords_scale[igraph::V(g),1]>0,-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]),pi-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]))\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n #igraph::E(g)$color<- grDevices::adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n igraph::E(g)$color <- ifelse(igraph::E(g)$weight > 0, color.edge[1],color.edge[2])\n igraph::E(g)$color <- grDevices::adjustcolor(igraph::E(g)$color, alpha.edge)\n\n igraph::E(g)$weight <- abs(igraph::E(g)$weight)\n\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n #E(g)$width<-0.3+edge.width.max/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n igraph::E(g)$loop.angle <- 0\n if(sum(edge.start[,2]==edge.start[,1])!=0){\n igraph::E(g)$loop.angle[which(edge.start[,2]==edge.start[,1])]<-loop.angle[edge.start[which(edge.start[,2]==edge.start[,1]),1]]\n }\n radian.rescale <- function(x, start=0, direction=1) {\n c.rotate <- function(x) (x + start) %% (2 * pi) * direction\n c.rotate(scales::rescale(x, c(0, 2 * pi), range(x)))\n }\n label.locs <- radian.rescale(x=1:length(igraph::V(g)), direction=-1, start=0)\n label.dist <- vertex.weight/max(vertex.weight)+2\n plot(g,edge.curved=edge.curved,vertex.shape=shape,layout=coords_scale,margin=margin, vertex.label.dist=label.dist,\n vertex.label.degree=label.locs, vertex.label.family=\"Helvetica\", edge.label.family=\"Helvetica\") # \"sans\"\n if (!is.null(title.name)) {\n text(0,1.5,title.name, cex = 1.1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Visualization of network using heatmap\n#'\n#' This heatmap can be used to 1) show differential number of interactions or interaction strength in the cell-cell communication network between two datasets;\n#' 2) the number of interactions or interaction strength in a single dataset;\n#' 3) the inferred cell-cell communication network in a single dataset, defined by `signaling`. Please see @Details below for detailed explanations of this heatmap plot.\n#'\n#' When show differential number of interactions or interaction strength in the cell-cell communication network between two datasets, the width of edges represent the relative number of interactions or interaction strength.\n#' Red (or blue) colored edges represent increased (or decreased) signaling in the second dataset compared to the first one.\n#'\n#' The top colored bar plot represents the sum of absolute values displayed in each column of the heatmap. The right colored bar plot represents the sum of absolute values in each row.\n#'\n#'\n#' @param object A merged CellChat object or a single CellChat object\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param signaling a character vector giving the name of signaling networks in a single CellChat object\n#' @param slot.name the slot name of object. Set is to be \"netP\" if input signaling is a pathway name; Set is to be \"net\" if input signaling is a ligand-receptor pair\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap A vector of two colors corresponding to max/min values, or a color name in brewer.pal only when the data in the heatmap do not contain negative values.\n#' By default, color.heatmap = c('#2166ac','#b2182b') when taking a merged CellChat object as input; color.heatmap = \"Reds\" when taking a single CellChat object as input.\n#' @param title.name the name of the title\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param row.show,col.show a vector giving the index or the name of row or columns to show in the heatmap\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation anno_barplot rowAnnotation\n#' @return an object of ComplexHeatmap\n#' @export\nnetVisual_heatmap <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\"), signaling = NULL, slot.name = c(\"netP\", \"net\"), color.use = NULL, color.heatmap = NULL,\n title.name = NULL, width = NULL, height = NULL, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE,\n sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, row.show = NULL, col.show = NULL){\n if (!is.null(measure)) {\n measure <- match.arg(measure)\n }\n slot.name <- match.arg(slot.name)\n if (class(object@net[[1]]) == \"list\") {\n message(\"Do heatmap based on a merged object \\n\")\n if (is.null(color.heatmap)) {\n color.heatmap <- c('#2166ac','#b2182b')\n }\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n legend.name = \"Relative values\"\n } else {\n message(\"Do heatmap based on a single object \\n\")\n if (is.null(color.heatmap)) {\n color.heatmap <- \"Reds\"\n }\n if (!is.null(signaling)) {\n prob <- slot(object, slot.name)$prob\n if (slot.name == \"net\") {\n prob[object@net$pval > thresh] <- 0\n }\n net.diff <- prob[,,signaling]\n if (is.null(title.name)) {\n title.name = paste0(signaling, \" signaling network\")\n }\n legend.name <- \"Communication Prob.\"\n } else if (!is.null(measure)) {\n net.diff <- object@net[[measure]]\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Interaction strength\"\n }\n }\n legend.name <- title.name\n }\n }\n\n net <- net.diff\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- rownames(net.diff)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (is.null(color.use)) {\n color.use <- scPalette(ncol(net))\n }\n names(color.use) <- colnames(net)\n color.use.row <- color.use\n color.use.col <- color.use\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n #idx <- intersect(idx1, idx2)\n # if (length(idx) > 0) {\n # net <- net[-idx, ]\n # net <- net[, -idx]\n # }\n if (length(idx1) > 0) {\n net <- net[-idx1, ]\n color.use.row <- color.use.row[-idx1]\n }\n if (length(idx2) > 0) {\n net <- net[, -idx2]\n color.use.col <- color.use.col[-idx2]\n }\n }\n\n mat <- net\n if (!is.null(row.show)) {\n mat <- mat[row.show, , drop=FALSE]\n color.use.row <- color.use.row[row.show]\n }\n if (!is.null(col.show)) {\n mat <- mat[ ,col.show, drop=FALSE]\n color.use.col <- color.use.col[col.show]\n }\n\n\n if (min(mat) < 0) {\n color.heatmap.use = colorRamp3(c(min(mat), 0, max(mat)), c(color.heatmap[1], \"#f7f7f7\", color.heatmap[2]))\n colorbar.break <- c(round(min(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",min(mat, na.rm = T)))+1), 0, round(max(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",max(mat, na.rm = T)))+1))\n # color.heatmap.use = colorRamp3(c(seq(min(mat), -(max(mat)-min(max(mat)))/9, length.out = 4), 0, seq((max(mat)-min(max(mat)))/9, max(mat), length.out = 4)), RColorBrewer::brewer.pal(n = 9, name = color.heatmap))\n } else {\n if (length(color.heatmap) == 3) {\n color.heatmap.use = colorRamp3(c(0, min(mat), max(mat)), color.heatmap)\n } else if (length(color.heatmap) == 2) {\n color.heatmap.use = colorRamp3(c(min(mat), max(mat)), color.heatmap)\n } else if (length(color.heatmap) == 1) {\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n }\n colorbar.break <- c(round(min(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",min(mat, na.rm = T)))+1), round(max(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",max(mat, na.rm = T)))+1))\n }\n # col_fun(as.vector(mat))\n\n df.col<- data.frame(group = colnames(mat)); rownames(df.col) <- colnames(mat)\n df.row<- data.frame(group = rownames(mat)); rownames(df.row) <- rownames(mat)\n col_annotation <- HeatmapAnnotation(df = df.col, col = list(group = color.use.col),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n row_annotation <- HeatmapAnnotation(df = df.row, col = list(group = color.use.row), which = \"row\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ha1 = rowAnnotation(Strength = anno_barplot(rowSums(abs(mat)), border = FALSE,gp = gpar(fill = color.use.row, col=color.use.row)), show_annotation_name = FALSE)\n ha2 = HeatmapAnnotation(Strength = anno_barplot(colSums(abs(mat)), border = FALSE,gp = gpar(fill = color.use.col, col=color.use.col)), show_annotation_name = FALSE)\n\n if (sum(abs(mat) > 0) == 1) {\n color.heatmap.use = c(\"white\", color.heatmap.use)\n } else {\n mat[mat == 0] <- NA\n }\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = legend.name,\n bottom_annotation = col_annotation, left_annotation =row_annotation, top_annotation = ha2, right_annotation = ha1,\n cluster_rows = cluster.rows,cluster_columns = cluster.rows,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n # width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = title.name,column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 90,\n row_title = \"Sources (Sender)\",row_title_gp = gpar(fontsize = font.size.title),row_title_rot = 90,\n heatmap_legend_param = list(title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, #at = colorbar.break,\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n # draw(ht1)\n return(ht1)\n}\n\n\n#' Visualization of (differential) number of interactions\n#'\n#' @param object A merged CellChat object or a single CellChat object\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param invert.source,invert.target retain the complementary set\n#' @param signaling a character vector giving the name of signaling networks in a single CellChat object\n#' @param slot.name the slot name of object. Set is to be \"netP\" if input signaling is a pathway name; Set is to be \"net\" if input signaling is a ligand-receptor pair\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name the name of the title\n#' @param x.lab.rot do rotation for the x-ticklabels\n#' @param ... Parameters passing to `barplot_internal`\n#' @importFrom methods slot\n#' @return an object of ggplot\n#' @export\nnetVisual_barplot <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\"), sources.use = NULL, targets.use = NULL, invert.source = FALSE, invert.target = FALSE,signaling = NULL, slot.name = c(\"netP\", \"net\"), color.use = NULL,\n title.name = NULL,x.lab.rot = FALSE,...){\n if (!is.null(measure)) {\n measure <- match.arg(measure)\n }\n slot.name <- match.arg(slot.name)\n if (is.list(object@net[[1]])) {\n message(\"Show differential number of interactions based on a merged object \\n\")\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n } else {\n message(\"Show number of interactions based on a single object \\n\")\n if (!is.null(signaling)) {\n net.diff <- slot(object, slot.name)$prob[,,signaling]\n if (is.null(title.name)) {\n title.name = paste0(signaling, \" signaling network\")\n }\n } else if (!is.null(measure)) {\n net.diff <- object@net[[measure]]\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Interaction strength\"\n }\n }\n }\n }\n\n net <- net.diff\n cells.level <- rownames(net.diff)\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n if (invert.source == TRUE) {\n sources.use <- setdiff(rownames(net.diff), sources.use)\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n if (invert.target == TRUE) {\n targets.use <- setdiff(rownames(net.diff), targets.use)\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n }\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(cells.level))\n }\n names(color.use) <- cells.level\n color.use <- color.use[cells.level %in% unique(df.net$target)]\n\n gg <- barplot_internal(df.net, x = \"target\", y = \"value\", fill = \"target\", color.use = color.use, title.name = title.name,x.lab.rot = x.lab.rot,...)\n\n return(gg)\n\n}\n\n\n#' Show all the significant interactions (L-R pairs) from some cell groups to other cell groups\n#'\n#' The dot color and size represent the calculated communication probability and p-values.\n#'\n#' @param object CellChat object\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest and the order of L-R on y-axis\n#' @param sort.by.source,sort.by.target,sort.by.source.priority set the order of interacting cell pairs on x-axis; please check examples for details\n#' @param color.heatmap A character string or vector indicating the colormap option to use. It can be the avaibale color palette in viridis_pal() or brewer.pal()\n#' @param direction Sets the order of colors in the scale. If 1, the default colors are used. If -1, the order of colors is reversed.\n#' @param n.colors number of basic colors to generate from color palette\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param comparison a numerical vector giving the datasets for comparison in the merged object; e.g., comparison = c(1,2)\n#' @param group a numerical vector giving the group information of different datasets; e.g., group = c(1,2,2)\n#' @param remove.isolate whether to remove the entire empty columns, i.e., communication between certain cell groups\n#' @param max.dataset a scale, keeping the communications with highest probability in max.dataset (i.e., certrain condition)\n#' @param min.dataset a scale, keeping the communications with lowest probability in min.dataset (i.e., certrain condition)\n#' @param min.quantile,max.quantile minimum and maximum quantile cutoff values for the colorbar, may specify quantile in [0,1]\n#' @param line.on whether to add vertical line when doing comparison analysis for the merged object\n#' @param line.size size of vertical line if added\n#' @param color.text.use whether to color the xtick labels according to the dataset origin when doing comparison analysis\n#' @param color.text the colors for xtick labels according to the dataset origin when doing comparison analysis\n#' @param dot.size.min,dot.size.max Size of smallest and largest points\n#' @param title.name main title of the plot\n#' @param font.size,font.size.title font size of all the text and the title name\n#' @param show.legend whether to show legend\n#' @param grid.on,color.grid whether to add grid\n#' @param angle.x,vjust.x,hjust.x parameters for adjusting the rotation of xtick labels\n#' @param return.data whether to return the data.frame for replotting\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # show all the significant interactions (L-R pairs) from some cell groups (defined by 'sources.use') to other cell groups (defined by 'targets.use')\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), remove.isolate = FALSE)\n#'\n#' # show all the significant interactions (L-R pairs) associated with certain signaling pathways\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), signaling = c(\"CCL\",\"CXCL\"))\n#'\n#' # show all the significant interactions (L-R pairs) based on user's input (defined by `pairLR.use`; the order of L-R is also based on user's input)\n#' pairLR.use <- extractEnrichedLR(cellchat, signaling = c(\"CCL\",\"CXCL\",\"FGF\"))\n#' netVisual_bubble(cellchat, sources.use = c(3,4), targets.use = c(5:8), pairLR.use = pairLR.use, remove.isolate = TRUE)\n#'\n#' # set the order of interacting cell pairs on x-axis\n#' # (1) Default: first sort cell pairs based on the appearance of sources in levels(object@idents), and then based on the appearance of targets in levels(object@idents)\n#' # (2) sort cell pairs based on the targets.use defined by users\n#' netVisual_bubble(cellchat, targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.target = T)\n#' # (3) sort cell pairs based on the sources.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T)\n#' # (4) sort cell pairs based on the sources.use and then targets.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T, sort.by.target = T)\n#' # (5) sort cell pairs based on the targets.use and then sources.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T, sort.by.target = T, sort.by.source.priority = FALSE)\n#'\n#'# show all the increased interactions in the second dataset compared to the first dataset\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:8), remove.isolate = TRUE, max.dataset = 2)\n#'\n#'# show all the decreased interactions in the second dataset compared to the first dataset\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:8), remove.isolate = TRUE, max.dataset = 1)\n#'}\nnetVisual_bubble <- function(object, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR.use = NULL, sort.by.source = FALSE, sort.by.target = FALSE, sort.by.source.priority = TRUE, color.heatmap = c(\"Spectral\",\"viridis\"), n.colors = 10, direction = -1, thresh = 0.05,\n comparison = NULL, group = NULL, remove.isolate = FALSE, max.dataset = NULL, min.dataset = NULL,\n min.quantile = 0, max.quantile = 1, line.on = TRUE, line.size = 0.2, color.text.use = TRUE, color.text = NULL, dot.size.min = NULL, dot.size.max = NULL,\n title.name = NULL, font.size = 10, font.size.title = 10, show.legend = TRUE,\n grid.on = TRUE, color.grid = \"grey90\", angle.x = 90, vjust.x = NULL, hjust.x = NULL,\n return.data = FALSE){\n color.heatmap <- match.arg(color.heatmap)\n if (is.list(object@net[[1]])) {\n message(\"Comparing communications on a merged object \\n\")\n } else {\n message(\"Comparing communications on a single object \\n\")\n }\n if (is.null(vjust.x) | is.null(hjust.x)) {\n angle=c(0, 45, 90)\n hjust=c(0, 1, 1)\n vjust=c(0, 1, 0.5)\n vjust.x = vjust[angle == angle.x]\n hjust.x = hjust[angle == angle.x]\n }\n if (length(color.heatmap) == 1) {\n color.use <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n scales::viridis_pal(option = color.heatmap, direction = -1)(n.colors)\n })\n } else {\n color.use <- color.heatmap\n }\n if (direction == -1) {\n color.use <- rev(color.use)\n }\n\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n pairLR.use$pathway_name <- as.character(pairLR.use$pathway_name)\n } else if (\"interaction_name\" %in% colnames(pairLR.use)) {\n pairLR.use$interaction_name <- as.character(pairLR.use$interaction_name)\n }\n }\n\n if (is.null(comparison)) {\n cells.level <- levels(object@idents)\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.net$source.target <- paste(df.net$source, df.net$target, sep = \" -> \")\n source.target <- paste(rep(sources.use, each = length(targets.use)), targets.use, sep = \" -> \")\n source.target.isolate <- setdiff(source.target, unique(df.net$source.target))\n if (length(source.target.isolate) > 0) {\n df.net.isolate <- as.data.frame(matrix(NA, nrow = length(source.target.isolate), ncol = ncol(df.net)))\n colnames(df.net.isolate) <- colnames(df.net)\n df.net.isolate$source.target <- source.target.isolate\n df.net.isolate$interaction_name_2 <- df.net$interaction_name_2[1]\n df.net.isolate$pval <- 1\n a <- stringr::str_split(df.net.isolate$source.target, \" -> \", simplify = T)\n df.net.isolate$source <- as.character(a[, 1])\n df.net.isolate$target <- as.character(a[, 2])\n df.net <- rbind(df.net, df.net.isolate)\n }\n\n df.net$pval[df.net$pval > 0.05] = 1\n df.net$pval[df.net$pval > 0.01 & df.net$pval <= 0.05] = 2\n df.net$pval[df.net$pval <= 0.01] = 3\n df.net$prob[df.net$prob == 0] <- NA\n df.net$prob.original <- df.net$prob\n df.net$prob <- -1/log(df.net$prob)\n\n idx1 <- which(is.infinite(df.net$prob) | df.net$prob < 0)\n if (sum(idx1) > 0) {\n values.assign <- seq(max(df.net$prob, na.rm = T)*1.1, max(df.net$prob, na.rm = T)*1.5, length.out = length(idx1))\n position <- sort(prob.original[idx1], index.return = TRUE)$ix\n df.net$prob[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n # rownames(df.net) <- df.net$interaction_name_2\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n group.names <- paste(rep(levels(df.net$source), each = length(levels(df.net$target))), levels(df.net$target), sep = \" -> \")\n\n df.net$interaction_name_2 <- as.character(df.net$interaction_name_2)\n df.net <- with(df.net, df.net[order(interaction_name_2),])\n df.net$interaction_name_2 <- factor(df.net$interaction_name_2, levels = unique(df.net$interaction_name_2))\n cells.order <- group.names\n df.net$source.target <- factor(df.net$source.target, levels = cells.order)\n df <- df.net\n } else {\n dataset.name <- names(object@net)\n df.net.all <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.all <- data.frame()\n for (ii in 1:length(comparison)) {\n cells.level <- levels(object@idents[[comparison[ii]]])\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n\n df.net <- df.net.all[[comparison[ii]]]\n df.net$interaction_name_2 <- as.character(df.net$interaction_name_2)\n df.net$source.target <- paste(df.net$source, df.net$target, sep = \" -> \")\n source.target <- paste(rep(sources.use, each = length(targets.use)), targets.use, sep = \" -> \")\n source.target.isolate <- setdiff(source.target, unique(df.net$source.target))\n if (length(source.target.isolate) > 0) {\n df.net.isolate <- as.data.frame(matrix(NA, nrow = length(source.target.isolate), ncol = ncol(df.net)))\n colnames(df.net.isolate) <- colnames(df.net)\n df.net.isolate$source.target <- source.target.isolate\n df.net.isolate$interaction_name_2 <- df.net$interaction_name_2[1]\n df.net.isolate$pval <- 1\n a <- stringr::str_split(df.net.isolate$source.target, \" -> \", simplify = T)\n df.net.isolate$source <- as.character(a[, 1])\n df.net.isolate$target <- as.character(a[, 2])\n df.net <- rbind(df.net, df.net.isolate)\n }\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n group.names <- paste(rep(levels(df.net$source), each = length(levels(df.net$target))), levels(df.net$target), sep = \" -> \")\n group.names0 <- group.names\n group.names <- paste0(group.names0, \" (\", dataset.name[comparison[ii]], \")\")\n\n if (nrow(df.net) > 0) {\n df.net$pval[df.net$pval > 0.05] = 1\n df.net$pval[df.net$pval > 0.01 & df.net$pval <= 0.05] = 2\n df.net$pval[df.net$pval <= 0.01] = 3\n df.net$prob[df.net$prob == 0] <- NA\n df.net$prob.original <- df.net$prob\n df.net$prob <- -1/log(df.net$prob)\n } else {\n df.net <- as.data.frame(matrix(NA, nrow = length(group.names), ncol = 5))\n colnames(df.net) <- c(\"interaction_name_2\",\"source.target\",\"prob\",\"pval\",\"prob.original\")\n df.net$source.target <- group.names0\n }\n # df.net$group.names <- sub(paste0(' \\\\(',dataset.name[comparison[ii]],'\\\\)'),'',as.character(df.net$source.target))\n df.net$group.names <- as.character(df.net$source.target)\n df.net$source.target <- paste0(df.net$source.target, \" (\", dataset.name[comparison[ii]], \")\")\n df.net$dataset <- dataset.name[comparison[ii]]\n df.all <- rbind(df.all, df.net)\n }\n if (nrow(df.all) == 0) {\n stop(\"No interactions are detected. Please consider changing the cell groups for analysis. \")\n }\n\n idx1 <- which(is.infinite(df.all$prob) | df.all$prob < 0)\n if (sum(idx1) > 0) {\n values.assign <- seq(max(df.all$prob, na.rm = T)*1.1, max(df.all$prob, na.rm = T)*1.5, length.out = length(idx1))\n position <- sort(df.all$prob.original[idx1], index.return = TRUE)$ix\n df.all$prob[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n\n df.all$interaction_name_2[is.na(df.all$interaction_name_2)] <- df.all$interaction_name_2[!is.na(df.all$interaction_name_2)][1]\n\n df <- df.all\n df <- with(df, df[order(interaction_name_2),])\n df$interaction_name_2 <- factor(df$interaction_name_2, levels = unique(df$interaction_name_2))\n\n cells.order <- c()\n dataset.name.order <- c()\n for (i in 1:length(group.names0)) {\n for (j in 1:length(comparison)) {\n cells.order <- c(cells.order, paste0(group.names0[i], \" (\", dataset.name[comparison[j]], \")\"))\n dataset.name.order <- c(dataset.name.order, dataset.name[comparison[j]])\n }\n }\n df$source.target <- factor(df$source.target, levels = cells.order)\n }\n\n min.cutoff <- quantile(df$prob, min.quantile,na.rm= T)\n max.cutoff <- quantile(df$prob, max.quantile,na.rm= T)\n df$prob[df$prob < min.cutoff] <- min.cutoff\n df$prob[df$prob > max.cutoff] <- max.cutoff\n\n\n if (remove.isolate) {\n df <- df[!is.na(df$prob), ]\n line.on <- FALSE\n }\n if (!is.null(max.dataset)) {\n # line.on <- FALSE\n # df <- df[!is.na(df$prob),]\n signaling <- as.character(unique(df$interaction_name_2))\n for (i in signaling) {\n df.i <- df[df$interaction_name_2 == i, ,drop = FALSE]\n cell <- as.character(unique(df.i$group.names))\n for (j in cell) {\n df.i.j <- df.i[df.i$group.names == j, , drop = FALSE]\n values <- df.i.j$prob\n idx.max <- which(values == max(values, na.rm = T))\n idx.min <- which(values == min(values, na.rm = T))\n #idx.na <- c(which(is.na(values)), which(!(dataset.name[comparison] %in% df.i.j$dataset)))\n dataset.na <- c(df.i.j$dataset[is.na(values)], setdiff(dataset.name[comparison], df.i.j$dataset))\n if (length(idx.max) > 0) {\n if (all(!(df.i.j$dataset[idx.max] %in% dataset.name[max.dataset]))) {\n df.i.j$prob <- NA\n } else if (all((idx.max != idx.min) & !is.null(min.dataset))) {\n if (all(!(df.i.j$dataset[idx.min] %in% dataset.name[min.dataset]))) {\n df.i.j$prob <- NA\n } else if (length(dataset.na) > 0 & sum(!(dataset.name[min.dataset] %in% dataset.na)) > 0) {\n df.i.j$prob <- NA\n }\n }\n }\n df.i[df.i$group.names == j, \"prob\"] <- df.i.j$prob\n }\n df[df$interaction_name_2 == i, \"prob\"] <- df.i$prob\n }\n #df <- df[!is.na(df$prob), ]\n }\n if (remove.isolate) {\n df <- df[!is.na(df$prob), ]\n line.on <- FALSE\n }\n if (nrow(df) == 0) {\n stop(\"No interactions are detected. Please consider changing the cell groups for analysis. \")\n }\n # Re-order y-axis\n if (!is.null(pairLR.use)) {\n interaction_name_2.order <- intersect(object@DB$interaction[pairLR.use$interaction_name, ]$interaction_name_2, unique(df$interaction_name_2))\n df$interaction_name_2 <- factor(df$interaction_name_2, levels = interaction_name_2.order)\n }\n\n # Re-order x-axis\n df$source.target = droplevels(df$source.target, exclude = setdiff(levels(df$source.target),unique(df$source.target)))\n if (sort.by.target & !sort.by.source) {\n if (!is.null(targets.use)) {\n df$target <- factor(df$target, levels = intersect(targets.use, df$target))\n df <- with(df, df[order(target, source),])\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n if (sort.by.source & !sort.by.target) {\n if (!is.null(sources.use)) {\n df$source <- factor(df$source, levels = intersect(sources.use, df$source))\n df <- with(df, df[order(source, target),])\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n if (sort.by.source & sort.by.target) {\n if (!is.null(sources.use)) {\n df$source <- factor(df$source, levels = intersect(sources.use, df$source))\n if (!is.null(targets.use)) {\n df$target <- factor(df$target, levels = intersect(targets.use, df$target))\n }\n if (sort.by.source.priority) {\n df <- with(df, df[order(source, target),])\n } else {\n df <- with(df, df[order(target, source),])\n }\n\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n\n g <- ggplot(df, aes(x = source.target, y = interaction_name_2, color = prob, size = pval)) +\n geom_point(pch = 16) +\n theme_linedraw() + theme(panel.grid.major = element_blank()) +\n theme(axis.text.x = element_text(angle = angle.x, hjust= hjust.x, vjust = vjust.x),\n axis.title.x = element_blank(),\n axis.title.y = element_blank()) +\n scale_x_discrete(position = \"bottom\")\n\n values <- c(1,2,3); names(values) <- c(\"p > 0.05\", \"0.01 < p < 0.05\",\"p < 0.01\")\n if (is.null(dot.size.max)) {\n dot.size.max = max(df$pval)\n }\n if (is.null(dot.size.min)) {\n dot.size.min = min(df$pval)\n }\n g <- g + scale_radius(range = c(dot.size.min, dot.size.max), breaks = sort(unique(df$pval)),labels = names(values)[values %in% sort(unique(df$pval))], name = \"p-value\")\n #g <- g + scale_radius(range = c(1,3), breaks = values,labels = names(values), name = \"p-value\")\n if (min(df$prob, na.rm = T) != max(df$prob, na.rm = T)) {\n g <- g + scale_colour_gradientn(colors = colorRampPalette(color.use)(99), na.value = \"white\", limits=c(quantile(df$prob, 0,na.rm= T), quantile(df$prob, 1,na.rm= T)),\n breaks = c(quantile(df$prob, 0,na.rm= T), quantile(df$prob, 1,na.rm= T)), labels = c(\"min\",\"max\")) +\n guides(color = guide_colourbar(barwidth = 0.5, title = \"Commun. Prob.\"))\n } else {\n g <- g + scale_colour_gradientn(colors = colorRampPalette(color.use)(99), na.value = \"white\") +\n guides(color = guide_colourbar(barwidth = 0.5, title = \"Commun. Prob.\"))\n }\n\n g <- g + theme(text = element_text(size = font.size),plot.title = element_text(size=font.size.title)) +\n theme(legend.title = element_text(size = 8), legend.text = element_text(size = 6))\n\n if (grid.on) {\n if (length(unique(df$source.target)) > 1) {\n g <- g + geom_vline(xintercept=seq(1.5, length(unique(df$source.target))-0.5, 1),lwd=0.1,colour=color.grid)\n }\n if (length(unique(df$interaction_name_2)) > 1) {\n g <- g + geom_hline(yintercept=seq(1.5, length(unique(df$interaction_name_2))-0.5, 1),lwd=0.1,colour=color.grid)\n }\n }\n if (!is.null(title.name)) {\n g <- g + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5))\n }\n\n if (!is.null(comparison)) {\n if (line.on) {\n xintercept = seq(0.5+length(dataset.name[comparison]), length(group.names0)*length(dataset.name[comparison]), by = length(dataset.name[comparison]))\n g <- g + geom_vline(xintercept = xintercept, linetype=\"dashed\", color = \"grey60\", size = line.size)\n }\n if (color.text.use) {\n if (is.null(group)) {\n group <- 1:length(comparison)\n names(group) <- dataset.name[comparison]\n }\n if (is.null(color.text)) {\n color <- ggPalette(length(unique(group)))\n } else {\n color <- color.text\n }\n names(color) <- names(group[!duplicated(group)])\n color <- color[group]\n #names(color) <- dataset.name[comparison]\n dataset.name.order <- levels(df$source.target)\n dataset.name.order <- stringr::str_match(dataset.name.order, \"\\\\(.*\\\\)\")\n dataset.name.order <- stringr::str_sub(dataset.name.order, 2, stringr::str_length(dataset.name.order)-1)\n xtick.color <- color[dataset.name.order]\n g <- g + theme(axis.text.x = element_text(colour = xtick.color))\n }\n }\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (return.data) {\n return(list(communication = df, gg.obj = g))\n } else {\n return(g)\n }\n\n}\n\n\n\n\n#' Chord diagram for visualizing cell-cell communication for a signaling pathway\n#'\n#' Names of cell states will be displayed in this chord diagram\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the name of signaling networks\n#' @param net a weighted matrix or a data frame with three columns defining the cell-cell communication network\n#' @param slot.name the slot name of object: slot.name = \"net\" when visualizing cell-cell communication network per each ligand-receptor pair associated with a given signaling pathway;\n#' slot.name = \"netP\" when visualizing cell-cell communication network at the level of signaling pathways\n#' @param color.use colors for the cell groups\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param remove.isolate whether remove sectors without any links\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the figures\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param ... other parameters passing to chordDiagram\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_cell <- function(object, signaling = NULL, net = NULL, slot.name = \"netP\",\n color.use = NULL,group = NULL,cell.order = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n remove.isolate = FALSE, link.visible = TRUE, scale = FALSE, directional = 1,link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20, nCol = NULL,\n thresh = 0.05,...){\n\n if (!is.null(signaling)) {\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n }\n\n if (slot.name == \"netP\") {\n message(\"Plot the aggregated cell-cell communication network at the signaling pathway level\")\n net <- apply(prob, c(1,2), sum)\n if (is.null(title.name)) {\n title.name <- paste0(signaling, \" signaling pathway network\")\n }\n # par(mfrow = c(1,1), xpd=TRUE)\n # par(mar = c(5, 4, 4, 2))\n gg <- netVisual_chord_cell_internal(net, color.use = color.use, group = group, cell.order = cell.order, sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap, big.gap = big.gap,annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y, ...)\n } else if (slot.name == \"net\") {\n message(\"Plot the cell-cell communication network per each ligand-receptor pair associated with a given signaling pathway\")\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n # layout(matrix(1:length(pairLR.name.use), ncol = nCol))\n # par(xpd=TRUE)\n # par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE, mar = c(5, 4, 4, 2) +0.1)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n #par(mar = c(5, 4, 4, 2))\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n gg[[i]] <- netVisual_chord_cell_internal(net, color.use = color.use, group = group,cell.order = cell.order,sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap,big.gap = big.gap, annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y, ...)\n }\n }\n\n } else if (!is.null(net)) {\n gg <- netVisual_chord_cell_internal(net, color.use = color.use, group = group,cell.order = cell.order,sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap, big.gap = big.gap,annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y, ...)\n } else {\n stop(\"Please assign values to either `signaling` or `net`\")\n }\n\n return(gg)\n}\n\n\n#' Chord diagram for visualizing cell-cell communication from a weighted adjacency matrix or a data frame\n#'\n#' Names of cell states/groups will be displayed in this chord diagram\n#'\n#' @param net a weighted matrix or a data frame with three columns defining the cell-cell communication network\n#' @param color.use colors for the cell groups\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param remove.isolate whether remove sectors without any links\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name of the plot\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param ... other parameters passing to chordDiagram\n#' @importFrom circlize circos.clear chordDiagram circos.track circos.text get.cell.meta.data\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_cell_internal <- function(net, color.use = NULL, group = NULL, cell.order = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n remove.isolate = FALSE, link.visible = TRUE, scale = FALSE, directional = 1, link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20,...){\n if (inherits(x = net, what = c(\"matrix\", \"Matrix\"))) {\n cell.levels <- union(rownames(net), colnames(net))\n net <- reshape2::melt(net, value.name = \"prob\")\n colnames(net)[1:2] <- c(\"source\",\"target\")\n } else if (is.data.frame(net)) {\n if (all(c(\"source\",\"target\", \"prob\") %in% colnames(net)) == FALSE) {\n stop(\"The input data frame must contain three columns named as source, target, prob\")\n }\n cell.levels <- as.character(union(net$source,net$target))\n }\n if (!is.null(cell.order)) {\n cell.levels <- cell.order\n }\n net$source <- as.character(net$source)\n net$target <- as.character(net$target)\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cell.levels[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cell.levels[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n }\n # remove the interactions with zero values\n net <- subset(net, prob > 0)\n if(dim(net)[1]<=0){message(\"No interaction between those cells\")}\n # create a fake data if keeping the cell types (i.e., sectors) without any interactions\n if (!remove.isolate) {\n cells.removed <- setdiff(cell.levels, as.character(union(net$source,net$target)))\n if (length(cells.removed) > 0) {\n net.fake <- data.frame(cells.removed, cells.removed, 1e-10*sample(length(cells.removed), length(cells.removed)))\n colnames(net.fake) <- colnames(net)\n net <- rbind(net, net.fake)\n link.visible <- net[, 1:2]\n link.visible$plot <- FALSE\n if(nrow(net) > nrow(net.fake)){\n link.visible$plot[1:(nrow(net) - nrow(net.fake))] <- TRUE\n }\n # directional <- net[, 1:2]\n # directional$plot <- 0\n # directional$plot[1:(nrow(net) - nrow(net.fake))] <- 1\n # link.arr.type = \"big.arrow\"\n # message(\"Set scale = TRUE when remove.isolate = FALSE\")\n scale = TRUE\n }\n }\n\n df <- net\n cells.use <- union(df$source,df$target)\n\n # define grid order\n order.sector <- cell.levels[cell.levels %in% cells.use]\n\n # define grid color\n if (is.null(color.use)){\n color.use = scPalette(length(cell.levels))\n names(color.use) <- cell.levels\n } else if (is.null(names(color.use))) {\n names(color.use) <- cell.levels\n }\n grid.col <- color.use[order.sector]\n names(grid.col) <- order.sector\n\n # set grouping information\n if (!is.null(group)) {\n group <- group[names(group) %in% order.sector]\n }\n\n # define edge color\n edge.color <- color.use[as.character(df$source)]\n\n if (directional == 0 | directional == 2) {\n link.arr.type = \"triangle\"\n } else {\n link.arr.type = \"big.arrow\"\n }\n\n circos.clear()\n chordDiagram(df,\n order = order.sector,\n col = edge.color,\n grid.col = grid.col,\n transparency = transparency,\n link.border = link.border,\n directional = directional,\n direction.type = c(\"diffHeight\",\"arrows\"),\n link.arr.type = link.arr.type, # link.border = \"white\",\n annotationTrack = \"grid\",\n annotationTrackHeight = annotationTrackHeight,\n preAllocateTracks = list(track.height = max(strwidth(order.sector))),\n small.gap = small.gap,\n big.gap = big.gap,\n link.visible = link.visible,\n scale = scale,\n group = group,\n link.target.prop = link.target.prop,\n reduce = reduce,\n ...)\n circos.track(track.index = 1, panel.fun = function(x, y) {\n xlim = get.cell.meta.data(\"xlim\")\n xplot = get.cell.meta.data(\"xplot\")\n ylim = get.cell.meta.data(\"ylim\")\n sector.name = get.cell.meta.data(\"sector.index\")\n circos.text(mean(xlim), ylim[1], sector.name, facing = \"clockwise\", niceFacing = TRUE, adj = c(0, 0.5),cex = lab.cex)\n }, bg.border = NA)\n\n # https://jokergoo.github.io/circlize_book/book/legends.html\n if (show.legend) {\n lgd <- ComplexHeatmap::Legend(at = names(grid.col), type = \"grid\", legend_gp = grid::gpar(fill = grid.col), title = \"Cell State\")\n ComplexHeatmap::draw(lgd, x = unit(1, \"npc\")-unit(legend.pos.x, \"mm\"), y = unit(legend.pos.y, \"mm\"), just = c(\"right\", \"bottom\"))\n }\n\n if(!is.null(title.name)){\n # title(title.name, cex = 1)\n text(-0, 1.02, title.name, cex=1)\n }\n circos.clear()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Chord diagram for visualizing cell-cell communication for a set of ligands/receptors or signaling pathways\n#'\n#' Names of ligands/receptors or signaling pathways will be displayed in this chord diagram\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object: slot.name = \"net\" when visualizing links at the level of ligands/receptors; slot.name = \"netP\" when visualizing links at the level of signaling pathways\n#' @param signaling a character vector giving the name of signaling networks\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param net A data frame consisting of the interactions of interest.\n#' net should have at least three columns: \"source\",\"target\" and \"interaction_name\" when visualizing links at the level of ligands/receptors;\n#' \"source\",\"target\" and \"pathway_name\" when visualizing links at the level of signaling pathway; \"interaction_name\" and \"pathway_name\" must be the matched names in CellChatDB$interaction.\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param color.use colors for the cell groups\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name of the plot\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param ... other parameters to chordDiagram\n#' @importFrom circlize circos.clear chordDiagram circos.track circos.text get.cell.meta.data\n#' @importFrom dplyr select %>% group_by summarize\n#' @importFrom grDevices recordPlot\n#' @importFrom stringr str_split\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_gene <- function(object, slot.name = \"net\", color.use = NULL,\n signaling = NULL, pairLR.use = NULL, net = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n link.visible = TRUE, scale = FALSE, directional = 1, link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, legend.pos.x = 20, legend.pos.y = 20, show.legend = TRUE,\n thresh = 0.05,\n ...){\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use) | sum(c(\"interaction_name\",\"pathway_name\") %in% colnames(pairLR.use) == 0)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n message(\"slot.name is set to be 'netP' when pairLR.use contains signaling pathways\")\n slot.name = \"netP\"\n }\n }\n\n if (!is.null(pairLR.use) & !is.null(signaling)) {\n stop(\"Please do not assign values to 'signaling' when using 'pairLR.use'\")\n }\n\n if (is.null(net)) {\n prob <- slot(object, \"net\")$prob\n pval <- slot(object, \"net\")$pval\n prob[pval > thresh] <- 0\n net <- reshape2::melt(prob, value.name = \"prob\")\n colnames(net)[1:3] <- c(\"source\",\"target\",\"interaction_name\")\n cols.default <- c(\"interaction_name_2\", \"pathway_name\", \"ligand\", \"receptor\" ,\"annotation\",\"evidence\")\n cols.common <- intersect(cols.default,colnames(object@LR$LRsig))\n pairLR = dplyr::select(object@LR$LRsig, cols.common)\n idx <- match(net$interaction_name, rownames(pairLR))\n temp <- pairLR[idx,]\n net <- cbind(net, temp)\n }\n\n if (!is.null(signaling)) {\n pairLR.use <- data.frame()\n for (i in 1:length(signaling)) {\n pairLR.use.i <- searchPair(signaling = signaling[i], pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.use <- rbind(pairLR.use, pairLR.use.i)\n }\n }\n\n if (!is.null(pairLR.use)){\n if (\"interaction_name\" %in% colnames(pairLR.use)) {\n net <- subset(net,interaction_name %in% pairLR.use$interaction_name)\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n net <- subset(net, pathway_name %in% as.character(pairLR.use$pathway_name))\n }\n }\n\n if (slot.name == \"netP\") {\n net <- dplyr::select(net, c(\"source\",\"target\",\"pathway_name\",\"prob\"))\n net$source_target <- paste(net$source, net$target, sep = \"sourceTotarget\")\n net <- net %>% dplyr::group_by(source_target, pathway_name) %>% dplyr::summarize(prob = sum(prob))\n a <- stringr::str_split(net$source_target, \"sourceTotarget\", simplify = T)\n net$source <- as.character(a[, 1])\n net$target <- as.character(a[, 2])\n net$ligand <- net$pathway_name\n net$receptor <- \" \"\n }\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- levels(object@idents)[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n } else {\n sources.use <- levels(object@idents)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- levels(object@idents)[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n } else {\n targets.use <- levels(object@idents)\n }\n # remove the interactions with zero values\n df <- subset(net, prob > 0)\n\n if (nrow(df) == 0) {\n stop(\"No signaling links are inferred! \")\n }\n\n if (length(unique(net$ligand)) == 1) {\n message(\"You may try the function `netVisual_chord_cell` for visualizing individual signaling pathway\")\n }\n\n df$id <- 1:nrow(df)\n # deal with duplicated sector names\n ligand.uni <- unique(df$ligand)\n for (i in 1:length(ligand.uni)) {\n df.i <- df[df$ligand == ligand.uni[i], ]\n source.uni <- unique(df.i$source)\n for (j in 1:length(source.uni)) {\n df.i.j <- df.i[df.i$source == source.uni[j], ]\n df.i.j$ligand <- paste0(df.i.j$ligand, paste(rep(' ',j-1),collapse = ''))\n df$ligand[df$id %in% df.i.j$id] <- df.i.j$ligand\n }\n }\n receptor.uni <- unique(df$receptor)\n for (i in 1:length(receptor.uni)) {\n df.i <- df[df$receptor == receptor.uni[i], ]\n target.uni <- unique(df.i$target)\n for (j in 1:length(target.uni)) {\n df.i.j <- df.i[df.i$target == target.uni[j], ]\n df.i.j$receptor <- paste0(df.i.j$receptor, paste(rep(' ',j-1),collapse = ''))\n df$receptor[df$id %in% df.i.j$id] <- df.i.j$receptor\n }\n }\n\n cell.order.sources <- levels(object@idents)[levels(object@idents) %in% sources.use]\n cell.order.targets <- levels(object@idents)[levels(object@idents) %in% targets.use]\n\n df$source <- factor(df$source, levels = cell.order.sources)\n df$target <- factor(df$target, levels = cell.order.targets)\n # df.ordered.source <- df[with(df, order(source, target, -prob)), ]\n # df.ordered.target <- df[with(df, order(target, source, -prob)), ]\n df.ordered.source <- df[with(df, order(source, -prob)), ]\n df.ordered.target <- df[with(df, order(target, -prob)), ]\n\n order.source <- unique(df.ordered.source[ ,c('ligand','source')])\n order.target <- unique(df.ordered.target[ ,c('receptor','target')])\n\n # define sector order\n order.sector <- c(order.source$ligand, order.target$receptor)\n\n # define cell type color\n if (is.null(color.use)){\n color.use = scPalette(nlevels(object@idents))\n names(color.use) <- levels(object@idents)\n color.use <- color.use[levels(object@idents) %in% as.character(union(df$source,df$target))]\n } else if (is.null(names(color.use))) {\n names(color.use) <- levels(object@idents)\n color.use <- color.use[levels(object@idents) %in% as.character(union(df$source,df$target))]\n }\n\n # define edge color\n edge.color <- color.use[as.character(df.ordered.source$source)]\n names(edge.color) <- as.character(df.ordered.source$source)\n\n # define grid colors\n grid.col.ligand <- color.use[as.character(order.source$source)]\n names(grid.col.ligand) <- as.character(order.source$source)\n grid.col.receptor <- color.use[as.character(order.target$target)]\n names(grid.col.receptor) <- as.character(order.target$target)\n grid.col <- c(as.character(grid.col.ligand), as.character(grid.col.receptor))\n names(grid.col) <- order.sector\n\n df.plot <- df.ordered.source[ ,c('ligand','receptor','prob')]\n\n if (directional == 2) {\n link.arr.type = \"triangle\"\n } else {\n link.arr.type = \"big.arrow\"\n }\n circos.clear()\n chordDiagram(df.plot,\n order = order.sector,\n col = edge.color,\n grid.col = grid.col,\n transparency = transparency,\n link.border = link.border,\n directional = directional,\n direction.type = c(\"diffHeight\",\"arrows\"),\n link.arr.type = link.arr.type,\n annotationTrack = \"grid\",\n annotationTrackHeight = annotationTrackHeight,\n preAllocateTracks = list(track.height = max(strwidth(order.sector))),\n small.gap = small.gap,\n big.gap = big.gap,\n link.visible = link.visible,\n scale = scale,\n link.target.prop = link.target.prop,\n reduce = reduce,\n ...)\n\n circos.track(track.index = 1, panel.fun = function(x, y) {\n xlim = get.cell.meta.data(\"xlim\")\n xplot = get.cell.meta.data(\"xplot\")\n ylim = get.cell.meta.data(\"ylim\")\n sector.name = get.cell.meta.data(\"sector.index\")\n circos.text(mean(xlim), ylim[1], sector.name, facing = \"clockwise\", niceFacing = TRUE, adj = c(0, 0.5),cex = lab.cex)\n }, bg.border = NA)\n\n # https://jokergoo.github.io/circlize_book/book/legends.html\n if (show.legend) {\n lgd <- ComplexHeatmap::Legend(at = names(color.use), type = \"grid\", legend_gp = grid::gpar(fill = color.use), title = \"Cell State\")\n ComplexHeatmap::draw(lgd, x = unit(1, \"npc\")-unit(legend.pos.x, \"mm\"), y = unit(legend.pos.y, \"mm\"), just = c(\"right\", \"bottom\"))\n }\n\n circos.clear()\n if(!is.null(title.name)){\n text(-0, 1.02, title.name, cex=1)\n }\n gg <- recordPlot()\n return(gg)\n}\n\n\n\n\n#' River plot showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways\n#'\n#' River (alluvial) plot shows the correspondence between the inferred latent patterns and cell groups as well as ligand-receptor pairs or signaling pathways.\n#'\n#' The thickness of the flow indicates the contribution of the cell group or signaling pathway to each latent pattern. The height of each pattern is proportional to the number of its associated cell groups or signaling pathways.\n#'\n#' Outgoing patterns reveal how the sender cells coordinate with each other as well as how they coordinate with certain signaling pathways to drive communication.\n#'\n#' Incoming patterns show how the target cells coordinate with each other as well as how they coordinate with certain signaling pathways to respond to incoming signaling.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object: “netP” or “net”. Use “netP” to analyze cell-cell communication at the level of signaling pathways, and “net” to analyze cell-cell communication at the level of ligand-receptor pairs.\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param cutoff the threshold for filtering out weak links\n#' @param sources.use a vector giving the index or the name of source cell groups of interest\n#' @param targets.use a vector giving the index or the name of target cell groups of interest\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.use.pattern the character vector defining the color of each pattern\n#' @param color.use.signaling the character vector defining the color of each signaling\n#' @param do.order whether reorder the cell groups or signaling according to their similarity\n#' @param main.title the title of plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom methods slot\n#' @importFrom stats cutree dist hclust\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @import ggalluvial\n# #' @importFrom ggalluvial geom_stratum geom_flow to_lodes_form\n#' @importFrom ggplot2 geom_text scale_x_discrete scale_fill_manual theme ggtitle\n#' @importFrom cowplot plot_grid ggdraw draw_label\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_river <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = 0.5,\n sources.use = NULL, targets.use = NULL, signaling = NULL,\n color.use = NULL, color.use.pattern = NULL, color.use.signaling = \"grey50\",\n do.order = FALSE, main.title = NULL,\n font.size = 2.5, font.size.title = 12){\n message(\"Please make sure you have load `library(ggalluvial)` when running this function\")\n requireNamespace(\"ggalluvial\")\n # suppressMessages(require(ggalluvial))\n res.pattern <- methods::slot(object, slot.name)$pattern[[pattern]]\n data1 = res.pattern$pattern$cell\n data2 = res.pattern$pattern$signaling\n if (is.null(color.use.pattern)) {\n nPatterns <- length(unique(data1$Pattern))\n if (pattern == \"outgoing\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(1,nPatterns*2, by = 2)]\n } else if (pattern == \"incoming\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(2,nPatterns*2, by = 2)]\n }\n }\n if (is.null(main.title)) {\n if (pattern == \"outgoing\") {\n main.title = \"Outgoing communication patterns of secreting cells\"\n } else if (pattern == \"incoming\") {\n main.title = \"Incoming communication patterns of target cells\"\n }\n }\n\n if (is.null(data2)) {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n if (is.null(color.use)) {\n color.use <- scPalette(nCellGroup)\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n gg <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10))+\n ggtitle(main.title)\n\n } else {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n cells.level = levels(object@idents)\n if (is.null(color.use)) {\n color.use <- scPalette(length(cells.level))[cells.level %in% unique(plot.data$CellGroup)]\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n if (!is.null(sources.use)) {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% sources.use)\n }\n if (!is.null(targets.use)) {\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% targets.use)\n }\n ## connect cell groups with patterns\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n StatStratum <- ggalluvial::StatStratum\n gg1 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10)) +\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n ## connect patterns with signaling\n data2$Contribution[data2$Contribution < cutoff] <- 0\n plot.data <- data2\n nPatterns<-length(unique(plot.data$Pattern))\n nSignaling<-length(unique(plot.data$Signaling))\n if (length(color.use.signaling) == 1) {\n color.use.all <- c(color.use.pattern, rep(color.use.signaling, nSignaling))\n } else {\n color.use.all <- c(color.use.pattern, color.use.signaling)\n }\n\n if (!is.null(signaling)) {\n plot.data <- plot.data[plot.data$Signaling %in% signaling, ]\n }\n\n plot.data.long <- ggalluvial::to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"Signaling\"]], plot.data[[\"Pattern\"]]), sum)\n mat[is.na(mat)] <- 0; mat <- mat[-which(rowSums(mat) == 0), ]\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(colnames(mat),names(cluster)[order.name]))\n }\n\n gg2 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"Pattern\", \"Signaling\")),y= Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"forward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) + # 2.5\n scale_x_discrete(limits = c(), labels=c(\"Patterns\", \"Signaling\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size= 10))+\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n ## connect cell groups with signaling\n # data1 = data1[data1$Contribution > 0,]\n # data2 = data2[data2$Contribution > 0,]\n\n # data3 = merge(data1, data2, by.x=\"Pattern\", by.y=\"Pattern\")\n # data3$Contribution <- data3$Contribution.x * data3$Contribution.y\n # data3 <- data3[,colnames(data3) %in% c(\"CellGroup\",\"Signaling\",\"Contribution\")]\n\n # plot.data <- data3\n # nSignaling<-length(unique(plot.data$Signaling))\n # nCellGroup<-length(unique(plot.data$CellGroup))\n #\n # if (length(color.use.signaling) == 1) {\n # color.use.signaling <- rep(color.use.signaling, nSignaling)\n # }\n #\n #\n # ## connect cell groups with patterns\n # plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n # if (do.order) {\n # mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Signaling\"]]), sum)\n # d <- dist(as.matrix(mat))\n # hc <- hclust(d, \"ave\")\n # k <- length(unique(grep(\"Signaling\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n # cluster <- hc %>% cutree(k)\n # order.name <- order(cluster)\n # plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n # color.use <- color.use[order.name]\n # }\n # color.use.all <- c(color.use, color.use.signaling)\n\n # gg3 <- ggplot(plot.data.long, aes(x = factor(x, levels = c(\"CellGroup\", \"Signaling\")),y=Contribution,\n # stratum = stratum, alluvium = connection,\n # fill = stratum, label = stratum)) +\n # geom_flow(width = 1/3,aes.flow = \"forward\") +\n # geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n # geom_text(stat = \"stratum\", size = 2.5) +\n # scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Signaling\")) +\n # scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n # theme_bw()+\n # theme(legend.position = \"none\",\n # axis.title = element_blank(),\n # axis.text.y= element_blank(),\n # panel.grid.major = element_blank(),\n # panel.grid.minor = element_blank(),\n # panel.border = element_blank(),\n # axis.ticks = element_blank(),axis.text=element_text(size=10)) +\n # theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n\n gg <- cowplot::plot_grid(gg1, gg2,align = \"h\", nrow = 1)\n title <- cowplot::ggdraw() + cowplot::draw_label(main.title,size = font.size.title)\n gg <- cowplot::plot_grid(title, gg, ncol=1, rel_heights=c(0.1, 1))\n }\n return(gg)\n}\n\n#' Dot plots showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways\n#'\n#' Using a contribution score of each cell group to each signaling pathway computed by multiplying W by H obtained from `identifyCommunicationPatterns`, we constructed a dot plot in which the dot size is proportion to the contribution score to show association between cell group and their enriched signaling pathways.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param cutoff the threshold for filtering out weak links. Default is 1/R where R is the number of latent patterns. We set the elements in W and H to be zero if they are less than `cutoff`.\n#' @param color.use the character vector defining the color of each cell group\n#' @param pathway.show the character vector defining the signaling to show\n#' @param group.show the character vector defining the cell group to show\n#' @param shape the shape of the symbol: 21 for circle and 22 for square\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param main.title the title of plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom methods slot\n#' @import ggplot2\n#' @importFrom dplyr group_by top_n\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_dot <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = NULL, color.use = NULL,\n pathway.show = NULL, group.show = NULL,\n shape = 21, dot.size = c(1, 3), dot.alpha = 1, main.title = NULL,\n font.size = 10, font.size.title = 12){\n pattern <- match.arg(pattern)\n patternSignaling <- methods::slot(object, slot.name)$pattern[[pattern]]\n data1 = patternSignaling$pattern$cell\n data2 = patternSignaling$pattern$signaling\n data = patternSignaling$data\n if (is.null(main.title)) {\n if (pattern == \"outgoing\") {\n main.title = \"Outgoing communication patterns of secreting cells\"\n } else if (pattern == \"incoming\") {\n main.title = \"Incoming communication patterns of target cells\"\n }\n }\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(data1$CellGroup))\n }\n if (is.null(cutoff)) {\n cutoff <- 1/length(unique(data1$Pattern))\n }\n options(warn = -1)\n data1$Contribution[data1$Contribution < cutoff] <- 0\n data2$Contribution[data2$Contribution < cutoff] <- 0\n data3 = merge(data1, data2, by.x=\"Pattern\", by.y=\"Pattern\")\n data3$Contribution <- data3$Contribution.x * data3$Contribution.y\n data3 <- data3[,colnames(data3) %in% c(\"CellGroup\",\"Signaling\",\"Contribution\")]\n if (!is.null(pathway.show)) {\n data3 <- data3[data3$Signaling %in% pathway.show, ]\n pathway.add <- pathway.show[which(pathway.show %in% data3$Signaling == 0)]\n if (length(pathway.add) > 1) {\n data.add <- expand.grid(CellGroup = levels(data1$CellGroup), Signaling = pathway.add)\n data.add$Contribution <- 0\n data3 <- rbind(data3, data.add)\n }\n data3$Signaling <- factor(data3$Signaling, levels = pathway.show)\n }\n if (!is.null(group.show)) {\n data3$CellGroup <- as.character(data3$CellGroup)\n data3 <- data3[data3$CellGroup %in% group.show, ]\n data3$CellGroup <- factor(data3$CellGroup, levels = group.show)\n }\n\n data <- as.data.frame(as.table(data));\n data <- data[data[,3] != 0, ]\n data12 <- paste0(data[,1],data[,2])\n data312 <- paste0(data3[,1],data3[,2])\n idx1 <- which(match(data312, data12, nomatch = 0) ==0)\n data3$Contribution[idx1] <- 0\n data3$id <- data312\n data3 <- data3 %>% group_by(id) %>% top_n(1, Contribution)\n\n data3$Contribution[which(data3$Contribution == 0)] <- NA\n\n df <- data3\n gg <- ggplot(data = df, aes(x = Signaling, y = CellGroup)) +\n geom_point(aes(size = Contribution, fill = CellGroup, colour = CellGroup), shape = shape) +\n scale_size_continuous(range = dot.size) +\n theme_linedraw() +\n scale_x_discrete(position = \"bottom\") +\n ggtitle(main.title) +\n theme(plot.title = element_text(hjust = 0.5)) +\n theme(text = element_text(size = font.size),plot.title = element_text(size=font.size.title, face=\"plain\"),\n axis.text.x = element_text(angle = 45, hjust=1),\n axis.text.y = element_text(angle = 0, hjust=1),\n axis.title.x = element_blank(),\n axis.title.y = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25)) +\n theme(panel.grid.major = element_line(colour=\"grey90\", size = (0.1)))\n gg <- gg + scale_y_discrete(limits = rev(levels(data3$CellGroup)))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE, na.value = \"white\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, na.value = \"white\")\n gg <- gg + guides(colour=\"none\") + guides(fill=\"none\")\n gg <- gg + theme(legend.title = element_text(size = 10), legend.text = element_text(size = 8))\n gg\n return(gg)\n}\n\n\n#' 2D visualization of the learned manifold of signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param pathway.labeled a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param pathway.remove.show whether show the removed signaling names\n#' @param color.use defining the color for each cell group\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embedding <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), color.use = NULL, pathway.labeled = NULL, top.label = 1, pathway.remove = NULL, pathway.remove.show = TRUE, dot.size = c(2, 6), label.size = 2, dot.alpha = 0.5,\n xlabel = \"Dim 1\", ylabel = \"Dim 2\", title = NULL,\n font.size = 10, font.size.title = 12, do.label = T, show.legend = T, show.axes = T) {\n type <- match.arg(type)\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n Groups <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n prob <- methods::slot(object, slot.name)$prob\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n }\n\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(dimnames(prob)[[3]] %in% pathway.remove)\n prob <- prob[ , , -pathway.remove.idx]\n }\n\n prob_sum <- apply(prob, 3, sum)\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum), labels = as.character(unlist(dimnames(prob)[3])), Groups = as.factor(Groups))\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(Groups)))\n }\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.,fill = Groups, colour = Groups), shape = 21) +\n CellChat_theme_opts() +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\"))+\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE)\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n if (do.label) {\n if (is.null(pathway.labeled)) {\n if (top.label < 1) {\n if (length(comparison) == 2) {\n g.t <- rankSimilarity(object, slot.name = slot.name, type = type, comparison1 = comparison)\n pathway.labeled <- as.character(g.t$data$name[(nrow(g.t$data)-ceiling(top.label * nrow(g.t$data))+1):nrow(g.t$data) ])\n data.label <- df[df$labels %in% pathway.labeled, , drop = FALSE]\n }\n } else {\n data.label <- df\n }\n\n } else {\n data.label <- df[df$labels %in% pathway.labeled, , drop = FALSE]\n }\n gg <- gg + ggrepel::geom_text_repel(data = data.label, mapping = aes(label = labels, colour = Groups), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n\n # gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = Groups), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (length(pathway.remove) > 0 & pathway.remove.show) {\n gg <- gg + annotate(geom = 'text', label = paste(\"Isolate pathways: \", paste(pathway.remove, collapse = ', ')), x = -Inf, y = Inf, hjust = 0, vjust = 1, size = label.size,fontface=\"italic\")\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n gg\n}\n\n\n#' Zoom into the 2D visualization of the learned manifold learning of the signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param color.use defining the color for each cell group\n#' @param nCol the number of columns of the plot\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom cowplot plot_grid\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingZoomIn <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), color.use = NULL, pathway.remove = NULL, nCol = 1, dot.size = c(2, 6), label.size = 2.8, dot.alpha = 0.5,\n xlabel = NULL, ylabel = NULL, do.label = T, show.legend = F, show.axes = T) {\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n prob <- methods::slot(object, slot.name)$prob\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n }\n\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(dimnames(prob)[[3]] %in% pathway.remove)\n prob <- prob[ , , -pathway.remove.idx]\n }\n\n prob_sum <- apply(prob, 3, sum)\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum), labels = as.character(unlist(dimnames(prob)[3])), clusters = as.factor(clusters))\n\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n\n # zoom into each cluster and do labels\n ggAll <- vector(\"list\", length(unique(clusters)))\n for (i in 1:length(unique(clusters))) {\n clusterID = i\n title <- paste0(\"Group \", clusterID)\n df2 <- df[df$clusters %in% clusterID,]\n gg <- ggplot(data = df2, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.), shape = 21, colour = alpha(color.use[clusterID], alpha = 1), fill = alpha(color.use[clusterID], alpha = dot.alpha)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size=12))+\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels), colour = color.use[clusterID], size = label.size, segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n ggAll[[i]] <- gg\n }\n gg.combined <- cowplot::plot_grid(plotlist = ggAll, ncol = nCol)\n\n gg.combined\n\n}\n\n\n\n#' 2D visualization of the joint manifold learning of signaling networks from two datasets\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object\n#' @param pathway.labeled a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param pathway.remove.show whether show the removed signaling names\n#' @param color.use defining the color for each cell group\n#' @param point.shape a numeric vector giving the point shapes. By default point.shape <- c(21, 0, 24, 23, 25, 10, 12), see available shapes at http://www.sthda.com/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingPairwise <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, color.use = NULL, point.shape = NULL, pathway.labeled = NULL, top.label = 1, pathway.remove = NULL, pathway.remove.show = TRUE, dot.size = c(2, 6), label.size = 2.5, dot.alpha = 0.5,\n xlabel = \"Dim 1\", ylabel = \"Dim 2\", title = NULL,do.label = T, show.legend = T, show.axes = T) {\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"2D visualization of signaling networks from datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n object.names <- setdiff(names(methods::slot(object, slot.name)), \"similarity\")[comparison]\n prob <- list()\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n prob[[i]] = object.net$prob\n }\n\n if (is.null(point.shape)) {\n point.shape <- c(21, 0, 24, 23, 25, 10, 12)\n }\n\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove <- sub(\"--.*\", \"\", pathway.remove)\n }\n\n if (length(pathway.remove) > 0) {\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n pathway.remove.idx <- which(paste0(dimnames(probi)[[3]],\"--\",object.names[i]) %in% pathway.remove)\n # pathway.remove.idx <- which(dimnames(probi)[[3]] %in% pathway.remove)\n if (length(pathway.remove.idx) > 0) {\n probi <- probi[ , , -pathway.remove.idx]\n }\n prob[[i]] <- probi\n }\n }\n prob_sum.each <- list()\n signalingAll <- c()\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n prob_sum.each[[i]] <- apply(probi, 3, sum)\n signalingAll <- c(signalingAll, paste0(names(prob_sum.each[[i]]),\"--\",object.names[i]))\n }\n prob_sum <- unlist(prob_sum.each)\n names(prob_sum) <- signalingAll\n\n group <- sub(\".*--\", \"\", names(prob_sum))\n labels = sub(\"--.*\", \"\", names(prob_sum))\n\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum),\n labels = as.character(labels), clusters = as.factor(clusters), group = factor(group, levels = unique(group)))\n # color dots (light inside color and dark border) based on clustering and no labels\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.,fill = clusters, colour = clusters, shape = group)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) +\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) #+ scale_alpha(group, range = c(0.1, 1))\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n gg <- gg + scale_shape_manual(values = point.shape[1:length(prob)])\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = clusters, alpha=group), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n }\n\n if (length(pathway.remove) > 0 & pathway.remove.show) {\n gg <- gg + annotate(geom = 'text', label = paste(\"Isolate pathways: \", paste(pathway.remove, collapse = ', ')), x = -Inf, y = Inf, hjust = 0, vjust = 1, size = label.size,fontface=\"italic\")\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n gg\n}\n\n\n\n#' Zoom into the 2D visualization of the joint manifold learning of signaling networks from two datasets\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param color.use defining the color for each cell group\n#' @param nCol number of columns in the plot\n#' @param point.shape a numeric vector giving the point shapes. By default point.shape <- c(21, 0, 24, 23, 25, 10, 12), see available shapes at http://www.sthda.com/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingPairwiseZoomIn <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, color.use = NULL, nCol = 1, point.shape = NULL, pathway.remove = NULL, dot.size = c(2, 6), label.size = 2.8, dot.alpha = 0.5,\n xlabel = NULL, ylabel = NULL, do.label = T, show.legend = F, show.axes = T) {\n\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"2D visualization of signaling networks from datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n object.names <- setdiff(names(methods::slot(object, slot.name)), \"similarity\")[comparison]\n prob <- list()\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n prob[[i]] = object.net$prob\n }\n\n if (is.null(point.shape)) {\n point.shape <- c(21, 0, 24, 23, 25, 10, 12)\n }\n\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove <- sub(\"--.*\", \"\", pathway.remove)\n }\n\n if (length(pathway.remove) > 0) {\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n pathway.remove.idx <- which(paste0(dimnames(probi)[[3]],\"--\",object.names[i]) %in% pathway.remove)\n # pathway.remove.idx <- which(dimnames(probi)[[3]] %in% pathway.remove)\n if (length(pathway.remove.idx) > 0) {\n probi <- probi[ , , -pathway.remove.idx]\n }\n prob[[i]] <- probi\n }\n }\n\n prob_sum.each <- list()\n signalingAll <- c()\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n prob_sum.each[[i]] <- apply(probi, 3, sum)\n signalingAll <- c(signalingAll, paste0(names(prob_sum.each[[i]]),\"--\",object.names[i]))\n }\n prob_sum <- unlist(prob_sum.each)\n names(prob_sum) <- signalingAll\n\n group <- sub(\".*--\", \"\", names(prob_sum))\n labels = sub(\"--.*\", \"\", names(prob_sum))\n\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum),\n labels = as.character(labels), clusters = as.factor(clusters), group = factor(group, levels = unique(group)))\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n\n # zoom into each cluster and do labels\n ggAll <- vector(\"list\", length(unique(clusters)))\n for (i in 1:length(unique(clusters))) {\n clusterID = i\n title <- paste0(\"Cluster \", clusterID)\n df2 <- df[df$clusters %in% clusterID,]\n gg <- ggplot(data = df2, aes(x, y)) +\n geom_point(aes(size = Commun.Prob., shape = group),fill = alpha(color.use[clusterID], alpha = dot.alpha), colour = alpha(color.use[clusterID], alpha = 1)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) +\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n idx <- match(unique(df2$group), levels(df$group), nomatch = 0)\n gg <- gg + scale_shape_manual(values= point.shape[idx])\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels), colour = color.use[clusterID], size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n ggAll[[i]] <- gg\n }\n gg.combined <- cowplot::plot_grid(plotlist = ggAll, ncol = nCol)\n\n gg.combined\n\n}\n\n\n#' A Seurat wrapper function for plotting gene expression using violin plot, dot plot or bar plot\n#'\n#' This function create a Seurat object from an input CellChat object, and then plot gene expression distribution using a modified violin plot or dot plot based on Seurat's function or a bar plot.\n#' Please check \\code{\\link{StackedVlnPlot}},\\code{\\link{dotPlot}} and \\code{\\link{barPlot}}for detailed description of the arguments.\n#'\n#' USER can extract the signaling genes related to the inferred L-R pairs or signaling pathway using \\code{\\link{extractEnrichedLR}}, and then plot gene expression using Seurat package.\n#'\n#' @param object CellChat object\n#' @param features Features to plot gene expression\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param type violin plot or dot plot\n#' @param color.use defining the color for each cell group\n#' @param group.by Name of one metadata columns to group (color) cells. Default is the defined cell groups in CellChat object\n#' @param ... other arguments passing to either VlnPlot or DotPlot from Seurat package\n#' @return\n#' @export\n#'\n#' @examples\n\nplotGeneExpression <- function(object, features = NULL, signaling = NULL, enriched.only = TRUE, type = c(\"violin\", \"dot\",\"bar\"), color.use = NULL, group.by = NULL, ...) {\n type <- match.arg(type)\n meta <- object@meta\n if (is.list(object@idents)) {\n meta$group.cellchat <- object@idents$joint\n } else {\n meta$group.cellchat <- object@idents\n }\n if (!identical(rownames(meta), colnames(object@data.signaling))) {\n cat(\"The cell barcodes in 'meta' is \", head(rownames(meta)),'\\n')\n warning(\"The cell barcodes in 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of 'mata'!\")\n rownames(meta) <- colnames(object@data.signaling)\n }\n\n w10x <- Seurat::CreateSeuratObject(counts = object@data.signaling, meta.data = meta)\n if (is.null(group.by)) {\n group.by <- \"group.cellchat\"\n }\n Seurat::Idents(w10x) <- group.by\n if (!is.null(features) & !is.null(signaling)) {\n warning(\"`features` will be used when inputing both `features` and `signaling`!\")\n }\n if (!is.null(features)) {\n feature.use <- features\n } else if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, enriched.only = enriched.only)\n feature.use <- res$geneLR\n }\n if (type == \"violin\") {\n gg <- StackedVlnPlot(w10x, features = feature.use, color.use = color.use, ...)\n } else if (type == \"dot\") {\n gg <- dotPlot(w10x, features = feature.use, color.use = color.use, ...)\n } else if (type == \"bar\") {\n gg <- barPlot(w10x, features = feature.use, color.use = color.use, ...)\n }\n return(gg)\n}\n\n\n#' Dot plot\n#'\n#'The size of the dot encodes the percentage of cells within a class, while the color encodes the AverageExpression level across all cells within a class\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param rotation whether rotate the plot\n#' @param colormap RColorbrewer palette to use (check available palette using RColorBrewer::display.brewer.all()). default will use customed color palette\n#' @param color.direction Sets the order of colours in the scale. If 1, the default, colours are as output by RColorBrewer::brewer.pal(). If -1, the order of colours is reversed.\n#' @param color.use defining the color for each condition/dataset\n#' @param idents Which classes to include in the plot (default is all)\n#' @param group.by Name of one or more metadata columns to group (color) cells by\n#' (for example, orig.ident); pass 'ident' to group by identity class\n#' @param split.by Name of a metadata column to split plot by;\n#' @param legend.width legend width\n#' @param scale whther show x-axis text\n#' @param col.min Minimum scaled average expression threshold (everything smaller will be set to this)\n#' @param col.max Maximum scaled average expression threshold (everything larger will be set to this)\n#' @param dot.scale Scale the size of the points, similar to cex\n#' @param assay Name of assay to use, defaults to the active assay\n#' @param angle.x angle for x-axis text rotation\n#' @param hjust.x adjust x axis text\n#' @param angle.y angle for y-axis text rotation\n#' @param hjust.y adjust y axis text\n#' @param show.legend whether show the legend\n#' @param ... Extra parameters passed to DotPlot from Seurat package\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\ndotPlot <- function(object, features, rotation = TRUE, colormap = \"OrRd\", color.direction = 1, color.use = c(\"#F8766D\",\"#00BFC4\"), scale = TRUE, col.min = -2.5, col.max = 2.5, dot.scale = 6, assay = \"RNA\",\n idents = NULL, group.by = NULL, split.by = NULL, legend.width = 0.5,\n angle.x = 45, hjust.x = 1, angle.y = 0, hjust.y = 0.5, show.legend = TRUE, ...) {\n\n gg <- Seurat::DotPlot(object, features = features, assay = assay, cols = color.use,\n scale = scale, col.min = col.min, col.max = col.max, dot.scale = dot.scale,\n idents = idents, group.by = group.by, split.by = split.by,...)\n gg <- gg + theme(axis.title.x=element_blank(), axis.title.y=element_blank()) +\n theme(axis.text.x = element_text(size = 10), axis.text.y = element_text(size = 10), axis.line = element_line(colour = 'black')) +\n theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))+\n theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x), axis.text.y = element_text(angle = angle.y, hjust = hjust.y))\n\n gg <- gg + theme(legend.title = element_text(size = 10), legend.text = element_text(size = 8))\n if (is.null(split.by)) {\n gg <- gg + guides(color = guide_colorbar(barwidth = legend.width, title = \"Scaled expression\"),size = guide_legend(title = 'Percent expressed'))\n }\n\n if (rotation) {\n gg <- gg + coord_flip()\n }\n if (!is.null(colormap)) {\n if (is.null(split.by)) {\n gg <- gg + scale_color_distiller(palette = colormap, direction = color.direction, guide = guide_colorbar(title = \"Scaled Expression\", ticks = T, label = T, barwidth = legend.width), na.value = \"lightgrey\")\n }\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n return(gg)\n}\n\n\n\n#' Stacked Violin plot\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param color.use defining the color for each cell group\n#' @param colors.ggplot whether use ggplot color scheme; default: colors.ggplot = FALSE\n#' @param split.by Name of a metadata column to split plot by;\n#' @param idents Which classes to include in the plot (default is all)\n#' @param show.text.y whther show y-axis text\n#' @param line.size line width in the violin plot\n#' @param pt.size size of the dots\n#' @param plot.margin adjust the white space between each plot\n#' @param angle.x angle for x-axis text rotation\n#' @param vjust.x adjust x axis text\n#' @param hjust.x adjust x axis text\n#' @param ... Extra parameters passed to VlnPlot from Seurat package\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\n#' @importFrom patchwork wrap_plots\n# #' @importFrom Seurat VlnPlot\nStackedVlnPlot<- function(object, features, idents = NULL, split.by = NULL,\n color.use = NULL, colors.ggplot = FALSE,\n angle.x = 90, vjust.x = NULL, hjust.x = NULL, show.text.y = TRUE, line.size = NULL,\n pt.size = 0,\n plot.margin = margin(0, 0, 0, 0, \"cm\"),\n ...) {\n options(warn=-1)\n if (is.null(color.use)) {\n numCluster <- length(levels(Seurat::Idents(object)))\n if (colors.ggplot) {\n color.use <- NULL\n } else {\n color.use <- scPalette(numCluster)\n }\n }\n if (is.null(vjust.x) | is.null(hjust.x)) {\n angle=c(0, 45, 90)\n hjust=c(0, 1, 1)\n vjust=c(0, 1, 0.5)\n vjust.x = vjust[angle == angle.x]\n hjust.x = hjust[angle == angle.x]\n }\n\n plot_list<- purrr::map(features, function(x) modify_vlnplot(object = object, features = x, idents = idents, split.by = split.by, cols = color.use, pt.size = pt.size,\n show.text.y = show.text.y, line.size = line.size, ...))\n\n # Add back x-axis title to bottom plot. patchwork is going to support this?\n plot_list[[length(plot_list)]]<- plot_list[[length(plot_list)]] +\n theme(axis.text.x=element_text(), axis.ticks.x = element_line()) +\n theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x, vjust = vjust.x)) +\n theme(axis.text.x = element_text(size = 10))\n\n p<- patchwork::wrap_plots(plotlist = plot_list, ncol = 1)\n return(p)\n}\n\n#' modified vlnplot\n#' @param object Seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param split.by Name of a metadata column to split plot by;\n#' @param idents Which classes to include in the plot (default is all)\n#' @param cols defining the color for each cell group\n#' @param show.text.y whther show y-axis text\n#' @param line.size line width in the violin plot\n#' @param pt.size size of the dots\n#' @param plot.margin adjust the white space between each plot\n#' @param ... pass any arguments to VlnPlot in Seurat\n#' @import ggplot2\n# #' @importFrom Seurat VlnPlot\n#'\nmodify_vlnplot<- function(object,\n features,\n idents = NULL,\n split.by = NULL,\n cols = NULL,\n show.text.y = TRUE,\n line.size = NULL,\n pt.size = 0,\n plot.margin = margin(0, 0, 0, 0, \"cm\"),\n ...) {\n options(warn=-1)\n p<- Seurat::VlnPlot(object, features = features, cols = cols, pt.size = pt.size, idents = idents, split.by = split.by, ... ) +\n xlab(\"\") + ylab(features) + ggtitle(\"\")\n p <- p + theme(text = element_text(size = 10)) + theme(axis.line = element_line(size=line.size)) +\n theme(axis.text.x = element_text(size = 10), axis.text.y = element_text(size = 8), axis.line.x = element_line(colour = 'black', size=line.size),axis.line.y = element_line(colour = 'black', size= line.size))\n # theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))\n p <- p + theme(legend.position = \"none\",\n plot.title= element_blank(),\n axis.title.x = element_blank(),\n axis.text.x = element_blank(),\n axis.ticks.x = element_blank(),\n axis.title.y = element_text(size = rel(1), angle = 0),\n axis.text.y = element_text(size = rel(1)),\n plot.margin = plot.margin ) +\n theme(axis.text.y = element_text(size = 8))\n\n p <- p + scale_y_continuous(labels = function(x) {\n idx0 = which(x == 0)\n if (length(idx0) > 0) {\n if (idx0 > 1) {\n c(rep(x = \"\", times = idx0-1), \"0\",rep(x = \"\", times = length(x) -2-idx0), x[length(x) - 1], \"\")\n } else {\n c(\"0\", rep(x = \"\", times = length(x)-3), x[length(x) - 1], \"\")\n }\n } else {\n c(as.character(min(x)), rep(x = \"\", times = length(x)-3), x[length(x) - 1], \"\")\n }\n })\n # #c(rep(x = \"\", times = length(x)-2), x[length(x) - 1], \"\"))\n\n p <- p + theme(element_line(size=line.size))\n\n if (!show.text.y) {\n p <- p + theme(axis.ticks.y=element_blank(), axis.text.y=element_blank())\n }\n return(p)\n}\n\n#' extract the max value of the y axis\n#' @param p ggplot object\n#' @importFrom ggplot2 ggplot_build\nextract_max<- function(p){\n ymax<- max(ggplot_build(p)$layout$panel_scales_y[[1]]$range$range)\n return(signif(ymax,2))\n}\n\n\n#' Bar plot for average gene expression\n#'\n#' Please check \\code{\\link{barplot_internal}}for detailed description of the arguments.\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param color.use defining the color for each condition/dataset\n#' @param group.by Name of one or more metadata columns to group (color) cells by\n#' (for example, orig.ident); pass 'ident' to group by identity class\n#' @param method methods for computing the average gene expression per cell group. By default = \"truncatedMean\", where a value should be assigned to 'trim;\n#' @param trim the fraction (0 to 0.5) of observations to be trimmed from each end of x before the mean is computed.\n#' @param split.by Name of a metadata column to split plot by;\n#' @param assay Name of assay to use, defaults to the active assay\n#' @param x.lab.rot whether do rotation for the x.tick.label\n#' @param ncol number of columns to show in the plot\n#' @param ... Extra parameters passed to barplot_internal\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\nbarPlot <- function(object, features, group.by = NULL, split.by = NULL, color.use = NULL, method = c(\"truncatedMean\", \"triMean\",\"median\"),trim = 0.1, assay = \"RNA\",\n x.lab.rot = FALSE, ncol = 1, ...) {\n method <- match.arg(method)\n if (is.null(group.by)) {\n labels = Seurat::Idents(object)\n } else {\n labels = object@meta.data[,group.by]\n }\n FunMean <- switch(method,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n triMean = triMean,\n median = function(x) median(x, na.rm = TRUE))\n if (packageVersion(\"Seurat\") < \"5.0.0\") {\n data.all <- object[[assay]]@data\n } else {\n data.all <- object[[assay]]$data\n }\n if (!is.null(split.by)) {\n group = object@meta.data[,split.by]\n group.levels <- levels(group)\n df <- data.frame()\n for (i in 1:length(group.levels)) {\n data = data.all[, group == group.levels[i], drop = FALSE]\n labels.use <- labels[group == group.levels[i]]\n dataavg <- aggregate(t(data[features, ]), list(labels.use) , FUN = FunMean)\n dataavg <- t(dataavg[,-1])\n colnames(dataavg) <- levels(labels.use)\n dataavg <- as.data.frame(dataavg)\n dataavg$gene = rownames(dataavg)\n df1 = reshape2::melt(dataavg, id.vars = c(\"gene\"))\n colnames(df1) <- c(\"gene\",\"labels\",\"value\")\n df1$condition = group.levels[i]\n df = rbind(df, df1)\n }\n df$labels <- factor(df$labels, levels = levels(labels))\n df$condition <- factor(df$condition, levels = group.levels)\n\n } else {\n data = data.all\n dataavg <- aggregate(t(data[features, ]), list(labels) , FUN = FunMean)\n dataavg <- t(dataavg[,-1])\n colnames(dataavg) <- levels(labels)\n dataavg$gene = rownames(dataavg)\n df1 = reshape2::melt(dataavg, id.vars = c(\"gene\"))\n colnames(df1) <- c(\"gene\",\"labels\",\"value\")\n df1$condition = df1[,\"labels\"]\n df = df1\n }\n gg <- list()\n for (i in 1:length(features)) {\n if (i < length(features)) {\n df.use = subset(df, gene == features[i])\n gg[[i]] <- barplot_internal(df.use, x = \"labels\", y = \"value\", fill = \"condition\",color.use = color.use,ylabel = features[i],remove.xtick = TRUE,x.lab.rot = x.lab.rot,...)\n }else {\n gg[[i]] <- barplot_internal(df.use, x = \"labels\", y = \"value\", fill = \"condition\",color.use = color.use,ylabel = features[i],remove.xtick = FALSE,x.lab.rot = x.lab.rot,...)\n }\n }\n\n p<- patchwork::wrap_plots(plotlist = gg, ncol = ncol)+ patchwork::plot_layout(guides = \"collect\")\n return(p)\n\n}\n\n#' Bar plot for dataframe\n#'\n#' @param df a dataframe\n#' @param x Name of one column to show on the x-axis\n#' @param y Name of one column to show on the y-axis\n#' @param fill Name of one column to compare the values\n#' @param color.use defining the color of bar plot;\n#' @param percent.y whether showing y-values as percentage\n#' @param width bar width\n#' @param legend.title Name of legend\n#' @param xlabel Name of x label\n#' @param ylabel Name of y label\n#' @param remove.xtick whether remove x tick\n#' @param title.name Name of the main title\n#' @param stat.add whether adding statistical test\n#' @param stat.method,label.x parameters for ggpubr::stat_compare_means\n#' @param show.legend Whether show the legend\n#' @param x.lab.rot Whether rorate the xtick labels\n#' @param size.text font size\n\n#' @import ggplot2\n#' @importFrom ggpubr stat_compare_means\n#'\n#' @return ggplot2 object\n#' @export\nbarplot_internal <- function(df, x = \"cellType\", y = \"value\", fill = \"condition\", legend.title = NULL, width=0.6, title.name = NULL,\n xlabel = NULL, ylabel = NULL, color.use = NULL,remove.xtick = FALSE,\n stat.add = FALSE, stat.method = \"wilcox.test\", percent.y = FALSE, label.x = 1.5,\n show.legend = TRUE, x.lab.rot = FALSE, size.text = 10) {\n\n gg <- ggplot(df, aes_string(x=x, y=y, fill = fill, color = fill)) + geom_bar(stat=\"identity\", width=width, position=position_dodge()) +\n theme_classic() + scale_x_discrete(limits = (levels(df$x))) + theme(axis.text.x = element_text(angle = 45, hjust = 1,size=10))\n\n gg <- gg + ylab(ylabel) + xlab(xlabel) + theme_classic() +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = size.text), axis.text = element_text(colour=\"black\"))\n if (!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values = alpha(color.use, alpha = 1), drop = FALSE)\n gg <- gg + scale_color_manual(values = alpha(color.use, alpha = 1), drop = FALSE) + guides(colour = FALSE)\n }\n if (stat.add) {\n gg <- gg + ggpubr::stat_compare_means(mapping = aes_string(group = fill), method = stat.method, label.x = label.x,\n label = \"p.format\", size = 3)\n }\n # if (show.mean) {\n # gg <- gg + stat_summary(fun.y=mean, geom=\"point\", shape=20, size=10, color=\"red\", fill=\"red\")\n # }\n if (remove.xtick) {\n gg <- gg + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.title.x=element_blank())\n }\n if (percent.y) {\n gg <- gg + scale_y_continuous(labels = scales::percent_format(accuracy = 1))\n }\n if (is.null(legend.title)) {\n gg <- gg + theme(legend.title = element_blank())\n } else {\n gg <- gg + guides(fill=guide_legend(legend.title))\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n if (x.lab.rot) {\n gg <- gg + theme(axis.text.x = element_text(angle = 45, hjust = 1, size=size.text))\n }\n gg\n return(gg)\n}\n\n\n########################################\n# spatial plot #\n########################################\n#' Visualize spatial cell groups\n#'\n#' This function takes a CellChat object as input, and then plot cell groups of interest.\n#'\n#' @param object cellchat object\n#' @param color.use defining the color for each cell group\n#' @param group.by Name of one metadata columns to group (color) cells. Default is the defined cell groups in CellChat object\n#' @param sample.use the sample name used for visualization, which should be the element in `object@meta$samples`.\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups\n#' @param idents.use a vector giving the index or the name of cell groups of interest\n#' @param alpha the transparency of individual spot\n#' @param shape.by the shape of individual spot\n#' @param title.name title name\n#' @param point.size the size of spots\n#' @param legend.size the size of legend\n#' @param legend.text.size the text size on the legend\n#' @param legend.position legend position\n#' @param ncol number of columns of the legend text\n#' @param byrow arrange the legend text byrow or not\n#' @return\n#' @export\n#'\n#' @examples\nspatialDimPlot <- function(object, color.use = NULL, group.by = NULL, sample.use = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL,\n alpha = 1, shape.by = 16, title.name = NULL, point.size = 2.4,\n legend.size = 5, legend.text.size = 8, legend.position = \"right\", ncol = 1, byrow = FALSE){\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[,group.by]\n labels <- factor(labels)\n }\n cells.level <- levels(labels)\n\n coordinates <- object@images$coordinates\n samples <- object@meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n\n if (is.null(sources.use) & is.null(targets.use)){\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n } else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use, \"Others\"))\n\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use, targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n\n gg <- ggplot(data = coordinates,aes(x=x_cent,y=y_cent,colour = labels))+\n geom_point(alpha = alpha, size = point.size, shape=shape.by) +\n scale_color_manual(values = color.use, na.value = \"grey90\") + theme(legend.position = legend.position) +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size)) + # , legend.key.size = unit(0.4, \"inches\")\n guides(color = guide_legend(override.aes = list(size=legend.size), ncol = ncol, byrow = byrow)) +\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n coord_fixed() + theme(aspect.ratio = 1)+ theme(legend.key = element_blank())\n gg <- gg + scale_y_reverse()\n\n if (!is.null(title.name)){\n gg <- gg + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))\n }\n return(gg)\n\n}\n\n\n#' A spatial feature plots\n#'\n#' This function takes a CellChat object as input, and then plot gene expression distribution over spots/cells on the image.\n#'\n#' @param object cellchat object\n#' @param features a char vector containing features to visualize. `features` can be genes or column names of `object@meta`.\n#' @param signaling signalling names to visualize\n#' @param pairLR.use a data frame consisting of one column named \"interaction_name\", defining the L-R pairs of interest\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param do.group set `do.group = TRUE` when only showing enriched signaling based on cell group-level communication; set `do.group = FALSE` when only showing enriched signaling based on individual cell-level communication\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param color.heatmap A character string or vector indicating the colormap option to use. It can be the avaibale color palette in brewer.pal() or viridis_pal() (e.g., \"Spectral\",\"viridis\")\n#' @param n.colors,direction n.colors: number of basic colors to generate from color palette; direction: Sets the order of colors in the scale. If 1, the default colors are used. If -1, the order of colors is reversed.\n#' @param do.binary,cutoff whether binarizing the expression using a given cutoff\n#' @param color.use defining the color for cells/spots expressing ligand only, expressing receptor only, expressing both ligand & receptor and cells/spots without expression of given ligands and receptors\n#' @param alpha the transparency of individual spot\n#' @param point.size the size of cell slot\n#' @param shape.by the shape of individual spot\n#' @param legend.size the size of legend\n#' @param legend.text.size the text size on the legend\n#' @param ncol number of columns if plotting multiple plots\n#' @param show.legend whether show each figure legend\n#' @param show.legend.combined whether show the figure legend for the last plot\n#' @return\n#' @export\n#'\n#' @examples\n\nspatialFeaturePlot <- function(object, features = NULL, signaling = NULL, pairLR.use = NULL, sample.use = NULL, enriched.only = TRUE,thresh = 0.05, do.group = TRUE,\n color.heatmap = \"Spectral\", n.colors = 8, direction = -1,\n do.binary = FALSE, cutoff = NULL, color.use = NULL, alpha = 1,\n point.size = 0.8, legend.size = 3, legend.text.size = 8, shape.by = 16, ncol = NULL,\n show.legend = TRUE, show.legend.combined = FALSE){\n data <- object@data\n meta <- object@meta\n coords <- object@images$coordinates\n samples <- meta$samples\n if (ncol(coords) == 2) {\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coords = coords\n coords[,1] = temp_coords[,2]\n coords[,2] = temp_coords[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n scales::viridis_pal(option = color.heatmap, direction = -1)(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n } else {\n colormap <- color.heatmap\n }\n\n if (is.null(features) & is.null(signaling) & is.null(pairLR.use)){\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)){\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)){\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)){\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n\n df <- data.frame(x = coords[, 1], y = coords[, 2])\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, enriched.only = enriched.only, thresh = thresh)\n feature.use <- res$geneLR\n } else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n } else {\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(paste0('There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.'))\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\",\"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex, object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex, object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n } else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) > 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n } else if (length(intersect(feature.use, colnames(meta))) > 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[ ,feature.use, drop = FALSE])\n } else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \",cutoff,\"to the values...\", '\\n')\n data.use[data.use <= cutoff] <- 0\n }\n\n\n if (is.null(ncol)) {\n if (length(feature.use) > 9) {\n ncol <- 4\n } else {\n ncol <- min(length(feature.use), 4)\n }\n }\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i, ]\n g <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = feature.data), alpha = alpha, size=point.size, shape=shape.by) +\n scale_colour_gradientn(colours = colormap, guide = guide_colorbar(title = NULL, ticks = T, label = T, barwidth = 0.5), na.value = \"grey90\") +\n theme(legend.position = \"right\") +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size), legend.key.size = unit(0.15, \"inches\")) + # , legend.key.size = unit(0.4, \"inches\")\n ggtitle(feature.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))+\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n theme(legend.key = element_blank())\n g <- g + coord_fixed() + theme(aspect.ratio = 1) + scale_y_reverse()\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (show.legend.combined & i == numFeature) {\n g <- g + theme(legend.position = \"right\", legend.key.height = grid::unit(0.15, \"in\"), legend.key.width = grid::unit(0.5, \"in\"), legend.title = element_blank(),legend.key = element_blank())\n }\n gg[[i]] <- g\n }\n if (ncol > 1) {\n gg <- patchwork::wrap_plots(gg, ncol = ncol)\n } else {\n gg <- gg[[1]]\n }\n\n } else {\n\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, enriched.only = enriched.only, thresh = thresh)\n # gene.pair = searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n # LR.pair <- gene.pair[res$interaction_name, c(\"ligand\",\"receptor\")]\n LR.pair <- object@LR$LRsig[res$interaction_name, c(\"ligand\",\"receptor\")]\n } else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n } else {\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(paste0('There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.'))\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\",\"receptor\")]\n } else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n # compute the expression of ligand or receptor\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL; rownames(dataR) <- geneR;\n # data.use <- matrix(0, nrow = nrow(dataL)*2, ncol = ncol(dataL))\n # data.use[seq_len(nrow(data.use)) %% 2 == 1, ] <- dataL\n # data.use[seq_len(nrow(data.use)) %% 2 == 0, ] <- dataR\n # rownames(data.use)[seq_len(nrow(data.use)) %% 2 == 1] <- geneL\n # rownames(data.use)[seq_len(nrow(data.use)) %% 2 == 0] <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n if (is.null(ncol)) {\n if (length(feature.use) > 9) {\n ncol <- 4\n } else {\n ncol <- min(length(feature.use), 4)\n }\n }\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \" )\n }\n gg <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i, ] > cutoff\n idx2 = dataR[i, ] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\",ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i],geneR[i],\"Both\",\"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i],geneR[i],\"Both\",\"None\")\n\n if (length(setdiff(levels(group), unique(group))) > 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group), unique(group)))\n }\n\n df$feature.data <- group\n g <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = feature.data), alpha = alpha, size=point.size, shape=shape.by) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size), legend.key.size = unit(0.15, \"inches\")) + # , legend.key.size = unit(0.4, \"inches\")\n guides(color = guide_legend(override.aes = list(size=legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))+\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n theme(legend.key = element_blank())\n g <- g + coord_fixed() + theme(aspect.ratio = 1) + scale_y_reverse()\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (show.legend.combined & i == numFeature) {\n g <- g + theme(legend.position = \"right\", legend.key.height = grid::unit(0.15, \"in\"), legend.key.width = grid::unit(0.5, \"in\"), legend.title = element_blank(),legend.key = element_blank())\n }\n gg[[i]] <- g\n }\n if (ncol > 1) {\n gg <- patchwork::wrap_plots(gg, ncol = ncol)\n } else {\n gg <- gg[[1]]\n }\n\n }\n return(gg)\n}\n"], ["/CellChat/R/analysis.R", "\n#' Compute and visualize the contribution of each ligand-receptor pair in the overall signaling pathways\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param width the width of individual bar\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param return.data whether return the data.frame consisting of the predicted L-R pairs and their contribution\n#' @param x.rotation rotation of x-label\n#' @param title the title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom dplyr select\n#' @importFrom ggplot2 ggplot geom_bar aes coord_flip scale_x_discrete element_text theme ggtitle\n#' @importFrom cowplot ggdraw draw_label plot_grid\n#'\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_contribution <- function(object, signaling, signaling.name = NULL, sources.use = NULL, targets.use = NULL,\n width = 0.1, vertex.receiver = NULL, thresh = 0.05, return.data = FALSE,\n x.rotation = 0, title = \"Contribution of each L-R pair\",\n font.size = 10, font.size.title = 10) {\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pair.name.use = select(object@DB$interaction[rownames(pairLR),],\"interaction_name_2\")\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n\n prob <- prob[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n dimnames(prob)[3] <- pairLR.name.use\n }\n prob <-(prob-min(prob))/(max(prob)-min(prob))\n\n if (is.null(vertex.receiver)) {\n pSum <- apply(prob, 3, sum)\n pSum.max <- sum(prob)\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n y.lim <- max(pSum)\n\n pair.name <- unlist(dimnames(prob)[3])\n pair.name <- factor(pair.name, levels = unique(pair.name))\n if (!is.null(pairLR.name.use)) {\n pair.name <- pair.name.use[as.character(pair.name),1]\n pair.name <- factor(pair.name, levels = unique(pair.name))\n }\n mat <- pSum\n df1 <- data.frame(name = pair.name, contribution = mat)\n if(nrow(df1) < 10) {\n df2 <- data.frame(name = as.character(1:(10-nrow(df1))), contribution = rep(0, 10-nrow(df1)))\n df <- rbind(df1, df2)\n } else {\n df <- df1\n }\n df <- df[order(df$contribution, decreasing = TRUE), ]\n # df$name <- factor(df$name, levels = unique(df$name))\n df$name <- factor(df$name,levels=df$name[order(df$contribution, decreasing = TRUE)])\n df1$name <- factor(df1$name,levels=df1$name[order(df1$contribution, decreasing = TRUE)])\n gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\", width = 0.7) +\n theme_classic() + theme(axis.text.y = element_text(angle = x.rotation, hjust = 1,size=font.size, colour = 'black'), axis.text=element_text(size=font.size),\n axis.title.y = element_text(size= font.size), axis.text.x = element_blank(), axis.ticks = element_blank()) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim) + coord_flip() + theme(legend.position=\"none\") +\n scale_x_discrete(limits = rev(levels(df$name)), labels = c(rep(\"\", max(0, 10-nlevels(df1$name))),rev(levels(df1$name))))\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5, size = font.size.title))\n }\n gg\n\n } else {\n pair.name <- factor(unlist(dimnames(prob)[3]), levels = unique(unlist(dimnames(prob)[3])))\n # show all the communications\n pSum <- apply(prob, 3, sum)\n pSum.max <- sum(prob)\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n y.lim <- max(pSum)\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\",width = 0.2) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8),\n axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"All\")+ theme(plot.title = element_text(hjust = 0.5))#+\n\n # show the communications in Hierarchy1\n if (dim(prob)[3] > 1) {\n pSum <- apply(prob[,vertex.receiver,], 3, sum)\n } else {\n pSum <- sum(prob[,vertex.receiver,])\n }\n\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg1 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\",width = 0.2) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"Hierarchy1\") + theme(plot.title = element_text(hjust = 0.5))#+\n #scale_x_discrete(limits = c(0,1))\n\n # show the communications in Hierarchy2\n\n if (dim(prob)[3] > 1) {\n pSum <- apply(prob[,setdiff(1:dim(prob)[1],vertex.receiver),], 3, sum)\n } else {\n pSum <- sum(prob[,setdiff(1:dim(prob)[1],vertex.receiver),])\n }\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg2 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\", width=0.9) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"Hierarchy2\")+ theme(plot.title = element_text(hjust = 0.5))#+\n #scale_x_discrete(limits = c(0,1))\n title <- cowplot::ggdraw() + cowplot::draw_label(paste0(\"Contribution of each signaling in \", signaling.name, \" pathway\"), fontface='bold', size = 10)\n gg.combined <- cowplot::plot_grid(gg, gg1, gg2, nrow = 1)\n gg.combined <- cowplot::plot_grid(title, gg.combined, ncol = 1, rel_heights=c(0.1, 1))\n gg <- gg.combined\n gg\n }\n if (return.data) {\n df <- subset(df, contribution > 0)\n return(list(LR.contribution = df, gg.obj = gg))\n } else {\n return(gg)\n }\n}\n\n\n#' Compute the network centrality scores allowing identification of dominant senders, receivers, mediators and influencers in all inferred communication networks\n#'\n#' NB: This function was previously named as `netAnalysis_signalingRole`. The previous function `netVisual_signalingRole` is now named as `netAnalysis_signalingRole_network`.\n#'\n#' @param object CellChat object; If object = NULL, USER must provide `net`\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks. Setting slot.name = \"netP\" to compute the network centrality scores at the level of signaling pathways, and setting slot.name = \"net\" to compute the network centrality scores at the level of ligand-receptor pairs\n#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net\n#' @param net.name a character vector giving the name of signaling networks\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom future nbrOfWorkers\n#' @importFrom methods slot\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#'\n#' @return\n#' @export\n#'\nnetAnalysis_computeCentrality <- function(object = NULL, slot.name = \"netP\", net = NULL, net.name = NULL, thresh = 0.05) {\n if (is.null(net)) {\n prob <- methods::slot(object, slot.name)$prob\n pval <- methods::slot(object, slot.name)$pval\n pval[prob == 0] <- 1\n prob[pval >= thresh] <- 0\n net = prob\n }\n if (is.null(net.name)) {\n net.name <- dimnames(net)[[3]]\n }\n if (length(dim(net)) == 3) {\n nrun <- dim(net)[3]\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n centr.all = my.sapply(\n X = 1:nrun,\n FUN = function(x) {\n net0 <- net[ , , x]\n return(computeCentralityLocal(net0))\n },\n simplify = FALSE\n )\n } else {\n centr.all <- as.list(computeCentralityLocal(net))\n }\n names(centr.all) <- net.name\n if (is.null(object)) {\n return(centr.all)\n } else {\n slot(object, slot.name)$centr <- centr.all\n return(object)\n }\n}\n\n\n\n#' Compute Centrality measures for a signaling network\n#'\n#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net\n#' @importFrom igraph graph_from_adjacency_matrix strength hub_score authority_score eigen_centrality page_rank betweenness E\n#' @importFrom sna flowbet infocent\n#'\n#' @return\ncomputeCentralityLocal <- function(net) {\n centr <- vector(\"list\")\n G <- igraph::graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n centr$outdeg_unweighted <- rowSums(net > 0)\n centr$indeg_unweighted <- colSums(net > 0)\n centr$outdeg <- igraph::strength(G, mode=\"out\")\n centr$indeg <- igraph::strength(G, mode=\"in\")\n centr$hub <- igraph::hub_score(G)$vector\n centr$authority <- igraph::authority_score(G)$vector # A node has high authority when it is linked by many other nodes that are linking many other nodes.\n centr$eigen <- igraph::eigen_centrality(G)$vector # A measure of influence in the network that takes into account second-order connections\n centr$page_rank <- igraph::page_rank(G)$vector\n igraph::E(G)$weight <- 1/igraph::E(G)$weight\n centr$betweenness <- igraph::betweenness(G)\n #centr$flowbet <- try(sna::flowbet(net)) # a measure of its role as a gatekeeper for the flow of communication between any two cells; the total maximum flow (aggregated across all pairs of third parties) mediated by v.\n #centr$info <- try(sna::infocent(net)) # actors with higher information centrality are predicted to have greater control over the flow of information within a network; highly information-central individuals tend to have a large number of short paths to many others within the social structure.\n centr$flowbet <- tryCatch({\n sna::flowbet(net)\n }, error = function(e) {\n as.vector(matrix(0, nrow = nrow(net), ncol = 1))\n })\n centr$info <- tryCatch({\n sna::infocent(net, diag = T, rescale = T, cmode = \"lower\")\n # sna::infocent(net, diag = T, rescale = T, cmode = \"weak\")\n }, error = function(e) {\n as.vector(matrix(0, nrow = nrow(net), ncol = 1))\n })\n return(centr)\n}\n\n\n#' Select the number of the patterns for running `identifyCommunicationPatterns`\n#'\n#' We infer the number of patterns based on two metrics that have been implemented in the NMF R package, including Cophenetic and Silhouette. Both metrics measure the stability for a particular number of patterns based on a hierarchical clustering of the consensus matrix. For a range of the number of patterns, a suitable number of patterns is the one at which Cophenetic and Silhouette values begin to drop suddenly.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param k.range a range of the number of patterns\n#' @param title.name title of plot\n#' @param do.facet whether use facet plot showing the two measures\n#' @param nrun number of runs when performing NMF\n#' @param seed.use seed when performing NMF\n#' @importFrom methods slot\n# #' @importFrom NMF nmfEstimateRank\n#' @import NMF\n# #' @importFrom ggplot2 scale_color_brewer\n#' @import ggplot2\n#' @return a ggplot object\n#' @export\n#'\n#' @examples\nselectK <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), title.name = NULL, do.facet = TRUE, k.range = seq(2,10), nrun = 30, seed.use = 10) {\n pattern <- match.arg(pattern)\n prob <- methods::slot(object, slot.name)$prob\n if (pattern == \"outgoing\") {\n data_sender <- apply(prob, c(1,3), sum)\n data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_sender)\n } else if (pattern == \"incoming\") {\n data_receiver <- apply(prob, c(2,3), sum)\n data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_receiver)\n }\n options(warn = -1)\n data <- data0\n data <- data[rowSums(data)!=0,]\n\n if (is.null(title.name)) {\n title.name <- paste0(pattern, \" signaling \\n\")\n # title.name <- paste0(pattern, \" signaling \\n (nrun = \", nrun, \", seed = \", seed.use, \")\")\n }\n\n res <- NMF::nmfEstimateRank(data, range = k.range, method = 'lee', nrun=nrun, seed = seed.use)\n df1 <- data.frame(k = res$measures$rank, score = res$measures$cophenetic, Measure = \"Cophenetic\")\n df2 <- data.frame(k = res$measures$rank, score = res$measures$silhouette.consensus, Measure = \"Silhouette\")\n # df3 <- data.frame(k = res$measures$rank, score = res$measures$dispersion, Measure = \"Dispersion\")\n df <- rbind(df1, df2)\n #df <- rbind(df1, df2, df3)\n gg <- ggplot(df, aes(x = k, y = score, group = Measure, color = Measure)) + geom_line(size=1) +\n geom_point() +\n theme_classic() + labs(x = 'Number of patterns', y='Measure score') +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(legend.position = \"right\") + theme(text = element_text(size = 10)) + scale_x_discrete(limits = (unique(df$k))) +\n scale_color_brewer(palette=\"Set2\") + guides(color=guide_legend(\"Measure type\"))\n if (do.facet) {\n gg <- gg + facet_wrap(~ Measure, scales='free')\n }\n gg\n return(gg)\n}\n\n\n\n#' Identification of major signals for specific cell groups and general communication patterns\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param k the number of patterns\n#' @param k.range a range of the number of patterns\n#' @param heatmap.show whether showing heatmap\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param title.legend the title of legend in heatmap\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @importFrom methods slot\n#' @importFrom NMF nmfEstimateRank nmf\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation draw\n#' @importFrom stats setNames\n#' @importFrom grid grid.grabExpr grid.newpage pushViewport grid.draw unit gpar viewport popViewport\n#'\n#' @return\n#' @export\n#'\n#' @examples\n\nidentifyCommunicationPatterns <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), k = NULL, k.range = seq(2,10), heatmap.show = TRUE,\n color.use = NULL, color.heatmap = \"Spectral\", title.legend = \"Contributions\",\n width = 4, height = 6, font.size = 8) {\n pattern <- match.arg(pattern)\n prob <- methods::slot(object, slot.name)$prob\n if (pattern == \"outgoing\") {\n data_sender <- apply(prob, c(1,3), sum)\n data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_sender)\n } else if (pattern == \"incoming\") {\n data_receiver <- apply(prob, c(2,3), sum)\n data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_receiver)\n }\n options(warn = -1)\n data <- data0\n data <- data[rowSums(data)!=0,]\n if (is.null(k)) {\n stop(\"Please run the function `selectK` for selecting a suitable k!\")\n }\n\n outs_NMF <- NMF::nmf(data, rank = k, method = 'lee', seed = 'nndsvd')\n W <- scaleMat(outs_NMF@fit@W, 'r1')\n H <- scaleMat(outs_NMF@fit@H, 'c1')\n colnames(W) <- paste0(\"Pattern \", seq(1,ncol(W))); rownames(H) <- paste0(\"Pattern \", seq(1,nrow(H)));\n if (heatmap.show) {\n net <- W\n if (is.null(color.use)) {\n color.use <- scPalette(length(rownames(net)))\n }\n color.heatmap = grDevices::colorRampPalette(rev(RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(255)\n\n df<- data.frame(group = rownames(net)); rownames(df) <- rownames(net)\n cell.cols.assigned <- setNames(color.use, unique(as.character(df$group)))\n row_annotation <- HeatmapAnnotation(df = df, col = list(group = cell.cols.assigned),which = \"row\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ht1 = Heatmap(net, col = color.heatmap, na_col = \"white\", name = \"Contribution\",\n left_annotation = row_annotation,\n cluster_rows = T,cluster_columns = F,clustering_method_rows = \"average\",\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n show_heatmap_legend = F,\n column_title = \"Cell patterns\",column_title_gp = gpar(fontsize = 10)\n )\n\n\n net <- t(H)\n\n ht2 = Heatmap(net, col = color.heatmap, na_col = \"white\", name = \"Contribution\",\n cluster_rows = T,cluster_columns = F,clustering_method_rows = \"average\",\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = \"Communication patterns\",column_title_gp = gpar(fontsize = 10),\n heatmap_legend_param = list(title = title.legend, title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = c(round(min(net, na.rm = T), digits = 1), round(max(net, na.rm = T), digits = 1)),\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 6),grid_width = unit(2, \"mm\"))\n )\n\n gb_ht1 = grid.grabExpr(draw(ht1))\n gb_ht2 = grid.grabExpr(draw(ht2))\n #grid.newpage()\n pushViewport(viewport(x = 0.1, y = 0.1, width = 0.2, height = 0.5, just = c(\"left\", \"bottom\")))\n grid.draw(gb_ht1)\n popViewport()\n\n pushViewport(viewport(x = 0.6, y = 0.1, width = 0.2, height = 0.5, just = c(\"left\", \"bottom\")))\n grid.draw(gb_ht2)\n popViewport()\n\n }\n\n data_W <- as.data.frame(as.table(W)); colnames(data_W) <- c(\"CellGroup\",\"Pattern\",\"Contribution\")\n data_H <- as.data.frame(as.table(H)); colnames(data_H) <- c(\"Pattern\",\"Signaling\",\"Contribution\")\n\n res.pattern = list(\"cell\" = data_W, \"signaling\" = data_H)\n methods::slot(object, slot.name)$pattern[[pattern]] <- list(data = data0, pattern = res.pattern)\n return(object)\n}\n\n\n#' Compute signaling network similarity for any pair of signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param k the number of nearest neighbors\n#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity\n#' @importFrom methods slot\n\n#'\n#' @return\n#' @export\n#'\n#' @examples\ncomputeNetSimilarity <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), k = NULL, thresh = NULL) {\n type <- match.arg(type)\n prob = methods::slot(object, slot.name)$prob\n if (is.null(k)) {\n if (dim(prob)[3] <= 25) {\n k <- ceiling(sqrt(dim(prob)[3]))\n } else {\n k <- ceiling(sqrt(dim(prob)[3])) + 1\n }\n\n }\n if (!is.null(thresh)) {\n prob[prob < quantile(c(prob[prob != 0]), thresh)] <- 0\n }\n if (type == \"functional\") {\n # compute the functional similarity\n D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])\n S2 <- D_signalings; S3 <- D_signalings;\n for (i in 1:(dim(prob)[3]-1)) {\n for (j in (i+1):dim(prob)[3]) {\n Gi <- (prob[ , ,i] > 0)*1\n Gj <- (prob[ , ,j] > 0)*1\n S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)\n }\n }\n # define the similarity matrix\n S3[is.na(S3)] <- 0; S3 <- S3 + t(S3); diag(S3) <- 1\n # S_signalings <- S1 *S2\n S_signalings <- S3\n } else if (type == \"structural\") {\n # compute the structure distance\n D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])\n for (i in 1:(dim(prob)[3]-1)) {\n for (j in (i+1):dim(prob)[3]) {\n Gi <- (prob[ , ,i] > 0)*1\n Gj <- (prob[ , ,j] > 0)*1\n D_signalings[i,j] <- computeNetD_structure(Gi,Gj)\n }\n }\n # define the structure similarity matrix\n D_signalings[is.infinite(D_signalings)] <- 0\n D_signalings[is.na(D_signalings)] <- 0\n D_signalings <- D_signalings + t(D_signalings)\n S_signalings <- 1-D_signalings\n }\n\n # smooth the similarity matrix using SNN\n SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)\n Similarity <- as.matrix(S_signalings*SNN)\n rownames(Similarity) <- dimnames(prob)[[3]]\n colnames(Similarity) <- dimnames(prob)[[3]]\n\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {\n methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity\n return(object)\n}\n\n\n\n#' Compute signaling network similarity for any pair of datasets\n#'\n#' @param object A merged CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison\n#' @param k the number of nearest neighbors\n#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity\n#' @importFrom methods slot\n#'\n#' @return\n#' @export\n#'\ncomputeNetSimilarityPairwise <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, k = NULL, thresh = NULL) {\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Compute signaling network similarity for datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n net <- list()\n signalingAll <- c()\n object.net.nameAll <- c()\n # 1:length(setdiff(names(methods::slot(object, slot.name)), \"similarity\"))\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n object.net.name <- names(methods::slot(object, slot.name))[comparison[i]]\n object.net.nameAll <- c(object.net.nameAll, object.net.name)\n net[[i]] = object.net$prob\n signalingAll <- c(signalingAll, paste0(dimnames(net[[i]])[[3]], \"--\", object.net.name))\n # signalingAll <- c(signalingAll, dimnames(net[[i]])[[3]])\n }\n names(net) <- object.net.nameAll\n net.dim <- sapply(net, dim)[3,]\n nnet <- sum(net.dim)\n position <- cumsum(net.dim); position <- c(0,position)\n\n if (is.null(k)) {\n if (nnet <= 25) {\n k <- ceiling(sqrt(nnet))\n } else {\n k <- ceiling(sqrt(nnet)) + 1\n }\n\n }\n if (!is.null(thresh)) {\n for (i in 1:length(net)) {\n neti <- net[[i]]\n neti[neti < quantile(c(neti[neti != 0]), thresh)] <- 0\n net[[i]] <- neti\n }\n }\n if (type == \"functional\") {\n # compute the functional similarity\n S3 <- matrix(0, nrow = nnet, ncol = nnet)\n for (i in 1:nnet) {\n for (j in 1:nnet) {\n idx.i <- which(position - i >= 0)[1]\n idx.j <- which(position - j >= 0)[1]\n net.i <- net[[idx.i-1]]\n net.j <- net[[idx.j-1]]\n Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1\n Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1\n S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)\n }\n }\n\n # define the similarity matrix\n S3[is.na(S3)] <- 0; diag(S3) <- 1\n S_signalings <- S3\n } else if (type == \"structural\") {\n # compute the structure distance\n D_signalings <- matrix(0, nrow = nnet, ncol = nnet)\n for (i in 1:nnet) {\n for (j in 1:nnet) {\n idx.i <- which(position - i >= 0)[1]\n idx.j <- which(position - j >= 0)[1]\n net.i <- net[[idx.i-1]]\n net.j <- net[[idx.j-1]]\n Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1\n Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1\n D_signalings[i,j] <- computeNetD_structure(Gi,Gj)\n }\n }\n # define the structure similarity matrix\n D_signalings[is.infinite(D_signalings)] <- 0\n D_signalings[is.na(D_signalings)] <- 0\n S_signalings <- 1-D_signalings\n }\n # smooth the similarity matrix using SNN\n SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)\n Similarity <- as.matrix(S_signalings*SNN)\n rownames(Similarity) <- signalingAll\n colnames(Similarity) <- rownames(Similarity)\n\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {\n methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL\n }\n # methods::slot(object, slot.name)$similarity[[type]]$matrix <- Similarity\n methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity\n return(object)\n}\n\n\n#' Manifold learning of the signaling networks based on their similarity\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object\n#' @param pathway.remove a range of the number of patterns\n#' @param umap.method UMAP implementation to run.\n#'\n#' Can be umap-learn: Run the python umap-learn package; uwot: Runs umap via the uwot R package; If umap.method = \"uwot\", please make sure you have installed the 'uwot' (https://github.com/jlmelville/uwot)\n#'\n#' @param n_neighbors the number of nearest neighbors in running umap\n#' @param min_dist This controls how tightly the embedding is allowed compress points together.\n#' Larger values ensure embedded points are moreevenly distributed, while smaller values allow the\n#' algorithm to optimise more accurately with regard to local structure. Sensible values are in the range 0.001 to 0.5.\n#' @param ... Parameters passing to umap\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetEmbedding <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, pathway.remove = NULL,\n umap.method = c(\"umap-learn\", \"uwot\"), n_neighbors = NULL,min_dist = 0.3,...) {\n umap.method <- match.arg(umap.method)\n if (object@options$mode == \"single\") {\n comparison <- \"single\"\n cat(\"Manifold learning of the signaling networks for a single dataset\", '\\n')\n } else if (object@options$mode == \"merged\") {\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Manifold learning of the signaling networks for datasets\", as.character(comparison), '\\n')\n }\n comparison.name <- paste(comparison, collapse = \"-\")\n Similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n if (is.null(pathway.remove)) {\n pathway.remove <- rownames(Similarity)[which(colSums(Similarity) == 1)]\n }\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(rownames(Similarity) %in% pathway.remove)\n Similarity <- Similarity[-pathway.remove.idx, -pathway.remove.idx]\n }\n if (is.null(n_neighbors)) {\n n_neighbors <- ceiling(sqrt(dim(Similarity)[1])) + 1\n }\n options(warn = -1)\n # dimension reduction\n if (umap.method == \"umap-learn\") {\n Y <- runUMAP(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)\n } else if (umap.method == \"uwot\") {\n Y <- uwot::umap(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)\n colnames(Y) <- paste0('UMAP', 1:ncol(Y))\n rownames(Y) <- colnames(Similarity)\n }\n\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$dr)) {\n methods::slot(object, slot.name)$similarity[[type]]$dr <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]] <- Y\n return(object)\n}\n\n\n#' Classification learning of the signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object\n#' @param k the number of signaling groups when running kmeans\n#' @param methods the methods for clustering: \"kmeans\" or \"spectral\"\n#' @param do.plot whether showing the eigenspectrum for inferring number of clusters; Default will save the plot\n#' @param fig.id add a unique figure id when saving the plot\n#' @param do.parallel whether doing parallel when inferring the number of signaling groups when running kmeans\n#' @param nCores number of workers when doing parallel\n#' @param k.eigen the number of eigenvalues used when doing spectral clustering\n#' @importFrom methods slot\n#' @importFrom future nbrOfWorkers plan\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @return\n#' @export\n#'\n#' @examples\nnetClustering <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, k = NULL, methods = \"kmeans\", do.plot = TRUE, fig.id = NULL, do.parallel = TRUE, nCores = 4, k.eigen = NULL) {\n type <- match.arg(type)\n if (object@options$mode == \"single\") {\n comparison <- \"single\"\n cat(\"Classification learning of the signaling networks for a single dataset\", '\\n')\n } else if (object@options$mode == \"merged\") {\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Classification learning of the signaling networks for datasets\", as.character(comparison), '\\n')\n }\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n data.use <- Y\n if (methods == \"kmeans\") {\n if (!is.null(k)) {\n clusters = kmeans(data.use,k,nstart=10)$cluster\n } else {\n N <- nrow(data.use)\n kRange <- seq(2,min(N-1, 10),by = 1)\n if (do.parallel) {\n future::plan(\"multisession\", workers = nCores)\n options(future.globals.maxSize = 1000 * 1024^2)\n }\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n results = my.sapply(\n X = 1:length(kRange),\n FUN = function(x) {\n idents <- kmeans(data.use,kRange[x],nstart=10)$cluster\n clusIndex <- idents\n #adjMat0 <- as.numeric(outer(clusIndex, clusIndex, FUN = \"==\")) - outer(1:N, 1:N, \"==\")\n adjMat0 <- Matrix::Matrix(as.numeric(outer(clusIndex, clusIndex, FUN = \"==\")), nrow = N, ncol = N)\n return(list(adjMat = adjMat0, ncluster = length(unique(idents))))\n },\n simplify = FALSE\n )\n adjMat <- lapply(results, \"[[\", 1)\n CM <- Reduce('+', adjMat)/length(kRange)\n res <- computeEigengap(as.matrix(CM))\n numCluster <- res$upper_bound\n clusters = kmeans(data.use,numCluster,nstart=10)$cluster\n if (do.plot) {\n gg <- res$gg.obj\n ggsave(filename= paste0(\"estimationNumCluster_\",fig.id,\"_\",type,\"_dataset_\",comparison.name,\".pdf\"), plot=gg, width = 3.5, height = 3, units = 'in', dpi = 300)\n }\n }\n\n } else if (methods == \"spectral\") {\n A <- as.matrix(data.use)\n D <- apply(A, 1, sum)\n L <- diag(D)-A # unnormalized version\n L <- diag(D^-0.5)%*%L%*% diag(D^-0.5) # normalized version\n evL <- eigen(L,symmetric=TRUE) # evL$values is decreasing sorted when symmetric=TRUE\n # pick the first k first k eigenvectors (corresponding k smallest) as data points in spectral space\n plot(rev(evL$values)[1:30])\n Z <- evL$vectors[,(ncol(evL$vectors)-k.eigen+1):ncol(evL$vectors)]\n clusters = kmeans(Z,k,nstart=20)$cluster\n }\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$group)) {\n methods::slot(object, slot.name)$similarity[[type]]$group <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]] <- clusters\n return(object)\n}\n\n\n#' Build SNN matrix\n# #' Adapted from swne (https://github.com/yanwu2014/swne)\n#' @param data.use Features x samples matrix to use to build the SNN\n#' @param k Defines k for the k-nearest neighbor algorithm\n#' @param k.scale Granularity option for k.param\n#' @param prune.SNN Sets the cutoff for acceptable Jaccard distances when\n#' computing the neighborhood overlap for the SNN construction.\n#'\n#' @return Returns similarity matrix in sparse matrix format\n#'\n#' @importFrom FNN get.knn\n#' @importFrom Matrix sparseMatrix\n#' @export\n#'\nbuildSNN <- function(data.use, k = 10, k.scale = 10, prune.SNN = 1/15) {\n n.cells <- ncol(data.use)\n if (n.cells < k) {\n stop(\"k cannot be greater than the number of samples\")\n }\n\n ## find the k-nearest neighbors for each single cell\n my.knn <- FNN::get.knn(t(as.matrix(data.use)), k = min(k.scale * k, n.cells - 1))\n nn.ranked <- cbind(1:n.cells, my.knn$nn.index[, 1:(k - 1)])\n nn.large <- my.knn$nn.index\n\n w <- ComputeSNN(nn.ranked, prune.SNN)\n colnames(w) <- rownames(w) <- colnames(data.use)\n\n Matrix::diag(w) <- 1\n return(w)\n}\n\n\n\n#' Compute the eigengap of a given matrix for inferring the number of clusters\n#'\n#' @param CM consensus matrix\n#' @param tau truncated consensus matrix\n#' @param tol tolerance\n#' @return\n#' @import ggplot2\n#' @export\ncomputeEigengap <- function(CM, tau = NULL, tol = 0.01){\n # compute the drop tolerance, enforcing parsimony of components\n K.init <- computeLaplacian(CM, tol = tol)$n_zeros\n if (is.null(tau)) {\n if (K.init <= 5) {\n tau = 0.3\n } else if (K.init <= 10){\n tau = 0.4\n } else {\n tau = 0.5\n }\n }\n\n # truncate the ensemble consensus matrix\n CM[CM <= tau] <- 0;\n # normalize and make symmetric\n CM <- (CM + t(CM))/2\n eigs <- computeLaplacian(CM, tol = tol)\n\n # compute the largest eigengap\n gaps <- diff(eigs$val)\n upper_bound <- which(gaps == max(gaps))\n\n # compute the number of zero eigenvalues\n lower_bound <- eigs$n_zeros\n\n df <- data.frame(nCluster = 1:min(c(30,length(eigs$val))), eigenVal = eigs$val[1:min(c(30,length(eigs$val)))])\n g <- ggplot(df, aes(x = nCluster, y = eigenVal)) + geom_point(size = 1) +\n geom_point(aes(x= upper_bound, y= eigs$val[upper_bound]), colour=\"red\", size = 3, pch = 1) + theme(legend.position=\"none\")\n title.name <- paste0('Inferred number of clusters: ', upper_bound,'; Min number: ', lower_bound)\n g <- g + labs(title = title.name) + theme_bw() + scale_x_continuous(breaks=seq(0,30,5)) +\n theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = 10)) + labs(x = 'Number of clusters', y = 'Eigenvalue of graph Laplacian')+\n theme(axis.text.x = element_text(size = 8), axis.text.y = element_text(size = 8))\n # ggsave(filename= paste0(\"estimationNumCluster_eigenspectrum\",sample.int(100,1),\".pdf\"), plot=g, width = 3.5, height = 3, units = 'in', dpi = 300)\n return(list(upper_bound = upper_bound,\n lower_bound = lower_bound,\n eigs = eigs,\n gg.obj = g))\n\n}\n\n\n#' Compute eigenvalues of associated Laplacian matrix of a given matrix\n#'\n#' @param CM consensus matrix\n#' @param tol tolerance\n#' @return\n#' @importFrom RSpectra eigs_sym\n#' @importFrom Matrix colSums\n#' @export\ncomputeLaplacian <- function(CM, tol = 0.01) {\n # Normalized Laplacian:\n Dsq <- sqrt(Matrix::colSums(CM))\n L <- -Matrix::t(CM / Dsq) / Dsq\n Matrix::diag(L) <- 1 + Matrix::diag(L)\n\n numEigs <- min(100,nrow(CM))\n res <- RSpectra::eigs_sym(L, k = numEigs, which = \"SM\", opt = list(tol = 1e-4))\n eigs <- abs(Re(res$values))\n n_zeros <- sum(eigs <= tol)\n return(list(val = sort(eigs), n_zeros = n_zeros))\n}\n\n\n#' Rank the similarity of the shared signaling pathways based on their joint manifold learning\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison1 a numerical vector giving the datasets for comparison. This should be the same as `comparison` in `computeNetSimilarityPairwise`\n#' @param comparison2 a numerical vector with two elements giving the datasets for comparison.\n#'\n#' If there are more than 2 datasets defined in `comparison1`, `comparison2` can be defined to indicate which two datasets used for computing the distance.\n#' e.g., comparison2 = c(1,3) indicates the first and third datasets defined in `comparison1` will be used for comparison.\n#' @param x.rotation rotation of x-labels\n#' @param title main title of the plot\n#' @param bar.w the width of bar plot\n#' @param color.use defining the color\n#' @param font.size font size\n#' @import ggplot2\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nrankSimilarity <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison1 = NULL, comparison2 = c(1,2),\n x.rotation = 90, title = NULL, color.use = NULL, bar.w = NULL, font.size = 8) {\n type <- match.arg(type)\n\n if (is.null(comparison1)) {\n comparison1 <- 1:length(unique(object@meta$datasets))\n }\n comparison.name <- paste(comparison1, collapse = \"-\")\n cat(\"Compute the distance of signaling networks between datasets\", as.character(comparison1[comparison2]), '\\n')\n comparison2.name <- names(methods::slot(object, slot.name))[comparison1[comparison2]]\n # net <- list()\n # for (i in 1:length(comparison2)) {\n # net[[i]] = methods::slot(object, slot.name)[[comparison1[comparison2[i]]]]$prob\n # }\n\n #net.dim <- sapply(net, dim)[3,]\n #position <- cumsum(net.dim); position <- c(0,position)\n # if (is.null(pathway.remove)) {\n # similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n # pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove.idx <- which(rownames(similarity) %in% pathway.remove)\n # }\n\n # if (length(pathway.remove.idx) > 0) {\n # for (i in 1:length(pathway.remove.idx)) {\n # idx <- which(position - pathway.remove.idx[i] > 0)\n # if (!is.null(idx)) {\n # position[idx[1]] <- position[idx[1]] - 1\n # if (idx[1] == 2) {\n # position[3] <- position[3] - 1\n # }\n # }\n # }\n # }\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n group <- sub(\".*--\", \"\", rownames(Y))\n data1 <- Y[group %in% comparison2.name[1], ]\n data2 <- Y[group %in% comparison2.name[2], ]\n rownames(data1) <- sub(\"--.*\", \"\", rownames(data1))\n rownames(data2) <- sub(\"--.*\", \"\", rownames(data2))\n\n pathway.show = as.character(intersect(rownames(data1), rownames(data2)))\n data1 <- data1[pathway.show, ]\n data2 <- data2[pathway.show, ]\n euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))\n dist <- NULL\n for(i in 1:nrow(data1)) dist[i] <- euc.dist(data1[i,],data2[i,])\n df <- data.frame(name = pathway.show, dist = dist, row.names = pathway.show)\n df <- df[order(df$dist), , drop = F]\n df$name <- factor(df$name, levels = as.character(df$name))\n\n gg <- ggplot(df, aes(x=name, y=dist)) + geom_bar(stat=\"identity\",width = bar.w) +\n theme_classic() + theme(text=element_text(size=font.size),axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_text(size=font.size)) +\n xlab(\"\") + ylab(\"Pathway distance\") + coord_flip()#+\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n if (!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = 1), drop = FALSE, na.value = \"white\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, na.value = \"white\")\n }\n return(gg)\n}\n\n\n\n\n\n\n\n#' Rank signaling networks based on the information flow or the number of interactions\n#'\n#' This function can also be used to rank signaling from certain cell groups to other cell groups\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param measure \"weight\" or \"count\". \"weight\": comparing the total interaction weights (strength); \"count\": comparing the number of interactions;\n#' @param mode \"single\",\"comparison\"\n#' @param comparison a numerical vector giving the datasets for comparison; a single value means ranking for only one dataset and two values means ranking comparison for two datasets\n#' @param color.use defining the color for each cell group\n#' @param stacked whether plot the stacked bar plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a vector giving the signaling pathway to show\n#' @param pairLR a vector giving the names of L-R pairs to show (e.g, pairLR = c(\"IL1A_IL1R1_IL1RAP\",\"IL1B_IL1R1_IL1RAP\"))\n#' @param signaling.type a char giving the types of signaling from the three categories c(\"Secreted Signaling\", \"ECM-Receptor\", \"Cell-Cell Contact\")\n#' @param do.stat whether do a Wilcoxon test to determine whether there is significant difference between two datasets. Default = FALSE\n#' @param paired.test a logical indicating whether you want a paired test. Paired test is applicable to compare two datasets with the same cellular compositions.\n#' @param cutoff.pvalue the cutoff of pvalue when doing Wilcoxon test; Default = 0.05\n#' @param tol a tolerance when considering the relative contribution being equal between two datasets. contribution.relative between 1-tol and 1+tol will be considered as equal contribution\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @param do.flip whether flip the x-y axis\n#' @param x.angle,y.angle,x.hjust,y.hjust parameters for rotating and spacing axis labels\n#' @param axis.gap whetehr making gaps in y-axes\n#' @param ylim,segments,tick_width,rel_heights parameters in the function gg.gap when making gaps in y-axes\n#' e.g., ylim = c(0, 35), segments = list(c(11, 14),c(16, 28)), tick_width = c(5,2,5), rel_heights = c(0.8,0,0.1,0,0.1)\n#' https://tobiasbusch.xyz/an-r-package-for-everything-ep2-gaps\n#' @param show.raw whether show the raw information flow. Default = FALSE, showing the scaled information flow to provide compariable data scale; When stacked = TRUE, use raw information flow by default.\n#' @param return.data whether return the data.frame consisting of the calculated information flow of each signaling pathway or L-R pair\n#' @param x.rotation rotation of x-labels\n#' @param title main title of the plot\n#' @param bar.w the width of bar plot\n#' @param font.size font size\n\n#' @import ggplot2\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nrankNet <- function(object, slot.name = \"netP\", measure = c(\"weight\",\"count\"), mode = c(\"comparison\", \"single\"), comparison = c(1,2), color.use = NULL, stacked = FALSE, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR = NULL, signaling.type = NULL, do.stat = FALSE, paired.test = TRUE, cutoff.pvalue = 0.05, tol = 0.05, thresh = 0.05, show.raw = FALSE, return.data = FALSE, x.rotation = 90, title = NULL, bar.w = 0.75, font.size = 8,\n do.flip = TRUE, x.angle = NULL, y.angle = 0, x.hjust = 1,y.hjust = 1,\n axis.gap = FALSE, ylim = NULL, segments = NULL, tick_width = NULL, rel_heights = c(0.9,0,0.1)) {\n measure <- match.arg(measure)\n mode <- match.arg(mode)\n options(warn = -1)\n object.names <- names(methods::slot(object, slot.name))\n if (measure == \"weight\") {\n ylabel = \"Information flow\"\n } else if (measure == \"count\") {\n ylabel = \"Number of interactions\"\n }\n if (mode == \"single\") {\n object1 <- methods::slot(object, slot.name)\n prob = object1$prob\n prob[object1$pval > thresh] <- 0\n if (measure == \"count\") {\n prob <- 1*(prob > 0)\n }\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n if (sum(prob) == 0) {\n stop(\"No inferred communications for the input!\")\n }\n\n pSum <- apply(prob, 3, sum)\n pSum.original <- pSum\n if (measure == \"weight\") {\n pSum <- -1/log(pSum)\n pSum[is.na(pSum)] <- 0\n idx1 <- which(is.infinite(pSum) | pSum < 0)\n values.assign <- seq(max(pSum)*1.1, max(pSum)*1.5, length.out = length(idx1))\n position <- sort(pSum.original[idx1], index.return = TRUE)$ix\n pSum[idx1] <- values.assign[match(1:length(idx1), position)]\n } else if (measure == \"count\") {\n pSum <- pSum.original\n }\n\n pair.name <- names(pSum)\n\n df<- data.frame(name = pair.name, contribution = pSum.original, contribution.scaled = pSum, group = object.names[comparison[1]])\n idx <- with(df, order(df$contribution))\n df <- df[idx, ]\n df$name <- factor(df$name, levels = as.character(df$name))\n for (i in 1:length(pair.name)) {\n df.t <- df[df$name == pair.name[i], \"contribution\"]\n if (sum(df.t) == 0) {\n df <- df[-which(df$name == pair.name[i]), ]\n }\n }\n\n if (!is.null(signaling.type)) {\n LR <- subset(object@DB$interaction, annotation %in% signaling.type)\n if (slot.name == \"netP\") {\n signaling <- unique(LR$pathway_name)\n } else if (slot.name == \"net\") {\n pairLR <- LR$interaction_name\n }\n }\n\n if ((slot.name == \"netP\") && (!is.null(signaling))) {\n df <- subset(df, name %in% signaling)\n } else if ((slot.name == \"netP\") &&(!is.null(pairLR))) {\n stop(\"You need to set `slot.name == 'net'` if showing specific L-R pairs \")\n }\n if ((slot.name == \"net\") && (!is.null(pairLR))) {\n df <- subset(df, name %in% pairLR)\n } else if ((slot.name == \"net\") && (!is.null(signaling))) {\n stop(\"You need to set `slot.name == 'netP'` if showing specific signaling pathways \")\n }\n\n gg <- ggplot(df, aes(x=name, y=contribution.scaled)) + geom_bar(stat=\"identity\",width = bar.w) +\n theme_classic() + theme(axis.text=element_text(size=font.size),axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(ylabel) + coord_flip()#+\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n\n } else if (mode == \"comparison\") {\n prob.list <- list()\n pSum <- list()\n pSum.original <- list()\n pair.name <- list()\n idx <- list()\n pSum.original.all <- c()\n object.names.comparison <- c()\n for (i in 1:length(comparison)) {\n object.list <- methods::slot(object, slot.name)[[comparison[i]]]\n prob <- object.list$prob\n prob[object.list$pval > thresh] <- 0\n if (measure == \"count\") {\n prob <- 1*(prob > 0)\n }\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n if (sum(prob) == 0) {\n stop(\"No inferred communications for the input!\")\n }\n prob.list[[i]] <- prob\n pSum.original[[i]] <- apply(prob, 3, sum)\n if (measure == \"weight\") {\n pSum[[i]] <- -1/log(pSum.original[[i]])\n pSum[[i]][is.na(pSum[[i]])] <- 0\n idx[[i]] <- which(is.infinite(pSum[[i]]) | pSum[[i]] < 0)\n pSum.original.all <- c(pSum.original.all, pSum.original[[i]][idx[[i]]])\n } else if (measure == \"count\") {\n pSum[[i]] <- pSum.original[[i]] # the prob is already binarized in line 1136\n }\n pair.name[[i]] <- names(pSum.original[[i]])\n object.names.comparison <- c(object.names.comparison, object.names[comparison[i]])\n }\n if (measure == \"weight\") {\n values.assign <- seq(max(unlist(pSum))*1.1, max(unlist(pSum))*1.5, length.out = length(unlist(idx)))\n position <- sort(pSum.original.all, index.return = TRUE)$ix\n for (i in 1:length(comparison)) {\n if (i == 1) {\n pSum[[i]][idx[[i]]] <- values.assign[match(1:length(idx[[i]]), position)]\n } else {\n pSum[[i]][idx[[i]]] <- values.assign[match(length(unlist(idx[1:i-1]))+1:length(unlist(idx[1:i])), position)]\n }\n }\n }\n\n\n\n pair.name.all <- as.character(unique(unlist(pair.name)))\n df <- list()\n for (i in 1:length(comparison)) {\n df[[i]] <- data.frame(name = pair.name.all, contribution = 0, contribution.scaled = 0, group = object.names[comparison[i]], row.names = pair.name.all)\n df[[i]][pair.name[[i]],3] <- pSum[[i]]\n df[[i]][pair.name[[i]],2] <- pSum.original[[i]]\n }\n\n\n # contribution.relative <- as.numeric(format(df[[length(comparison)]]$contribution/abs(df[[1]]$contribution), digits=1))\n # # contribution.relative <- as.numeric(format(df[[length(comparison)]]$contribution.scaled/abs(df[[1]]$contribution.scaled), digits=1))\n # contribution.relative2 <- as.numeric(format(df[[length(comparison)-1]]$contribution/abs(df[[1]]$contribution), digits=1))\n # contribution.relative[is.na(contribution.relative)] <- 0\n # for (i in 1:length(comparison)) {\n # df[[i]]$contribution.relative <- contribution.relative\n # df[[i]]$contribution.relative2 <- contribution.relative2\n # }\n # df[[1]]$contribution.data2 <- df[[length(comparison)]]$contribution\n # idx <- with(df[[1]], order(-contribution.relative, -contribution.relative2, contribution, -contribution.data2))\n #\n contribution.relative <- list()\n for (i in 1:(length(comparison)-1)) {\n contribution.relative[[i]] <- as.numeric(format(df[[length(comparison)-i+1]]$contribution/df[[1]]$contribution, digits=1))\n contribution.relative[[i]][is.na(contribution.relative[[i]])] <- 0\n }\n names(contribution.relative) <- paste0(\"contribution.relative.\", 1:length(contribution.relative))\n for (i in 1:length(comparison)) {\n for (j in 1:length(contribution.relative)) {\n df[[i]][[names(contribution.relative)[j]]] <- contribution.relative[[j]]\n }\n }\n df[[1]]$contribution.data2 <- df[[length(comparison)]]$contribution\n if (length(comparison) == 2) {\n idx <- with(df[[1]], order(-contribution.relative.1, contribution, -contribution.data2))\n } else if (length(comparison) == 3) {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2,contribution, -contribution.data2))\n } else if (length(comparison) == 4) {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2, -contribution.relative.3, contribution, -contribution.data2))\n } else {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2, -contribution.relative.3, -contribution.relative.4, contribution, -contribution.data2))\n }\n\n\n\n for (i in 1:length(comparison)) {\n df[[i]] <- df[[i]][idx, ]\n df[[i]]$name <- factor(df[[i]]$name, levels = as.character(df[[i]]$name))\n }\n df[[1]]$contribution.data2 <- NULL\n\n df <- do.call(rbind, df)\n df$group <- factor(df$group, levels = object.names.comparison)\n\n if (is.null(color.use)) {\n color.use = ggPalette(length(comparison))\n }\n\n # https://stackoverflow.com/questions/49448497/coord-flip-changes-ordering-of-bars-within-groups-in-grouped-bar-plot\n df$group <- factor(df$group, levels = rev(levels(df$group)))\n color.use <- rev(color.use)\n\n # perform statistical analysis\n # if (do.stat) {\n # pvalues <- c()\n # for (i in 1:length(pair.name.all)) {\n # df.prob <- data.frame()\n # for (j in 1:length(comparison)) {\n # if (pair.name.all[i] %in% pair.name[[j]]) {\n # df.prob <- rbind(df.prob, data.frame(prob = as.vector(prob.list[[j]][ , , pair.name.all[i]]), group = comparison[j]))\n # } else {\n # df.prob <- rbind(df.prob, data.frame(prob = as.vector(matrix(0, nrow = nrow(prob.list[[j]]), ncol = nrow(prob.list[[j]]))), group = comparison[j]))\n # }\n #\n # }\n # df.prob$group <- factor(df.prob$group, levels = comparison)\n # if (length(comparison) == 2) {\n # pvalues[i] <- wilcox.test(prob ~ group, data = df.prob)$p.value\n # } else {\n # pvalues[i] <- kruskal.test(prob ~ group, data = df.prob)$p.value\n # }\n # }\n # df$pvalues <- pvalues\n # }\n if (do.stat & length(comparison) == 2) {\n for (i in 1:length(pair.name.all)) {\n if (nrow(prob.list[[j]]) != nrow(prob.list[[1]])) {\n if (paired.test) {\n stop(\"Paired test is not applicable to datasets with different cellular compositions! Please set `do.stat = FALSE` or `paired.test = FALSE`! \\n\")\n }\n }\n prob.values <- matrix(0, nrow = nrow(prob.list[[1]]) * nrow(prob.list[[1]]), ncol = length(comparison))\n for (j in 1:length(comparison)) {\n if (pair.name.all[i] %in% pair.name[[j]]) {\n prob.values[, j] <- as.vector(prob.list[[j]][ , , pair.name.all[i]])\n } else {\n prob.values[, j] <- NA\n }\n }\n prob.values <- prob.values[rowSums(prob.values, na.rm = TRUE) != 0, , drop = FALSE]\n if (nrow(prob.values) >3 & sum(is.na(prob.values)) == 0) {\n pvalues <- wilcox.test(prob.values[ ,1], prob.values[ ,2], paired = paired.test)$p.value\n } else {\n pvalues <- 0\n }\n pvalues[is.na(pvalues)] <- 0\n df$pvalues[df$name == pair.name.all[i]] <- pvalues\n }\n }\n\n\n if (length(comparison) == 2) {\n if (do.stat) {\n colors.text <- ifelse((df$contribution.relative < 1-tol) & (df$pvalues < cutoff.pvalue), color.use[2], ifelse((df$contribution.relative > 1+tol) & df$pvalues < cutoff.pvalue, color.use[1], \"black\"))\n } else {\n colors.text <- ifelse(df$contribution.relative < 1-tol, color.use[2], ifelse(df$contribution.relative > 1+tol, color.use[1], \"black\"))\n }\n } else {\n message(\"The text on the y-axis will not be colored for the number of compared datasets larger than 3!\")\n colors.text = NULL\n }\n\n for (i in 1:length(pair.name.all)) {\n df.t <- df[df$name == pair.name.all[i], \"contribution\"]\n if (sum(df.t) == 0) {\n df <- df[-which(df$name == pair.name.all[i]), ]\n }\n }\n\n if ((slot.name == \"netP\") && (!is.null(signaling))) {\n df <- subset(df, name %in% signaling)\n } else if ((slot.name == \"netP\") &&(!is.null(pairLR))) {\n stop(\"You need to set `slot.name == 'net'` if showing specific L-R pairs \")\n }\n if ((slot.name == \"net\") && (!is.null(pairLR))) {\n df <- subset(df, name %in% pairLR)\n } else if ((slot.name == \"net\") && (!is.null(signaling))) {\n stop(\"You need to set `slot.name == 'netP'` if showing specific signaling pathways \")\n }\n\n if (stacked) {\n gg <- ggplot(df, aes(x=name, y=contribution, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position =\"fill\") # +\n # xlab(\"\") + ylab(\"Relative information flow\") #+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n # scale_y_discrete(breaks=c(\"0\",\"0.5\",\"1\")) +\n if (measure == \"weight\") {\n gg <- gg + xlab(\"\") + ylab(\"Relative information flow\")\n } else if (measure == \"count\") {\n gg <- gg + xlab(\"\") + ylab(\"Relative number of interactions\")\n }\n\n gg <- gg + geom_hline(yintercept = 0.5, linetype=\"dashed\", color = \"grey50\", size=0.5)\n } else {\n if (show.raw) {\n gg <- ggplot(df, aes(x=name, y=contribution, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position = position_dodge(0.8)) +\n xlab(\"\") + ylab(ylabel) #+ coord_flip()#+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n } else {\n gg <- ggplot(df, aes(x=name, y=contribution.scaled, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position = position_dodge(0.8)) +\n xlab(\"\") + ylab(ylabel) #+ coord_flip()#+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n }\n\n if (axis.gap) {\n gg <- gg + theme_bw() + theme(panel.grid = element_blank())\n gg.gap::gg.gap(gg,\n ylim = ylim,\n segments = segments,\n tick_width = tick_width,\n rel_heights = rel_heights)\n }\n }\n gg <- gg + CellChat_theme_opts() + theme_classic()\n if (do.flip) {\n gg <- gg + coord_flip() + theme(axis.text.y = element_text(colour = colors.text))\n if (is.null(x.angle)) {\n x.angle = 0\n }\n\n } else {\n if (is.null(x.angle)) {\n x.angle = 45\n }\n gg <- gg + scale_x_discrete(limits = rev) + theme(axis.text.x = element_text(colour = rev(colors.text)))\n\n }\n\n gg <- gg + theme(axis.text=element_text(size=font.size), axis.title.y = element_text(size=font.size))\n gg <- gg + scale_fill_manual(name = \"\", values = color.use)\n gg <- gg + guides(fill = guide_legend(reverse = TRUE))\n gg <- gg + theme(axis.text.x = element_text(angle = x.angle, hjust=x.hjust),\n axis.text.y = element_text(angle = y.angle, hjust=y.hjust))\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n }\n\n if (return.data) {\n df$contribution <- abs(df$contribution)\n df$contribution.scaled <- abs(df$contribution.scaled)\n return(list(signaling.contribution = df, gg.obj = gg))\n } else {\n return(gg)\n }\n}\n\n\n#' Comparing the number of inferred communication links between different datasets\n#'\n#' @param object A merged CellChat object\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param color.use defining the color for each group of datasets\n#' @param group a vector giving the groups of different datasets to define colors of the bar plot. Default: only one group and a single color\n#' @param group.levels the factor level in the defined group\n#' @param group.facet Name of one metadata column defining faceting groups\n#' @param group.facet.levels the factor level in the defined group.facet\n#' @param n.row Number of rows in facet_grid()\n#' @param color.alpha transparency\n#' @param legend.title legend title\n#' @param width bar width\n#' @param title.name main title of the plot\n#' @param digits integer indicating the number of decimal places (round) to be used when `measure` is `weight`.\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param remove.xtick whether remove xtick\n#' @param size.text font size of the text\n#' @param show.legend whether show the legend\n#' @param x.lab.rot,angle.x,vjust.x,hjust.x adjusting parameters if rotating xtick.labels when x.lab.rot = TRUE\n#' @import ggplot2\n#' @return A ggplot object\n#' @export\n#'\ncompareInteractions <- function(object, measure = c(\"count\", \"weight\"), color.use = NULL, group = NULL, group.levels = NULL, group.facet = NULL, group.facet.levels = NULL, n.row = 1, color.alpha = 1, legend.title = NULL, width=0.6, title.name = NULL, digits = 3,\n xlabel = NULL, ylabel = NULL, remove.xtick = FALSE,\n show.legend = TRUE, x.lab.rot = FALSE, angle.x = 45, vjust.x = NULL, hjust.x = 1, size.text = 10) {\n measure <- match.arg(measure)\n if (measure == \"count\") {\n df <- as.data.frame(sapply(object@net, function(x) sum(x$count)))\n if (is.null(ylabel)) {\n ylabel = \"Number of inferred interactions\"\n }\n } else if (measure == \"weight\") {\n df <- as.data.frame(sapply(object@net, function(x) sum(x$weight)))\n df[,1] <- round(df[,1],digits)\n if (is.null(ylabel)) {\n ylabel = \"Interaction strength\"\n }\n }\n colnames(df) <- \"count\"\n\n df$dataset <- names(object@net)\n if (is.null(group)) {\n group <- 1\n }\n df$group <- group\n df$dataset <- factor(df$dataset, levels = names(object@net))\n if (is.null(group.levels)) {\n df$group <- factor(df$group)\n } else {\n df$group <- factor(df$group, levels = group.levels)\n }\n\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(group)))\n }\n # theme_classic() #+ scale_x_discrete(limits = (levels(df$x)))\n if (!is.null(group.facet)) {\n if (all(group.facet %in% colnames(df))) {\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n gg <- gg + facet_wrap(group.facet, nrow = n.row)\n } else {\n df$group.facet <- group.facet\n if (is.null(group.facet.levels)) {\n df$group.facet <- factor(df$group.facet)\n } else {\n df$group.facet <- factor(df$group.facet, levels = group.facet.levels)\n }\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n gg <- gg + facet_wrap(~group.facet, nrow = n.row)\n }\n } else {\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n }\n gg <- gg + geom_text(aes(label=count), vjust=-0.3, size=3, position = position_dodge(0.9))\n gg <- gg + ylab(ylabel) + xlab(xlabel) + theme_classic() +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = size.text), axis.text = element_text(colour=\"black\"))\n gg <- gg + scale_fill_manual(values = alpha(color.use, alpha = color.alpha), drop = FALSE)\n # gg <- gg + scale_color_manual(values = alpha(color.use, alpha = 1), drop = FALSE) + guides(colour = FALSE)\n if (remove.xtick) {\n gg <- gg + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank())\n }\n if (is.null(legend.title)) {\n gg <- gg + theme(legend.title = element_blank())\n } else {\n gg <- gg + guides(fill=guide_legend(legend.title))\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n if (x.lab.rot) {\n gg <- gg + theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x, vjust = vjust.x, size=size.text))\n }\n gg\n return(gg)\n}\n\n\n#' Rank ligand-receptor interactions for any pair of two cell groups\n#'\n#' @param object CellChat object\n#' @param LR.use ligand-receptor interactions used in inferring communication network\n#' @return\n#' @export\n#'\nrankNetPairwise <- function(object, LR.use = NULL) {\n if (is.null(LR.use)) {\n pairLR.use <- object@LR$LRsig\n } else {\n pairLR.use <- LR.use\n }\n net <- object@net\n prob <- net$prob\n pval <- net$pval\n numCluster <- dim(prob)[1]\n pairwiseLR <- list()\n for (i in 1:numCluster) {\n temp <- list()\n for (j in 1:numCluster) {\n pvalij <- pval[i,j,]; pvalij <- as.vector(pvalij)\n probij <- prob[i,j,]; probij <- as.vector(probij)\n index <- 1:length(pvalij)\n data <- data.frame(pathway_index = index, interaction_name = pairLR.use$interaction_name, interaction_name_2 = pairLR.use$interaction_name_2, pathway_name = pairLR.use$pathway_name, ligand = pairLR.use$ligand, receptor = pairLR.use$receptor,\n prob = probij, pval = pvalij, row.names = rownames(pairLR.use))\n temp[[j]] <- data[with(data, order(pval, -prob)), ]\n }\n names(temp) <- colnames(prob)\n pairwiseLR[[i]] <- temp\n }\n names(pairwiseLR) <- rownames(prob)\n object@net$pairwiseRank <- pairwiseLR\n return(object)\n}\n\n\n#' compute the Shannon entropy\n#'\n#' @param a a numeric vector\n#' @return\nentropia<-function(a){\n a<-a[which(a>0)]\n return(-sum(a*log(a)))\n}\n\n\n#' compute the node distance matrix\n#'\n#' @param g a graph objecct\n#' @return\nnode_distance<-function(g){\n n<-length(V(g))\n if(n==1){\n retorno=1\n }\n\n if(n>1){\n a<-Matrix::Matrix(0,nrow=n,ncol=n,sparse=TRUE)\n m<-igraph::shortest.paths(g,algorithm=c(\"unweighted\"))\n m[which(m==\"Inf\")]<-n\n quem<-setdiff(intersect(m,m),0)\n for(j in (1:length(quem))){\n\n l<-which(m==quem[j])/n\n\n linhas<-floor(l)+1\n\n posicoesm1<-which(l==floor(l))\n\n if(length(posicoesm1)>0){\n linhas[posicoesm1]<-linhas[posicoesm1]-1\n }\n a[1:n,quem[j]]<-hist(linhas,plot=FALSE,breaks=(0:n))$counts\n\n }\n retorno=(a/(n-1))\n }\n return(retorno)\n}\n\n\n#' compute nnd\n#'\n#' @param g a graph objecct\n#' @return\nnnd<-function(g){\n\n N<-length(V(g))\n\n nd<-node_distance(g)\n\n pdfm<-Matrix::colMeans(nd)\n\n norm<-log(max(c(2,length(which(pdfm[1:(N-1)]>0))+1)))\n\n return(c(pdfm,max(c(0,entropia(pdfm)-entropia(as.matrix(nd))/N))/norm))\n}\n\n#' compute alpha centrality\n#'\n#' @param g a graph objecct\n#' @importFrom igraph degree alpha.centrality\n#' @return\nalpha_centrality<-function(g){\n\n N<-length(igraph::V(g))\n\n r<-sort(igraph::alpha.centrality(g,exo=igraph::degree(g)/(N-1),alpha=1/N))/((N^2))\n\n return(c(r,max(c(0,1-sum(r)))))\n\n}\n\n#' Compute the structural distance between two signaling networks\n#'\n#' @param g a graph object of one signaling network\n#' @param h a graph object of another signaling network\n#' @param w1 parameter\n#' @param w2 parameter\n#' @param w3 parameter\n#' @importFrom igraph graph_from_adjacency_matrix V graph.complementer\n#' @return\n#' @export\n#'\n#' @examples\ncomputeNetD_structure <- function(g, h, w1 = 0.45, w2 = 0.45, w3 = 0.1){\n\n first<-0\n\n second<-0\n\n third<-0\n\n # g<-read.graph(g,format=c(\"edgelist\"),directed=FALSE)\n #\n # h<-read.graph(h,format=c(\"edgelist\"),directed=FALSE)\n\n g <- graph_from_adjacency_matrix(g,mode=\"directed\")\n h <- graph_from_adjacency_matrix(h,mode=\"directed\")\n\n N<-length(V(g))\n\n M<-length(V(h))\n\n PM<-matrix(0,ncol=max(c(M,N)))\n\n if(w1+w2>0){\n\n pg = nnd(g)\n\n PM[1:(N-1)]=pg[1:(N-1)]\n\n PM[length(PM)]<-pg[N]\n\n ph=nnd(h)\n\n PM[1:(M-1)]=PM[1:(M-1)]+ph[1:(M-1)]\n\n PM[length(PM)]<-PM[length(PM)]+ph[M]\n\n PM<-PM/2\n\n first<-sqrt(max(c((entropia(PM)-(entropia(pg[1:N])+entropia(ph[1:M]))/2)/log(2),0)))\n\n second<-abs(sqrt(pg[N+1])-sqrt(ph[M+1]))\n\n\n }\n\n if(w3>0){\n\n pg<-alpha_centrality(g)\n\n ph<-alpha_centrality(h)\n\n m<-max(c(length(pg),length(ph)))\n\n Pg<-matrix(0,ncol=m)\n\n Ph<-matrix(0,ncol=m)\n\n Pg[(m-length(pg)+1):m]<-pg\n\n Ph[(m-length(ph)+1):m]<-ph\n\n third<-third+sqrt((entropia((Pg+Ph)/2)-(entropia(pg)+entropia(ph))/2)/log(2))/2\n\n g<-graph.complementer(g)\n\n h<-graph.complementer(h)\n\n\n pg<-alpha_centrality(g)\n\n ph<-alpha_centrality(h)\n\n m<-max(c(length(pg),length(ph)))\n\n Pg<-matrix(0,ncol=m)\n\n Ph<-matrix(0,ncol=m)\n\n Pg[(m-length(pg)+1):m]<-pg\n\n Ph[(m-length(ph)+1):m]<-ph\n\n third<-third+sqrt((entropia((Pg+Ph)/2)-(entropia(pg)+entropia(ph))/2)/log(2))/2\n }\n return(w1*first+w2*second+w3*third)\n}\n\n\n#' Identify all the significant interactions (L-R pairs) and related signaling genes for a given signaling pathway\n#'\n#' @param object CellChat object\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param geneLR.return whether return the related signaling genes of enriched L-R pairs\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param geneInfo a dataframe with gene official symbol (there should be one column named `Symbol`)\n#' @param complex_input signaling complex information from CellChatDB\n#' @importFrom dplyr select\n#'\n#' @return The returned value depends on the input argument:\n#'\n#' When `geneLR.return = FALSE`, it returns a data frame containing the significant interactions (L-R pairs)\n#'\n#' When `geneLR.return = TRUE`, it returns a list, the first element is a data frame containing the significant interactions (L-R pairs), and the second is a vector containing the related signaling genes of enriched L-R pairs, which can be used for examining the gene expression pattern using the function \\code{\\link{plotGeneExpression}}\n#'\n#' @export\n#'\nextractEnrichedLR <- function(object, signaling, geneLR.return = FALSE, enriched.only = TRUE, thresh = 0.05, geneInfo = NULL, complex_input = NULL) {\n DB <- object@DB\n if (is.null(geneInfo)) {\n geneInfo = DB$geneInfo\n } else {\n DB$geneInfo = geneInfo\n }\n if (is.null(complex_input)) {\n complex_input = DB$complex\n } else {\n DB$complex = complex_input\n }\n pairLR.all <- c()\n geneLR.all <- c()\n net0 <- slot(object, \"net\")\n for (ii in 1:length(signaling)) {\n signaling.i <- signaling[ii]\n if (object@options$mode == \"single\") {\n net <- net0\n LR <- object@LR\n res <- extractEnrichedLR_internal(net, LR, DB, signaling = signaling.i, enriched.only = enriched.only, thresh = thresh)\n } else {\n geneLR.t <- c()\n pairLR.t <- c()\n for (i in 1:length(net0)) {\n net <- net0[[i]]\n LR <- object@LR[[i]]\n res.t <- extractEnrichedLR_internal(net, LR, DB, signaling = signaling.i, enriched.only = enriched.only, thresh = thresh)\n geneLR.t <- BiocGenerics::union(geneLR.t, as.character(res.t[[1]]))\n pairLR.t <- BiocGenerics::union(pairLR.t, as.character(res.t[[2]]))\n }\n res <- list(geneLR.t, pairLR.t)\n }\n geneLR.all <- c(geneLR.all, as.character(res[[1]]))\n pairLR.all <- c(pairLR.all, as.character(res[[2]]))\n }\n pairLR.all <- data.frame(interaction_name = pairLR.all, stringsAsFactors = FALSE)\n\n if (geneLR.return) {\n return(list(pairLR = pairLR.all, geneLR = geneLR.all))\n } else {\n return(pairLR.all)\n }\n}\n\n#' Identify all the significant interactions (L-R pairs) and related signaling genes for a given signaling pathway\n#'\n#' @param net,LR,DB object@net object@LR object@DB\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom dplyr select\n#'\n#' @return a list: list(geneLR, pairLR.name.use)\nextractEnrichedLR_internal <- function(net, LR, DB, signaling, enriched.only = TRUE, thresh = 0.05){\n pairLR <- searchPair(signaling = signaling, pairLR.use = LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.name.use = dplyr::select(DB$interaction[rownames(pairLR),],\"interaction_name\")\n if (enriched.only) {\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n if (length(pairLR.name.use) == 0) {\n message(paste0('There is no significant communication of ', signaling))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n }\n geneL <- unique(pairLR$ligand)\n geneR <- unique(pairLR$receptor)\n geneL <- extractGeneSubset(geneL, DB$complex, DB$geneInfo)\n geneR <- extractGeneSubset(geneR, DB$complex, DB$geneInfo)\n geneLR <- c(geneL, geneR)\n return(list(geneLR, pairLR.name.use))\n}\n\n\n#' Compute the maximum value of certain measures in the inferred cell-cell communication networks\n#'\n#' To better control the node size and edge weights of the inferred networks across different datasets,\n#' we compute the maximum number of cells per cell group and the maximum number of interactions (or interaction weights) across all datasets\n#'\n#' @param object.list List of CellChat objects\n#' @param slot.name the slot name of object that is used to compute the maximum value.\n#'\n#' When slot.name = \"idents\", 'attribute' should be \"idents\", which will compute the maximum number of cells per cell group across all datasets\n#'\n#' When slot.name = \"net\", 'attribute' can be either \"count\" or \"weight\", which will compute he maximum number of interactions (or interaction weights) across all datasets\n#'\n#' When slot.name = \"net\" or \"netP\", 'attribute' can be a single pathway name or a ligand-receptor pair name\n#'\n#' @param attribute the attribute to compute the maximum values. `attribute` should have the same length as `slot.name`.\n#'\n#' `attribute` can only be \"count\", \"weight\",\"count.merged\",\"weight.merged\" or a single pathway name or a ligand-receptor pair name\n#'\n#' @return A numeric vector\n#' @export\n#'\ngetMaxWeight <- function(object.list, slot.name = c(\"idents\", \"net\"), attribute = c(\"idents\", \"count\")) {\n weight <- c()\n for (i in 1:length(slot.name)) {\n if (slot.name[i] == \"idents\") {\n weight.all <- sapply(object.list, function (x) {max(as.numeric(table(slot(x, slot.name[i]))))})\n } else if ((slot.name[i] == \"net\") & (attribute[i] %in% c(\"count\", \"weight\",\"count.merged\",\"weight.merged\"))) {\n weight.all <- sapply(object.list, function (x) {max(slot(x, slot.name[i])[[attribute[i]]])})\n } else if (attribute[i] %in% c(object.list[[1]]@DB$interaction$pathway_name, object.list[[1]]@DB$interaction$interaction_name)) {\n weight.all <- sapply(object.list, function (x) {max(slot(x, slot.name[i])$prob[,,attribute[i]])})\n }\n weight[i] <- max(weight.all)\n }\n names(weight) <- attribute\n weight.max <- weight\n return(weight.max)\n}\n\n\n#' Compute the number of interactions/interaction strength between cell types based on their associated cell subpopulations\n#'\n#' @param object CellChat object\n#' @param group.merged a factor defining the group for merging different clusters/subpopulations\n#'\n#' @return An updated slot `net` by adding three elements:\n#'\n#' `count.merged`: the number of interactions between cell types (i.e., merged cell groups)\n#'\n#' `weight.merged`: interaction strength between cell types (i.e., merged cell groups)\n#'\n#' `group.merged` the defined group for merging different clusters/subpopulations\n#'\n#' @export\n#'\nmergeInteractions <- function(object, group.merged) {\n if (!is.factor(group.merged)) {\n group.merged <- factor(group.merged)\n }\n count <- object@net$count\n count.merged <- matrix(0, nrow = nlevels(group.merged), ncol = nlevels(group.merged))\n rownames(count.merged) <- levels(group.merged); colnames(count.merged) <- levels(group.merged);\n weight <- object@net$weight\n weight.merged <- count.merged\n dimnames(weight.merged) <- dimnames(count.merged)\n for (i in levels(group.merged)) {\n for (j in levels(group.merged)) {\n count.merged[i, j] <- sum(count[group.merged == i, group.merged == j])\n weight.merged[i, j] <- sum(weight[group.merged == i, group.merged == j])\n }\n }\n object@net$count.merged <- count.merged\n object@net$weight.merged <- weight.merged\n object@net$group.merged <- group.merged\n return(object)\n}\n\n\n#' Subset the inferred cell-cell communications of interest\n#'\n#' NB: If all arguments are NULL, it returns a data frame consisting of all the inferred cell-cell communications\n#'\n#' @param object CellChat object\n#' @param net Alternative input is a data frame with at least with three columns defining the cell-cell communication network (\"source\",\"target\",\"interaction_name\")\n#' @param slot.name the slot name of object: slot.name = \"net\" when extracting the inferred communications at the level of ligands/receptors; slot.name = \"netP\" when extracting the inferred communications at the level of signaling pathways\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param datasets select the inferred cell-cell communications from a particular `datasets` when inputing a data frame `net`\n#' @param ligand.pvalues,ligand.logFC,ligand.pct.1,ligand.pct.2 set threshold for ligand genes\n#'\n#' ligand.pvalues: threshold for pvalues in the differential expression gene analysis (DEG)\n#'\n#' ligand.logFC: threshold for logFoldChange in the DEG analysis; When ligand.logFC > 0, keep upgulated genes; otherwise, kepp downregulated genes\n#'\n#' ligand.pct.1: threshold for the percent of expressed genes in the defined 'positive' cell group. keep genes with percent greater than ligand.pct.1\n#'\n#' ligand.pct.2: threshold for the percent of expressed genes in the cells except for the defined 'positive' cell group\n#'\n#' @param receptor.pvalues,receptor.logFC,receptor.pct.1,receptor.pct.2 set threshold for receptor genes\n#' @importFrom dplyr select group_by summarize groups\n#' @importFrom stringr str_split\n#' @importFrom BiocGenerics as.data.frame\n#' @importFrom reshape2 melt\n#' @importFrom magrittr %>%\n#'\n#' @return If input object is created from a single dataset, a data frame of the inferred cell-cell communications of interest, consisting of source, target, interaction_name, pathway_name, prob and other information\n#'\n#' If input object is a merged object from multiple datasets, it will return a list and each element is a data frame for one dataset\n#'\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # access all the inferred cell-cell communications\n#' df.net <- subsetCommunication(cellchat)\n#'\n#' # access all the inferred cell-cell communications at the level of signaling pathways\n#' df.net <- subsetCommunication(cellchat, slot.name = \"netP\")\n#'\n#' # Subset to certain cells with sources.use and targets.use\n#' df.net <- subsetCommunication(cellchat, sources.use = c(1,2), targets.use = c(4,5))\n#'\n#' # Subset to certain signaling, e.g., WNT and TGFb\n#' df.net <- subsetCommunication(cellchat, signaling = c(\"WNT\", \"TGFb\"))\n#'}\n#'\nsubsetCommunication <- function(object = NULL, net = NULL, slot.name = \"net\",\n sources.use = NULL, targets.use = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n thresh = 0.05,\n datasets = NULL, ligand.pvalues = NULL, ligand.logFC = NULL, ligand.pct.1 = NULL, ligand.pct.2 = NULL,\n receptor.pvalues = NULL, receptor.logFC = NULL, receptor.pct.1 = NULL, receptor.pct.2 = NULL) {\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n message(\"slot.name is set to be 'netP' when pairLR.use contains signaling pathways\")\n slot.name = \"netP\"\n }\n }\n\n if (!is.null(pairLR.use) & !is.null(signaling)) {\n stop(\"Please do not assign values to 'signaling' when using 'pairLR.use'\")\n }\n\n if (object@options$mode == \"single\") {\n if (is.null(net)) {\n net <- slot(object, \"net\")\n }\n LR <- object@LR$LRsig\n cells.level <- levels(object@idents)\n df.net <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n } else if (object@options$mode == \"merged\") {\n if (is.null(net)) {\n net0 <- slot(object, \"net\")\n df.net <- vector(\"list\", length(net0))\n names(df.net) <- names(net0)\n for (i in 1:length(net0)) {\n net <- net0[[i]]\n LR <- object@LR[[i]]$LRsig\n cells.level <- levels(object@idents[[i]])\n\n df.net[[i]] <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n }\n } else {\n LR <- data.frame()\n for (i in 1:length(object@LR)) {\n LR <- rbind(LR, object@LR[[i]]$LRsig)\n }\n LR <- unique(LR)\n cells.level <- levels(object@idents$joint)\n df.net <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n }\n\n }\n\n return(df.net)\n\n}\n\n#' Subset the inferred cell-cell communications of interest\n#'\n#' NB: If all arguments are NULL, it returns a data frame consisting of all the inferred cell-cell communications\n#'\n#' @param net,LR,cells.level net is object@net or a data frame; LR: object@LR$LRsig; cells.level: levels(object@idents)\n#' @param slot.name the slot name of object: slot.name = \"net\" when extracting the inferred communications at the level of ligands/receptors; slot.name = \"netP\" when extracting the inferred communications at the level of signaling pathways\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param datasets select the inferred cell-cell communications from a particular `datasets` when inputing a data frame `net`\n#' @param ligand.pvalues,ligand.logFC,ligand.pct.1,ligand.pct.2 set threshold for ligand genes\n#'\n#' ligand.pvalues: threshold for pvalues in the differential expression gene analysis (DEG)\n#'\n#' ligand.logFC: threshold for logFoldChange in the DEG analysis; When ligand.logFC > 0, keep upgulated genes; otherwise, kepp downregulated genes\n#'\n#' ligand.pct.1: threshold for the percent of expressed genes in the defined 'positive' cell group. keep genes with percent greater than ligand.pct.1\n#'\n#' ligand.pct.2: threshold for the percent of expressed genes in the cells except for the defined 'positive' cell group\n#'\n#' @param receptor.pvalues,receptor.logFC,receptor.pct.1,receptor.pct.2 set threshold for receptor genes\n#' @importFrom dplyr select group_by summarize groups\n#' @importFrom stringr str_split\n#' @importFrom BiocGenerics as.data.frame\n#' @importFrom reshape2 melt\n#' @importFrom magrittr %>%\n#'\n#' @return A data frame of the inferred cell-cell communications of interest, consisting of source, target, interaction_name, pathway_name, prob and other information\n\nsubsetCommunication_internal <- function(net, LR, cells.level, slot.name = \"net\",\n sources.use = NULL, targets.use = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n thresh = 0.05,\n datasets = NULL, ligand.pvalues = NULL, ligand.logFC = NULL, ligand.pct.1 = NULL, ligand.pct.2 = NULL,\n receptor.pvalues = NULL, receptor.logFC = NULL, receptor.pct.1 = NULL, receptor.pct.2 = NULL) {\n if (!is.data.frame(net)) {\n prob <- net$prob\n pval <- net$pval\n prob[pval >= thresh] <- 0\n net <- reshape2::melt(prob, value.name = \"prob\")\n colnames(net)[1:3] <- c(\"source\",\"target\",\"interaction_name\")\n net.pval <- reshape2::melt(pval, value.name = \"pval\")\n net$pval <- net.pval$pval\n # remove the interactions with zero values\n net <- subset(net, prob > 0)\n }\n if (!(\"ligand\" %in% colnames(net))) {\n col.use <- intersect(c(\"interaction_name_2\", \"pathway_name\", \"ligand\", \"receptor\" ,\"annotation\",\"evidence\"), colnames(LR))\n pairLR <- dplyr::select(LR, col.use)\n idx <- match(net$interaction_name, rownames(pairLR))\n net <- cbind(net, pairLR[idx,])\n }\n\n if (!is.null(signaling)) {\n pairLR.use <- data.frame()\n for (i in 1:length(signaling)) {\n pairLR.use.i <- searchPair(signaling = signaling[i], pairLR.use = LR, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.use <- rbind(pairLR.use, pairLR.use.i)\n }\n }\n\n if (!is.null(pairLR.use)){\n net <- tryCatch({\n subset(net,interaction_name %in% pairLR.use$interaction_name)\n }, error = function(e) {\n subset(net, pathway_name %in% pairLR.use$pathway_name)\n })\n }\n\n if (!is.null(datasets)) {\n if (!(\"datasets\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before selecting 'datasets'\")\n }\n net <- net[net$datasets %in% datasets, , drop = FALSE]\n }\n if (!is.null(ligand.pvalues)){\n if (!(\"ligand.pvalues\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pvalues'\")\n }\n net <- net[net$ligand.pvalues <= ligand.pvalues, , drop = FALSE]\n }\n if (!is.null(ligand.logFC)){\n if (!(\"ligand.logFC\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.logFC'\")\n }\n if (ligand.logFC >= 0) {\n net <- net[net$ligand.logFC >= ligand.logFC, , drop = FALSE]\n } else {\n net <- net[net$ligand.logFC <= ligand.logFC, , drop = FALSE]\n }\n }\n if (!is.null(ligand.pct.1)){\n if (!(\"ligand.pct.1\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pct.1'\")\n }\n net <- net[net$ligand.pct.1 >= ligand.pct.1, , drop = FALSE]\n }\n if (!is.null(ligand.pct.2)){\n if (!(\"ligand.pct.2\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pct.2'\")\n }\n net <- net[net$ligand.pct.2 >= ligand.pct.2, , drop = FALSE]\n }\n\n if (!is.null(receptor.pvalues)){\n if (!(\"receptor.pvalues\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pvalues'\")\n }\n net <- net[net$receptor.pvalues <= receptor.pvalues, , drop = FALSE]\n }\n if (!is.null(receptor.logFC)){\n if (!(\"receptor.logFC\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.logFC'\")\n }\n if (receptor.logFC >= 0) {\n net <- net[net$receptor.logFC >= receptor.logFC, , drop = FALSE]\n } else {\n net <- net[net$receptor.logFC <= receptor.logFC, , drop = FALSE]\n }\n }\n if (!is.null(receptor.pct.1)){\n if (!(\"receptor.pct.1\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pct.1'\")\n }\n net <- net[net$receptor.pct.1 >= receptor.pct.1, , drop = FALSE]\n }\n if (!is.null(receptor.pct.2)){\n if (!(\"receptor.pct.2\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pct.2'\")\n }\n net <- net[net$receptor.pct.2 >= receptor.pct.2, , drop = FALSE]\n }\n\n net <- net[rowSums(is.na(net)) != ncol(net), , drop = FALSE]\n\n if (nrow(net) == 0) {\n stop(\"No significant signaling interactions are inferred based on the input!\")\n }\n\n\n if (slot.name == \"netP\") {\n col.use <- intersect(c(\"source\",\"target\",\"pathway_name\",\"prob\", \"pval\",\"annotation\"), colnames(net))\n net <- dplyr::select(net, col.use)\n net$source_target <- paste(net$source, net$target, sep = \"sourceTotarget\")\n # net$source_target_pathway <- paste(paste(net$source, net$target, sep = \"_\"), net$pathway_name, sep = \"_\")\n net.pval <- net %>% group_by(source_target, pathway_name) %>% summarize(pval = mean(pval), .groups = 'drop')\n net <- net %>% group_by(source_target, pathway_name) %>% summarize(prob = sum(prob), .groups = 'drop')\n a <- stringr::str_split(net$source_target, \"sourceTotarget\", simplify = T)\n net$source <- as.character(a[, 1])\n net$target <- as.character(a[, 2])\n net <- dplyr::select(net, -source_target)\n net$pval <- net.pval$pval\n }\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n }\n\n net <- BiocGenerics::as.data.frame(net, stringsAsFactors=FALSE)\n\n if (nrow(net) == 0) {\n warning(\"No significant signaling interactions are inferred!\")\n } else {\n rownames(net) <- 1:nrow(net)\n }\n\n if (slot.name == \"net\") {\n if ((\"ligand.logFC\" %in% colnames(net)) & (\"datasets\" %in% colnames(net))) {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\",\n \"datasets\",\"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\", \"ligand.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\", \"receptor.pvalues\"), colnames(net))\n net <- net[,col.use]\n } else if (\"ligand.logFC\" %in% colnames(net)) {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\",\n \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\", \"ligand.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\", \"receptor.pvalues\"), colnames(net))\n net <- net[,col.use]\n } else {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\"), colnames(net))\n net <- net[,col.use]\n }\n } else if (slot.name == \"netP\") {\n col.use <- intersect(c(\"source\", \"target\", \"pathway_name\", \"prob\", \"pval\"), colnames(net))\n net <- net[,col.use]\n }\n\n return(net)\n\n}\n\n\n\n\n\n\n\n\n\n\n#' Heatmap showing the centrality scores/importance of cell groups as senders, receivers, mediators and influencers in a single intercellular communication network\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the name of signaling networks\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param measure centrality measures to show\n#' @param measure.name the names of centrality measures to show\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation draw\n#' @importFrom stats setNames\n#'\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_signalingRole_network <- function(object, signaling, slot.name = \"netP\", measure = c(\"outdeg\",\"indeg\",\"flowbet\",\"info\"), measure.name = c(\"Sender\",\"Receiver\",\"Mediator\",\"Influencer\"),\n color.use = NULL, color.heatmap = \"BuGn\",\n width = 6.5, height = 1.4, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE) {\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n centr <- slot(object, slot.name)$centr[signaling]\n for(i in 1:length(centr)) {\n centr0 <- centr[[i]]\n mat <- matrix(unlist(centr0), ncol = length(centr0), byrow = FALSE)\n mat <- t(mat)\n rownames(mat) <- names(centr0); colnames(mat) <- names(centr0$outdeg)\n if (!is.null(measure)) {\n mat <- mat[measure,,drop = FALSE]\n if (!is.null(measure.name)) {\n if (length(measure.name) != length(measure)) {\n stop(\"The length of `measure.name` is not the same as that of `measure`! Please modify it! \\n\")\n }\n rownames(mat) <- measure.name\n }\n }\n mat <- sweep(mat, 1L, apply(mat, 1, max), '/', check.margin = FALSE)\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(colnames(mat)))\n }\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n\n df<- data.frame(group = colnames(mat)); rownames(df) <- colnames(mat)\n cell.cols.assigned <- setNames(color.use, unique(as.character(df$group)))\n col_annotation <- HeatmapAnnotation(df = df, col = list(group = cell.cols.assigned),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = \"Importance\",\n bottom_annotation = col_annotation,\n cluster_rows = cluster.rows,cluster_columns = cluster.cols,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = paste0(names(centr[i]), \" signaling pathway network\"),column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 45,\n heatmap_legend_param = list(title = \"Importance\", title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = c(round(min(mat, na.rm = T), digits = 1), round(max(mat, na.rm = T), digits = 1)),\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n draw(ht1)\n }\n}\n\n\n#' 2D visualization of dominant senders (sources) and receivers (targets)\n#'\n#' @description\n#' This scatter plot shows the dominant senders (sources) and receivers (targets) in a 2D space.\n#' x-axis and y-axis are respectively the total outgoing or incoming communication probability associated with each cell group.\n#' Dot size is proportional to the number of inferred links (both outgoing and incoming) associated with each cell group.\n#' Dot colors indicate different cell groups. Dot shapes indicate different categories of cell groups if `group`` is defined.\n#'\n#' @param object CellChat object\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param color.use defining the color for each cell group\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param group a vector to categorize the cell groups, e.g., categorize the cell groups into two major categories: immune cells and fibroblasts\n#' @param weight.MinMax the Minmum/maximum weight, which is useful to control the dot size when comparing multiple datasets\n#' @param point.shape point shape when group is not NULL\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size a range defining the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_signalingRole_scatter <- function(object, signaling = NULL, color.use = NULL, slot.name = \"netP\", group = NULL, weight.MinMax = NULL, dot.size = c(2, 6), point.shape = c(21, 22, 24, 23, 25, 8, 3), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\",xlabel = \"Outgoing interaction strength\", ylabel = \"Incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n centr <- slot(object, slot.name)$centr\n outgoing <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n incoming <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n dimnames(outgoing) <- list(levels(object@idents), names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n if (is.null(signaling)) {\n message(\"Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\")\n } else {\n message(\"Signaling role analysis on the cell-cell communication network from user's input\")\n signaling <- signaling[signaling %in% object@netP$pathways]\n if (length(signaling) == 0) {\n stop('There is no significant communication for the input signaling. All the significant signaling are shown in `object@netP$pathways`')\n }\n outgoing <- outgoing[ , signaling, drop = FALSE]\n incoming <- incoming[ , signaling, drop = FALSE]\n }\n outgoing.cells <- rowSums(outgoing)\n incoming.cells <- rowSums(incoming)\n\n num.link <- aggregateNet(object, signaling = signaling, return.object = FALSE, remove.isolate = FALSE)$count\n num.link <- rowSums(num.link) + colSums(num.link)-diag(num.link)\n df <- data.frame(x = outgoing.cells, y = incoming.cells, labels = names(incoming.cells),\n Count = num.link)\n df$labels <- factor(df$labels, levels = names(incoming.cells))\n if (!is.null(group)) {\n df$Group <- group\n }\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(object@idents))\n }\n if (!is.null(group)) {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Count, colour = labels, fill = labels, shape = Group))\n } else {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Count, colour = labels, fill = labels))\n }\n\n gg <- gg + CellChat_theme_opts() +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\"))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE) + guides(colour=\"none\")\n # gg <- gg + scale_colour_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(colour=\"none\")\n # gg <- gg + scale_shape_manual(values = point.shape[1:length(prob)])\n if (!is.null(group)) {\n gg <- gg + scale_shape_manual(values = point.shape[1:length(unique(df$Group))])\n }\n if (is.null(weight.MinMax)) {\n gg <- gg + scale_size_continuous(range = dot.size)\n } else {\n gg <- gg + scale_size_continuous(limits = weight.MinMax, range = dot.size)\n }\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = labels), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n\n#' 2D visualization of differential signaling roles (dominant senders (sources) or receivers (targets) ) of each cell group when comparing mutiple datasets\n#'\n#' @description\n#' This scatter plot shows the differential signaling roles (dominant senders (sources) or receivers (targets) in a 2D space.\n#'\n#' x-axis and y-axis are respectively the differential outgoing or incoming communication probability associated with each cell group.\n#' Dot colors indicate different cell groups. Dot shapes indicate different categories of cell groups if `group`` is defined.\n#'\n#' Positive values indicate the increase in the second dataset while negative values indicate the increase in the first dataset\n#'\n#' @param object A merged CellChat object of a list of CellChat objects\n#' @param color.use defining the color for each cell group\n#' @param comparison an index vector giving the two datasets for comparison\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param signaling.exclude signaling pathways to exclude\n#' @param idents.exclude cell groups to exclude. This is useful when zooming into the small changes\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param group a vector to categorize the cell groups, e.g., categorize the cell groups into two major categories: immune cells and fibroblasts\n#' @param point.shape point shape when group is not NULL\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., Outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., Incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_diff_signalingRole_scatter <- function(object, color.use = NULL, comparison = c(1,2), signaling = NULL, signaling.exclude = NULL, idents.exclude = NULL, slot.name = \"netP\", group = NULL, dot.size = 2.5, point.shape = c(21, 22, 24, 23, 25, 8, 3), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\", xlabel = \"Outgoing interaction strength\", ylabel = \"Incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (is.list(object)) {\n object <- mergeCellChat(object, add.names = names(object))\n }\n if (!is.list(object@net[[1]])) {\n stop(\"This function cannot be applied to a single cellchat object from one dataset!\")\n }\n\n dataset.name <- names(object@net)\n message(paste0(\"Visualizing differential outgoing and incoming signaling changes from \", dataset.name[comparison[1]], \" to \", dataset.name[comparison[2]]))\n title <- paste0(\"Signaling changes \", \" (\", dataset.name[comparison[1]], \" vs. \", dataset.name[comparison[2]], \")\")\n\n cell.levels <- levels(object@idents$joint)\n if (is.null(xlabel) | is.null(ylabel)) {\n xlabel = \"Differential outgoing interaction strength\"\n ylabel = \"Differential incoming interaction strength\"\n }\n if (is.null(signaling)) {\n signaling <- union(object@netP[[comparison[1]]]$pathways, object@netP[[comparison[2]]]$pathways)\n }\n if (!is.null(signaling.exclude)) {\n signaling <- setdiff(signaling, signaling.exclude)\n }\n\n mat.all.merged <- list()\n for (ii in 1:length(comparison)) {\n if (length(slot(object, slot.name)[[comparison[ii]]]$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores for each dataset seperately! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n\n centr <- slot(object, slot.name)[[comparison[ii]]]$centr\n outgoing <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n incoming <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n dimnames(outgoing) <- list(cell.levels, names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n mat.out <- t(outgoing)\n mat.in <- t(incoming)\n\n mat.all <- array(0, dim = c(length(signaling),ncol(mat.out),2))\n mat.t <-list(mat.out, mat.in)\n for (i in 1:length(comparison)) {\n mat = mat.t[[i]]\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n mat.all[,,i] = mat\n }\n dimnames(mat.all) <- list(dimnames(mat)[[1]], dimnames(mat)[[2]], c(\"outgoing\", \"incoming\"))\n mat.all.merged[[ii]] <- mat.all\n\n }\n\n mat.diff <- mat.all.merged[[2]] - mat.all.merged[[1]]\n\n outgoing.diff <- colSums(mat.diff[ , , 1])\n incoming.diff <- colSums(mat.diff[ , , 2])\n\n\n df <- data.frame(x = outgoing.diff, y = incoming.diff, labels = names(incoming.diff))\n df$labels <- factor(df$labels, levels = names(incoming.diff))\n if (!is.null(group)) {\n df$Group <- group\n }\n if (is.null(color.use)) {\n color.use <- scPalette(length(cell.levels))\n }\n if (!is.null(idents.exclude)) {\n df <- df[!(df$labels %in% idents.exclude), ]\n color.use <- color.use[!(cell.levels %in% idents.exclude)]\n df$labels = droplevels(df$labels, exclude = setdiff(levels(df$labels),unique(df$labels)))\n }\n\n if (!is.null(group)) {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = labels, fill = labels, shape = Group), size = dot.size)\n } else {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = labels, fill = labels), size = dot.size)\n }\n\n gg <- gg + CellChat_theme_opts() + theme_linedraw() +theme(panel.grid = element_blank()) +\n geom_hline(yintercept=0,linetype=\"dashed\", color = \"grey50\", size = 0.25) + geom_vline(xintercept=0, linetype=\"dashed\", color = \"grey50\",size = 0.25) +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\", hjust = 0.5))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE) + guides(colour=\"none\")\n if (!is.null(group)) {\n gg <- gg + scale_shape_manual(values = point.shape[1:length(unique(df$Group))])\n }\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = labels), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n\n#' 2D visualization of differential outgoing and incoming signaling associated with one cell group\n#'\n#' @description\n#' Positive values indicate the increase in the second dataset while negative values indicate the increase in the first dataset\n#'\n#'\n#' @param object A merged CellChat object of a list of CellChat objects\n#' @param idents.use the cell group names of interest. Should be one of `levels(object@idents$joint)`\n#' @param color.use a vector with three elements: the first is for coloring shared pathways, the second is for specific pathways in the first dataset, and the third is for specific pathways in the second dataset\n#' @param comparison an index vector giving the two datasets for comparison\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param signaling.label a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param signaling.exclude signaling pathways to exclude when plotting\n#' @param xlims,ylims set x-Axis and y-Axis Limits for zoom into the plot. e.g., xlims = c(-0.05, 0.1), ylims = c(-0.01, 0.035)\n#' @param slot.name the slot name of object\n#' @param point.shape point shape\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., Outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., Incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @importFrom plyr mapvalues\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_signalingChanges_scatter <- function(object, idents.use, color.use = c(\"grey10\", \"#F8766D\", \"#00BFC4\"), comparison = c(1,2), signaling = NULL, signaling.label = NULL, top.label = 1, signaling.exclude = NULL, xlims = NULL, ylims = NULL,slot.name = \"netP\", dot.size = 2.5, point.shape = c(21, 22, 24, 23), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\", xlabel = \"Differential outgoing interaction strength\", ylabel = \"Differential incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (is.list(object)) {\n object <- mergeCellChat(object, add.names = names(object))\n }\n if (is.list(object@net[[1]])) {\n dataset.name <- names(object@net)\n message(paste0(\"Visualizing differential outgoing and incoming signaling changes from \", dataset.name[comparison[1]], \" to \", dataset.name[comparison[2]]))\n title <- paste0(\"Signaling changes of \", idents.use, \" (\", dataset.name[comparison[1]], \" vs. \", dataset.name[comparison[2]], \")\")\n\n cell.levels <- levels(object@idents$joint)\n if (is.null(xlabel) | is.null(ylabel)) {\n xlabel = \"Differential outgoing interaction strength\"\n ylabel = \"Differential incoming interaction strength\"\n }\n\n } else {\n message(\"Visualizing outgoing and incoming signaling on a single object \\n\")\n title <- paste0(\"Signaling patterns of \", idents.use)\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n cell.levels <- levels(object@idents)\n }\n if (!(idents.use %in% cell.levels)) {\n stop(\"Please check the input cell group names!\")\n }\n if (is.null(signaling)) {\n signaling <- union(object@netP[[comparison[1]]]$pathways, object@netP[[comparison[2]]]$pathways)\n }\n if (!is.null(signaling.exclude)) {\n signaling <- setdiff(signaling, signaling.exclude)\n }\n mat.all.merged <- list()\n for (ii in 1:length(comparison)) {\n if (length(slot(object, slot.name)[[comparison[ii]]]$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores for each dataset seperately! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n centr <- slot(object, slot.name)[[comparison[ii]]]$centr\n outgoing <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n incoming <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n dimnames(outgoing) <- list(cell.levels, names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n mat.out <- t(outgoing)\n mat.in <- t(incoming)\n\n mat.all <- array(0, dim = c(length(signaling),ncol(mat.out),2))\n mat.t <-list(mat.out, mat.in)\n for (i in 1:length(comparison)) {\n mat = mat.t[[i]]\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n mat.all[,,i] = mat\n }\n dimnames(mat.all) <- list(dimnames(mat)[[1]], dimnames(mat)[[2]], c(\"outgoing\", \"incoming\"))\n mat.all.merged[[ii]] <- mat.all\n }\n mat.all.merged.use <- list(mat.all.merged[[1]][,idents.use,], mat.all.merged[[2]][,idents.use,])\n idx.specific <- mat.all.merged.use[[1]] * mat.all.merged.use[[2]]\n mat.sum <- mat.all.merged.use[[2]] + mat.all.merged.use[[1]]\n out.specific.signaling <- rownames(idx.specific)[(mat.sum[,1] != 0) & (idx.specific[,1] == 0)]\n in.specific.signaling <- rownames(idx.specific)[(mat.sum[,2] != 0) & (idx.specific[,2] == 0)]\n\n mat.diff <- mat.all.merged.use[[2]] - mat.all.merged.use[[1]]\n idx <- rowSums(mat.diff) != 0\n mat.diff <- mat.diff[idx, ]\n out.specific.signaling <- rownames(mat.diff) %in% out.specific.signaling\n in.specific.signaling <- rownames(mat.diff) %in% in.specific.signaling\n out.in.specific.signaling <- as.logical(out.specific.signaling * in.specific.signaling)\n specificity.out.in <- matrix(0, nrow = nrow(mat.diff), ncol = 1)\n specificity.out.in[out.in.specific.signaling] <- 2 # both outgoing and incoming specific to one condition\n specificity.out.in[setdiff(which(out.specific.signaling), which(out.in.specific.signaling))] <- 1 # only outgoing specific to one condition\n specificity.out.in[setdiff(which(in.specific.signaling), which(out.in.specific.signaling))] <- -1 # only incoming specific to one condition\n\n\n df <- as.data.frame(mat.diff)\n df$specificity.out.in <- specificity.out.in\n df$specificity = 0\n df$specificity[(specificity.out.in != 0) & (rowSums(mat.diff >= 0) ==2)] = 1 # specific to dataset 2\n df$specificity[(specificity.out.in != 0) & (rowSums(mat.diff <= 0) ==2)] = -1 # specific to dataset 1\n\n # change number to char\n out.in.category <- c(\"Shared\", \"Incoming specific\", \"Outgoing specific\", \"Incoming & Outgoing specific\")\n specificity.category <- c(\"Shared\", paste0(dataset.name[comparison[1]],\" specific\"), paste0(dataset.name[comparison[2]],\" specific\"))\n df$specificity.out.in <- plyr::mapvalues(df$specificity.out.in, from = c(0,-1,1,2),to = out.in.category)\n df$specificity.out.in <- factor(df$specificity.out.in, levels = out.in.category)\n df$specificity <- plyr::mapvalues(df$specificity, from = c(0,-1,1),to = specificity.category)\n df$specificity <- factor(df$specificity, levels = specificity.category)\n\n point.shape.use <- point.shape[out.in.category %in% unique(df$specificity.out.in)]\n df$specificity.out.in = droplevels(df$specificity.out.in, exclude = setdiff(out.in.category,unique(df$specificity.out.in)))\n\n color.use <- color.use[specificity.category %in% unique(df$specificity)]\n df$specificity = droplevels(df$specificity, exclude = setdiff(specificity.category,unique(df$specificity)))\n\n df$labels <- rownames(df)\n gg <- ggplot(data = df, aes(outgoing, incoming)) +\n geom_point(aes(colour = specificity, fill = specificity, shape = specificity.out.in), size = dot.size)\n gg <- gg + theme_linedraw() +theme(panel.grid = element_blank()) +\n geom_hline(yintercept=0,linetype=\"dashed\", color = \"grey50\", size = 0.25) + geom_vline(xintercept=0, linetype=\"dashed\", color = \"grey50\",size = 0.25) +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, hjust = 0.5, face=\"plain\"))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n gg <- gg + scale_shape_manual(values = point.shape.use)\n gg <- gg + theme(legend.title = element_blank())\n if (!is.null(xlims)) {\n gg <- gg + xlim(xlims)\n }\n if (!is.null(ylims)) {\n gg <- gg + ylim(ylims)\n }\n\n if (do.label) {\n if (is.null(signaling.label)) {\n thresh <- stats::quantile(abs(as.matrix(df[,1:2])), probs = 1-top.label)\n idx = abs(df[,1]) > thresh | abs(df[,2]) > thresh\n data.label <- df[idx,]\n } else {\n data.label <- df[rownames(df) %in% signaling.label, ]\n }\n\n gg <- gg + ggrepel::geom_text_repel(data = data.label, mapping = aes(label = labels, colour = specificity), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n#' Heatmap showing the contribution of signals (signaling pathways or ligand-receptor pairs) to cell groups in terms of outgoing or incoming signaling\n#'\n#' In this heatmap, colobar represents the relative signaling strength of a signaling pathway across cell groups (NB: values are row-scaled).\n#' The top colored bar plot shows the total signaling strength of a cell group by summarizing all signaling pathways displayed in the heatmap.\n#' The right grey bar plot shows the total signaling strength of a signaling pathway by summarizing all cell groups displayed in the heatmap.\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the names of signaling networks of interest\n#' @param pattern this parameter can be set as \"outgoing\", \"incoming\" or \"all\". When pattern = \"all\", CellChat aggregates the outgoing and incoming signaling strength together;\n#' @param slot.name the slot name of object that is used to examine the signaling patterns at the level of signaling pathways (slot.name = \"netP\") or ligand-receptor pairs (slot.name = \"net\");\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param title title name\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation anno_barplot rowAnnotation\n#' @importFrom stats setNames\n#'\n#' @return\n#' @export\n#'\nnetAnalysis_signalingRole_heatmap <- function(object, signaling = NULL, pattern = c(\"outgoing\", \"incoming\",\"all\"), slot.name = \"netP\",\n color.use = NULL, color.heatmap = \"BuGn\",\n title = NULL, width = 10, height = 8, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE){\n pattern <- match.arg(pattern)\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n centr <- slot(object, slot.name)$centr\n outgoing <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n incoming <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n dimnames(outgoing) <- list(levels(object@idents), names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]]$outdeg\n incoming[,i] <- centr[[i]]$indeg\n }\n if (pattern == \"outgoing\") {\n mat <- t(outgoing)\n legend.name <- \"Outgoing\"\n } else if (pattern == \"incoming\") {\n mat <- t(incoming)\n legend.name <- \"Incoming\"\n } else if (pattern == \"all\") {\n mat <- t(outgoing+ incoming)\n legend.name <- \"Overall\"\n }\n if (is.null(title)) {\n title <- paste0(legend.name, \" signaling patterns\")\n } else {\n title <- paste0(paste0(legend.name, \" signaling patterns\"), \" - \",title)\n }\n\n if (!is.null(signaling)) {\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n }\n mat.ori <- mat\n mat <- sweep(mat, 1L, apply(mat, 1, max), '/', check.margin = FALSE)\n mat[mat == 0] <- NA\n\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(colnames(mat)))\n }\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n\n df<- data.frame(group = colnames(mat)); rownames(df) <- colnames(mat)\n names(color.use) <- colnames(mat)\n col_annotation <- HeatmapAnnotation(df = df, col = list(group = color.use),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n ha2 = HeatmapAnnotation(Strength = anno_barplot(colSums(mat.ori), border = FALSE,gp = gpar(fill = color.use, col=color.use)), show_annotation_name = FALSE)\n\n pSum <- rowSums(mat.ori)\n pSum.original <- pSum\n pSum <- -1/log(pSum)\n pSum[is.na(pSum)] <- 0\n idx1 <- which(is.infinite(pSum) | pSum < 0)\n if (length(idx1) > 0) {\n values.assign <- seq(max(pSum)*1.1, max(pSum)*1.5, length.out = length(idx1))\n position <- sort(pSum.original[idx1], index.return = TRUE)$ix\n pSum[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n\n ha1 = rowAnnotation(Strength = anno_barplot(pSum, border = FALSE), show_annotation_name = FALSE)\n\n if (min(mat, na.rm = T) == max(mat, na.rm = T)) {\n legend.break <- max(mat, na.rm = T)\n } else {\n legend.break <- c(round(min(mat, na.rm = T), digits = 1), round(max(mat, na.rm = T), digits = 1))\n }\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = \"Relative strength\",\n bottom_annotation = col_annotation, top_annotation = ha2, right_annotation = ha1,\n cluster_rows = cluster.rows,cluster_columns = cluster.rows,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = title,column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 90,\n heatmap_legend_param = list(title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = legend.break,\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n # draw(ht1)\n return(ht1)\n}\n\n\n\n#' Mapping the differential expressed genes (DEG) information onto the inferred cell-cell communications\n#'\n#' This function returns a data frame consisting of all the inferred cell-cell communications with mapped DEG information\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for extracting the DEG in `object@var.features[[features.name]]`\n#' @param variable.all variable.all = TRUE will compute the c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\") for a ligand/receptor complex using the mean value of its all subunits, that is requiring all subunits of the complex are differential expressed;\n#' variable.all = FALSE will compute the minimum value of \"pvalues\" and maximum value of c(\"logFC\", \"pct.1\", \"pct.2\") among the subunits, that is only requiring that any one of the subunits of the complex is differential expressed.\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom dplyr select\n#'\n#' @return a data frame of the inferred cell-cell communications, consisting of source, target, interaction_name, pathway_name, prob and other CellChatDB information as well as DEG information\n#'\n#' @export\n#'\nnetMappingDEG <- function(object, features.name, variable.all = TRUE, thresh = 0.05) {\n features.name <- paste0(features.name, \".info\")\n if (!(features.name %in% names(object@var.features))) {\n stop(\"The input features.name does not exist in `names(object@var.features)`. Please first run `identifyOverExpressedGenes`! \")\n }\n DEG <- object@var.features[[features.name]]\n geneInfo <- object@DB$geneInfo\n complex_input <- object@DB$complex\n\n df.net <- subsetCommunication(object, thresh = thresh)\n if (!is.data.frame(df.net)) {\n net <- data.frame()\n for (ii in 1:length(df.net)) {\n df.net[[ii]]$datasets <- names(df.net)[ii]\n net <- rbind(net, df.net[[ii]])\n }\n } else {\n net <- df.net\n }\n net$source.ligand <- paste0(net$source,\".\", net$ligand)\n net$target.receptor <- paste0(net$target,\".\", net$receptor)\n\n DEG$clusters.features <- paste0(DEG$clusters,\".\", DEG$features)\n\n net <- cbind(net, data.frame(ligand.pvalues = NA, ligand.logFC = NA, ligand.pct.1 = NA, ligand.pct.2 = NA,\n receptor.pvalues = NA, receptor.logFC = NA, receptor.pct.1 = NA, receptor.pct.2 = NA))\n # compute values for ligand\n idx1.ligand <- net$ligand %in% geneInfo$Symbol\n idx2.ligand <- which((net$ligand %in% geneInfo$Symbol) == \"FALSE\")\n idx.pos <- match(net$source.ligand, DEG$clusters.features)\n idx1.source.ligand <- which(!is.na(idx.pos))\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n idx2.source.ligand <- which(idx1.ligand & !(net$source.ligand %in% DEG$clusters.features))\n net[idx1.source.ligand, c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")] <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n\n if (length(idx2.ligand) > 0) {\n net.temp.all <- data.frame()\n for (i in 1:length(idx2.ligand)) {\n complex <- net$ligand[idx2.ligand[i]]\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n\n source.ligand.complex <- paste0(net$source[idx2.ligand[i]],\".\", complexsubunitsV)\n idx.pos <- match(source.ligand.complex, DEG$clusters.features)\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n if (length(idx1.clusters.features) > 0) {\n net.temp <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\"), drop = FALSE]\n if (variable.all == TRUE) {\n net.temp <- colMeans(net.temp, na.rm = TRUE)\n } else {\n net.temp <- c(min(net.temp$pvalues), apply(net.temp[, 2:ncol(net.temp), drop = FALSE], 2, function(x) max(x, na.rm = TRUE)))\n names(net.temp)[1] <- \"pvalues\"\n }\n net.temp <- as.data.frame(t(net.temp))\n colnames(net.temp) <- c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")\n } else {\n net.temp <- data.frame(ligand.pvalues = NA, ligand.logFC = NA, ligand.pct.1 = NA, ligand.pct.2 = NA)\n }\n net.temp.all <- rbind(net.temp.all, net.temp)\n }\n net[idx2.ligand, c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")] <- net.temp.all\n }\n\n # compute values for receptor\n idx1.receptor <- net$receptor %in% geneInfo$Symbol\n idx2.receptor <- which((net$receptor %in% geneInfo$Symbol) == \"FALSE\")\n idx.pos <- match(net$target.receptor, DEG$clusters.features)\n idx1.target.receptor <- which(!is.na(idx.pos))\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n net[idx1.target.receptor, c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")] <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n\n if (length(idx2.receptor) > 0) {\n net.temp.all <- data.frame()\n for (i in 1:length(idx2.receptor)) {\n complex <- net$receptor[idx2.receptor[i]]\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n\n target.receptor.complex <- paste0(net$target[idx2.receptor[i]],\".\", complexsubunitsV)\n idx.pos <- match(target.receptor.complex, DEG$clusters.features)\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n if (length(idx1.clusters.features) > 0) {\n net.temp <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n if (variable.all == TRUE) {\n net.temp <- colMeans(net.temp, na.rm = TRUE)\n } else {\n net.temp <- c(min(net.temp$pvalues, na.rm = TRUE), apply(net.temp[, 2:ncol(net.temp), drop = FALSE], 2, function(x) max(x, na.rm = TRUE)))\n names(net.temp)[1] <- \"pvalues\"\n }\n net.temp <- as.data.frame(t(net.temp))\n colnames(net.temp) <- c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")\n } else {\n net.temp <- data.frame(receptor.pvalues = NA, receptor.logFC = NA, receptor.pct.1 = NA, receptor.pct.2 = NA)\n }\n net.temp.all <- rbind(net.temp.all, net.temp)\n }\n net[idx2.receptor, c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")] <- net.temp.all\n }\n # net <- dplyr::select[net, -c(\"source.ligand\", \"target.receptor\")]\n return(net)\n}\n\n\n#' Compute and visualize the enrichment score of ligand-receptor pairs in one condition compared to another condition\n#'\n#' @param df a dataframe\n#' @param measure compute the enrichment score in terms of \"ligand\", \"signaling\",or \"LR-pair\"\n#' @param color.use defining the color for each group of datasets\n#' @param color.name the color names in RColorBrewer::brewer.pal\n#' @param n.color the number of colors\n#' @param species define the species as one of the c('mouse','human') to extract the CellChatDB; For other species, users need to provide a ligand-receptor database `db`\n#' @param db a customized ligand-receptor database `db`\n#' @param variable.both variable.both = TRUE will require that both ligand and receptor from one pair are over-expressed;\n#' variable.both = FALSE will only require that either ligand or receptor from one pair is over-expressed.\n#' @param scale A vector of length 2 indicating the range of the size of the words.\n#' @param min.freq words with frequency below min.freq will not be plotted\n#' @param max.words Maximum number of words to be plotted. least frequent terms dropped\n#' @param random.order plot words in random order. If false, they will be plotted in decreasing frequency\n#' @param rot.per \tproportion words with 90 degree rotation\n#' @param return.data whether return the data frame for plotting wordcloud\n#' @param seed set a seed\n#' @param ... Other parameters passing to wordcloud::wordcloud\n#' @import dplyr\n#' @return A ggplot object\n#' @export\n#'\ncomputeEnrichmentScore <- function(df, measure = c(\"ligand\", \"signaling\",\"LR-pair\"), variable.both = TRUE, species = c('mouse','human'), db = NULL, color.use = NULL, color.name = \"Dark2\", n.color = 8,\n scale=c(4,.8), min.freq = 0, max.words = 200, random.order = FALSE, rot.per = 0,return.data = FALSE,seed = 1,...) {\n measure <- match.arg(measure)\n species <- match.arg(species)\n LRpairs <- as.character(unique(df$interaction_name))\n ES <- vector(length = length(LRpairs))\n for (i in 1:length(LRpairs)) {\n df.i <- subset(df, interaction_name == LRpairs[i])\n idx = which(rowSums(is.na(df.i)) > 0)\n if (variable.both & (length(idx) > 0)) {\n df.i <- df.i[-idx, ,drop = FALSE]\n }\n ES[i] = mean(abs(df.i$ligand.logFC) * abs(df.i$receptor.logFC) *abs(df.i$ligand.pct.2-df.i$ligand.pct.1)*abs(df.i$receptor.pct.2-df.i$receptor.pct.1), na.rm = TRUE)\n }\n idx.na <- which(is.na(ES))\n if (length(idx.na) > 0) {\n ES <- ES[-idx.na]\n LRpairs <- LRpairs[-idx.na]\n }\n\n if (length(ES) == 0) {\n stop(\"No enriched signaling! Please adjust the parameters for selecting differential expressed signaling!\")\n }\n if (is.null(db)) {\n if (species == \"mouse\") {\n CellChatDB <- CellChatDB.mouse\n } else if (species == 'human') {\n CellChatDB <- CellChatDB.human\n } else {\n stop(\"Only mouse and human are supported currently. Please provide a `db` instead! \")\n }\n } else {\n CellChatDB <- db\n }\n df.es <- CellChatDB$interaction[LRpairs, c(\"ligand\",'receptor','pathway_name')]\n df.es$score <- ES\n # summarize the enrichment score\n df.es.ensemble <- df.es %>% group_by(ligand) %>% summarize(total = sum(score)) # avg = mean(score),\n\n set.seed(seed)\n if (is.null(color.use)) {\n color.use <- RColorBrewer::brewer.pal(n.color, color.name)\n }\n\n wordcloud::wordcloud(words = df.es.ensemble$ligand, freq = df.es.ensemble$total, min.freq = min.freq, max.words = max.words,scale=scale,\n random.order = random.order, rot.per = rot.per, colors = color.use,...)\n if (return.data) {\n return(df.es.ensemble)\n }\n}\n\n\n#' Find the enriched signaling according to the genes (e.g.DEGs) and cell groups of interest\n#'\n#' @param object CellChat object\n#' @param features a vector giving the genes of interest\n#' @param idents a vector giving the names of cell groups of interest. If idents = NULL, it returns signaling according to the input features.\n#' @param pattern \"both\", \"outgoing\" or \"incoming\"\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @return a dataframe of the cell-cell communication associated with the input features.\n#' @export\n#' @examples\n#'\\dontrun{\n#' # find all the significant outgoing signaling according to the features and cell groups of interest\n#' df <- findEnrichedSignaling(object, features = c(\"CCL19\", \"CXCL12\"), idents = c(\"Inflam. FIB\", \"COL11A1+ FIB\"), pattern =\"outgoing\")\n#'}\nfindEnrichedSignaling <- function(object, features, idents = NULL, pattern = c(\"both\",\"outgoing\",\"incoming\"), thresh = 0.05) {\n pattern <- match.arg(pattern)\n df.net <- subsetCommunication(object, thresh = thresh)\n if (!is.null(idents)) {\n if (pattern == \"both\") {\n idx <- (df.net$source %in% idents) | (df.net$target %in% idents)\n } else if (pattern == \"outgoing\") {\n idx <- df.net$source %in% idents\n } else if (pattern == \"incoming\"){\n idx <- df.net$target %in% idents\n }\n idx.feature <- (df.net$ligand %in% features) | (df.net$receptor %in% features)\n df.net.sub <- df.net[idx & idx.feature, , drop = FALSE]\n } else {\n if (pattern == \"both\") {\n idx.feature <- (df.net$ligand %in% features) | (df.net$receptor %in% features)\n } else if (pattern == \"outgoing\") {\n idx.feature <- (df.net$ligand %in% features)\n } else if (pattern == \"incoming\"){\n idx.feature <- (df.net$receptor %in% features)\n }\n df.net.sub <- df.net[idx.feature, , drop = FALSE]\n }\n return(df.net.sub)\n}\n\n"], ["/CellChat/R/utilities.R", "#' Normalize data using a scaling factor\n#'\n#' @param data.raw input raw data\n#' @param scale.factor the scaling factor used for each cell\n#' @param do.log whether to do log transformation with pseudocount 1\n#' @param do.sparse whether to use sparse format\n#' @export\n#'\nnormalizeData <- function(data.raw, scale.factor = 10000, do.log = TRUE, do.sparse = TRUE) {\n # Scale counts within a sample\n library.size <- Matrix::colSums(data.raw)\n #scale.factor <- median(library.size)\n expr <- Matrix::t(Matrix::t(data.raw) / library.size) * scale.factor\n if (do.log) {\n data.norm <-log1p(expr)\n }\n if (do.sparse) {\n data.input <- as(data.norm, \"dgCMatrix\")\n }\n return(data.norm)\n}\n\n\n#' Scale the data\n#'\n#' @param data.use input data\n#' @param do.center whether center the values\n#' @export\n#'\nscaleData <- function(data.use, do.center = T) {\n data.use <- Matrix::t(scale(Matrix::t(data.use), center = do.center, scale = TRUE))\n return(data.use)\n}\n\n\n#' Scale a data matrix\n#'\n#' @param x data matrix\n#' @param scale the method to scale the data\n#' @param na.rm whether remove na\n#' @importFrom Matrix rowMeans colMeans rowSums colSums\n#' @return\n#' @export\n#'\n#' @examples\nscaleMat <- function(x, scale, na.rm=TRUE){\n\n av <- c(\"none\", \"row\", \"column\", 'r1', 'c1')\n i <- pmatch(scale, av)\n if(is.na(i) )\n stop(\"scale argument shoud take values: 'none', 'row' or 'column'\")\n scale <- av[i]\n\n switch(scale, none = x\n , row = {\n x <- sweep(x, 1L, rowMeans(x, na.rm = na.rm), '-',check.margin = FALSE)\n sx <- apply(x, 1L, sd, na.rm = na.rm)\n sweep(x, 1L, sx, \"/\", check.margin = FALSE)\n }\n , column = {\n x <- sweep(x, 2L, colMeans(x, na.rm = na.rm), '-',check.margin = FALSE)\n sx <- apply(x, 2L, sd, na.rm = na.rm)\n sweep(x, 2L, sx, \"/\", check.margin = FALSE)\n }\n , r1 = sweep(x, 1L, rowSums(x, na.rm = na.rm), '/', check.margin = FALSE)\n , c1 = sweep(x, 2L, colSums(x, na.rm = na.rm), '/', check.margin = FALSE)\n )\n}\n\n#' Downsampling single cell data using geometric sketching algorithm\n#'\n#' USERs need to install the python package `pip install geosketch` (https://github.com/brianhie/geosketch)\n#'\n#' @param object A data matrix (should have row names; samples in rows, features in columns) or a Seurat object.\n#'\n#' When object is a PCA or UMAP space, please set `do.PCA = FALSE`\n#'\n#' When object is a data matrix (cells in rows and genes in columns), it is better to use the highly variable genes. PCA will be done on this input data matrix.\n#' @param percent the percent of data to sketch\n#' @param idents A vector of identity classes to keep for sketching\n#' @param do.PCA whether doing PCA on the input data\n#' @param dimPC the number of components to use\n#' @importFrom reticulate import\n#' @return A vector of cell names to use for downsampling\n#' @export\n#'\nsketchData <- function(object, percent, idents = NULL, do.PCA = TRUE, dimPC = 30) {\n # pip install geosketch\n geosketch <- reticulate::import('geosketch')\n if (is(object,\"Seurat\")) {\n sketch.size <- as.integer(percent*ncol(object))\n if (!is.null(idents)) {\n object <- subset(object, idents = idents)\n }\n object <- object %>% #Seurat::NormalizeData(verbose = FALSE) %>%\n FindVariableFeatures(selection.method = \"vst\", nfeatures = 2000) %>%\n RunPCA(pc.genes = object@var.genes, npcs = dimPC, verbose = FALSE)\n\n X.pcs <- object@reductions$pca@cell.embeddings\n cells.all <- Cells(object)\n\n } else {\n # Get top PCs\n if (do.PCA) {\n X.pcs <- runPCA(object, dimPC = dimPC)\n } else {\n X.pcs <- object\n }\n\n # Sketch percent of data.\n sketch.size <- as.integer(percent*nrow(X))\n cells.all <- rownames(object)\n }\n sketch.index <- geosketch$gs(X.pcs, sketch.size)\n sketch.index <- unlist(sketch.index) + 1\n sketch.cells <- cells.all[sketch.index]\n return(sketch.cells)\n}\n\n\n#' Add the cell information into meta slot\n#'\n#' @param object CellChat object\n#' @param meta cell information to be added\n#' @param meta.name the name of column to be assigned\n#'\n#' @return\n#' @export\n#'\n#' @examples\naddMeta <- function(object, meta, meta.name = NULL) {\n if (is.null(x = meta.name) && is.atomic(x = meta)) {\n stop(\"'meta.name' must be provided for atomic meta types (eg. vectors)\")\n }\n if (inherits(x = meta, what = c(\"matrix\", \"Matrix\"))) {\n meta <- as.data.frame(x = meta)\n }\n\n if (is.null(x = meta.name)) {\n meta.name <- names(meta)\n } else {\n names(meta) <- meta.name\n }\n object@meta <- meta\n return(object)\n}\n\n\n#' Set the default identity of cells\n#' @param object CellChat object\n#' @param ident.use the name of the variable in object.meta;\n#' @param levels set the levels of factor\n#' @param display.warning whether display the warning message\n#' @return\n#' @export\n#'\n#' @examples\nsetIdent <- function(object, ident.use = NULL, levels = NULL, display.warning = TRUE){\n if (!is.null(ident.use)) {\n object@idents <- as.factor(object@meta[[ident.use]])\n }\n\n if (!is.null(levels)) {\n object@idents <- factor(object@idents, levels = levels)\n }\n if (\"0\" %in% as.character(object@idents)) {\n stop(\"Cell labels cannot contain `0`! \")\n }\n if (length(object@net) > 0) {\n if (all(dimnames(object@net$prob)[[1]] %in% levels(object@idents) )) {\n message(\"Reorder cell groups! \")\n cat(\"The cell group order before reordering is \", dimnames(object@net$prob)[[1]],'\\n')\n # idx <- match(dimnames(object@net$prob)[[1]], levels(object@idents))\n idx <- match(levels(object@idents), dimnames(object@net$prob)[[1]])\n object@net$prob <- object@net$prob[idx, , ]\n object@net$prob <- object@net$prob[, idx, ]\n object@net$pval <- object@net$pval[idx, , ]\n object@net$pval <- object@net$pval[, idx, ]\n cat(\"The cell group order after reordering is \", dimnames(object@net$prob)[[1]],'\\n')\n } else {\n message(\"Rename cell groups but do not change the order! \")\n cat(\"The cell group order before renaming is \", dimnames(object@net$prob)[[1]],'\\n')\n dimnames(object@net$prob) <- list(levels(object@idents), levels(object@idents), dimnames(object@net$prob)[[3]])\n dimnames(object@net$pval) <- dimnames(object@net$prob)\n cat(\"The cell group order after renaming is \", dimnames(object@net$prob)[[1]],'\\n')\n }\n if (display.warning) {\n warning(\"All the calculations after `computeCommunProb` should be re-run!!\n These include but not limited to `computeCommunProbPathway`,`aggregateNet`, and `netAnalysis_computeCentrality`.\")\n }\n\n\n }\n return(object)\n}\n\n\n#' Add a reduced space of the data into CellChat object\n#'\n#' @param object CellChat object from a single dataset\n#' @param dr A data frame (rows are cells with rownames) consisting of a low-dimensional space for visualization\n#' @param dr.name A char name of the reduction method for the input `dr`\n#' @param seu.obj A Seurat object with the reduced space of the data\n#' @param dr.use A char name of the reduction method to use when taking `seu.obj` as input. By default, all reduced space in `seu.obj` will be added in `object@dr`\n#' @param force.add Whether to force to add a new reduced space when a reduced space exists in `object@dr`\n#' @return\n#' @export\n#' @examples\n#' \\dontrun{\n#' cellChat <- addReduction(object = cellchat, dr = cell.embeddings, dr.name = \"umap\")\n#'\n#' cellChat <- addReduction(object = cellchat, seu.obj = seu.obj)\n#' }\naddReduction <- function(object, dr = NULL, dr.name = NULL, seu.obj = NULL, dr.use = NULL, force.add = FALSE) {\n if (length(names(object@dr)) > 0) {\n if (!force.add) {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please set `force.add = TRUE` if intending to add a new reduced space. \\n\"))\n }\n }\n if (!is.null(dr)) {\n if (is.null(dr.name)) {\n stop(\"When inputing `dr`, please also provide the `dr.name`! \\n\")\n }\n dr <- as.data.frame(dr)\n if (all(colnames(object@data.signaling) %in% rownames(dr))) {\n object@dr[[dr.name]] <- dr[colnames(object@data.signaling), ]\n } else {\n stop(\"Some cell barcodes in the CellChat object are not the rownames of the input `dr`. Please check the input `dr` and make sure it contains all cells in the CellChat analysis. \\n\")\n }\n } else if(!is.null(seu.obj)) {\n if (!is(seu.obj,\"Seurat\")) {\n stop(\"The input `seu.obj` can be only the Seurat object. \\n\")\n }\n reductions <- names(seu.obj@reductions)\n if (length(reductions) == 0) {\n stop(\"The input `seu.obj` does not contain any low-dimensional space. Please generate a low-dimensional space for visualization. \\n\")\n }\n if (!is.null(dr.use)) {\n reductions <- intersect(reductions, dr.use)\n }\n if (length(reductions) == 0) {\n stop(\"The input `dr.use` is not in the reduced space in `seu.obj`. \\n\")\n }\n for (i in 1:length(reductions)) {\n dr.name <- reductions[i]\n dr = seu.obj@reductions[[dr.name]]@cell.embeddings\n if (all(colnames(object@data.signaling) %in% rownames(dr))) {\n cat(paste0(dr.name, \" is now added in `object@dr` as a low-dimensional space. \\n\"))\n object@dr[[dr.name]] <- dr[colnames(object@data.signaling), ]\n } else {\n stop(\"Some cell barcodes in the CellChat object are not in the input `seu.obj`. Please check the input `seu.obj` and make sure it contains all cells in the CellChat analysis. \\n\")\n }\n }\n } else {\n stop(\"Please input either `dr` or `seu.obj`! \\n\")\n }\n return(object)\n}\n\n\n#' Update and re-order the cell group names after running `computeCommunProb`\n#'\n#' @param object CellChat object\n#' @param old.cluster.name A vector defining old cell group labels in `object@idents`; Default = NULL, which will use `levels(object@idents)`\n#' @param new.cluster.name A vector defining new cell group labels to rename\n#' @param new.order reset order of cell group labels\n#' @param new.cluster.metaname assign a name of the new labels, which will be the column name of new labels in `object@meta`\n#' @return An updated CellChat object\n#' @export\n#'\nupdateClusterLabels <- function(object, old.cluster.name = NULL, new.cluster.name = NULL, new.order = NULL, new.cluster.metaname = \"new.labels\") {\n if (is.null(old.cluster.name)) {\n old.cluster.name <- levels(object@idents)\n }\n if (new.cluster.metaname %in% colnames(object@meta)) {\n stop(\"Please define another `new.cluster.metaname` as it exists in `colnames(object@meta)`!\")\n }\n if (!is.null(new.cluster.name)) {\n labels.new <- plyr::mapvalues(object@idents, from = old.cluster.name, to = new.cluster.name)\n object@meta[[new.cluster.metaname]] <- labels.new\n object <- setIdent(object, ident.use = new.cluster.metaname, display.warning = FALSE)\n } else {\n new.cluster.metaname <- NULL\n cat(\"Only reorder cell groups but do not rename cell groups!\")\n }\n\n if (!is.null(new.order)) {\n object <- setIdent(object, ident.use = new.cluster.metaname, levels = new.order, display.warning = FALSE)\n }\n message(\"We now re-run computeCommunProbPathway`,`aggregateNet`, and `netAnalysis_computeCentrality`...\")\n object <- computeCommunProbPathway(object)\n ## calculate the aggregated network by counting the number of links or summarizing the communication probability\n object <- aggregateNet(object)\n # network importance analysis\n object <-netAnalysis_computeCentrality(object, slot.name = \"netP\")\n return(object)\n}\n\n\n\n\n\n#' Subset the expression data of signaling genes for saving computation cost\n#'\n#' @param object CellChat object\n#' @param features default = NULL: subset the expression data of signaling genes in CellChatDB.use\n#'\n#' @return An updated CellChat object by assigning a subset of the data into the slot `data.signaling`\n#' @export\n#'\nsubsetData <- function(object, features = NULL) {\n interaction_input <- object@DB$interaction\n if (object@options$datatype != \"RNA\") {\n if (\"annotation\" %in% colnames(interaction_input) == FALSE) {\n warning(\"A column named `annotation` is required in `object@DB$interaction` when running CellChat on spatial transcriptomics! The `annotation` column is now automatically added and all L-R pairs are assigned as `Secreted Signaling`, which means that these L-R pairs are assumed to mediate diffusion-based cellular communication.\")\n interaction_input$annotation <- \"Secreted Signaling\"\n }\n }\n if (\"annotation\" %in% colnames(interaction_input) == TRUE) {\n if (length(unique(interaction_input$annotation)) > 1) {\n interaction_input$annotation <- factor(interaction_input$annotation, levels = c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\", \"Cell-Cell Contact\"))\n interaction_input <- interaction_input[order(interaction_input$annotation), , drop = FALSE]\n interaction_input$annotation <- as.character(interaction_input$annotation)\n }\n object@DB$interaction <- interaction_input\n }\n\n if (is.null(features)) {\n DB <- object@DB\n gene.use_input <- extractGene(DB)\n gene.use <- intersect(gene.use_input, rownames(object@data))\n } else {\n gene.use <- intersect(features, rownames(object@data))\n }\n object@data.signaling <- object@data[rownames(object@data) %in% gene.use, ]\n return(object)\n}\n\n\n\n#' Identify over-expressed signaling genes associated with each cell group\n#'\n#' USERS can use customized gene set as over-expressed signaling genes by setting `object@var.features[[features.name]] <- features.sig`\n#' The Bonferroni corrected/adjusted p value can be obtained via `object@var.features[[paste0(features.name, \".info\")]]`. Note that by default `features.name = \"features\"`\n#'\n#' @param object CellChat object\n#' @param data.use a customed data matrix. Default: data.use = NULL and the expression matrix in the slot 'data.signaling' is used\n#' @param group.by cell group information; default is `object@idents`; otherwise it should be one of the column names of the meta slot\n#' @param idents.use a subset of cell groups used for analysis\n#' @param invert whether to invert the idents.use\n#' @param group.dataset dataset origin information in a merged CellChat object; set it as one of the column names of meta slot when identifying the highly enriched genes in one dataset for each cell group\n#' @param pos.dataset the dataset name used for identifying highly enriched genes in this dataset for each cell group\n#' @param group.DE.combined Whether to perform differential expression between conditions by ignoring cell group information. By default, group.DE.combined = FALSE, which will perform differential expression analysis between two biological conditions for each cell group;\n#' When group.DE.combined = TRUE, it will perform DE analysis by combining all cell groups together.\n#'\n#' @param features.name a char name used for storing the over-expressed signaling genes in `object@var.features[[features.name]]`\n#' @param only.pos Only return positive markers\n#' @param features features used for identifying Over Expressed genes. default use all features\n#' @param return.object whether to return the object; otherwise return a data frame consisting of over-expressed signaling genes associated with each cell group\n#' @param thresh.pc Threshold of the fraction of cells expressed in one cluster, i.e., thresh.pc = 0.1\n#' @param thresh.fc Threshold of Log Fold Change, i.e., thresh.pc = 0.1\n#' @param thresh.p Threshold of p-values, i.e., thresh.pc = 0.05\n#' @param do.DE Whether to perform differential expression analysis. By default do.DE = TRUE; When do.DE = FALSE, selecting over-expressed genes that are expressed in more than `min.cells` cells.\n#' @param do.fast If do.fast = TRUE, then perform a ultra-fast Wilcoxon test using presto package; otherwise using stats package. These two methods produce different logFC values, and the presto::wilcoxauc method gives smaller values.\n#' @param min.cells the minmum number of expressed cells required for the genes that are considered for cell-cell communication analysis\n#' @importFrom future nbrOfWorkers\n#' @importFrom pbapply pbsapply\n#' @importFrom future.apply future_sapply\n#' @importFrom stats sd wilcox.test p.adjust\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, two new elements named 'features.name' and paste0(features.name, \".info\") will be added into the list `object@var.features`\n#' `object@var.features[[features.name]]` is a vector consisting of the identified over-expressed signaling genes;\n#' `object@var.features[[paste0(features.name, \".info\")]]` is a data frame returned from the differential expression analysis\n#' @export\n#'\nidentifyOverExpressedGenes <- function(object, data.use = NULL, group.by = NULL, idents.use = NULL, invert = FALSE,\n group.dataset = NULL, pos.dataset = NULL, group.DE.combined = FALSE,\n features.name = \"features\", only.pos = TRUE, features = NULL, return.object = TRUE,\n thresh.pc = 0, thresh.fc = 0, thresh.p = 0.05, do.DE = TRUE, do.fast = TRUE, min.cells = 10) {\n if (!is.list(object@var.features)) {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n if (is.null(data.use)) {\n X <- object@data.signaling\n if (nrow(X) < 3) {stop(\"Please check `object@data.signaling` and ensure that you have run `subsetData` and that the data matrix `object@data.signaling` looks OK.\")}\n } else {\n X <- data.use\n }\n\n if (is.null(features)) {\n features.use <- row.names(X)\n } else {\n features.use <- intersect(features, row.names(X))\n }\n data.use <- X[features.use,]\n\n if (do.DE) {\n # select genes based on differential expression\n data.use <- as.matrix(data.use)\n\n if (is.null(group.by)) {\n labels <- object@idents\n if (!is.factor(labels)) {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n level.use <- levels(labels)[levels(labels) %in% unique(labels)]\n if (!is.null(idents.use)) {\n if (invert) {\n level.use <- level.use[!(level.use %in% idents.use)]\n } else {\n level.use <- level.use[level.use %in% idents.use]\n }\n }\n numCluster <- length(level.use)\n\n if (!is.null(group.dataset)) {\n labels.dataset <- as.character(object@meta[[group.dataset]])\n if (!(pos.dataset %in% unique(labels.dataset))) {\n cat(\"Please set pos.dataset to be one of the following dataset names: \", unique(as.character(labels.dataset)))\n stop()\n }\n labels.dataset[labels.dataset != pos.dataset] <- toString(setdiff(unique(labels.dataset), pos.dataset))\n labels.dataset <- factor(labels.dataset, levels = c(pos.dataset, setdiff(unique(labels.dataset), pos.dataset)))\n }\n\n if (do.fast) {\n presto.check <- rlang::is_installed(c(\"presto\"))\n if (!presto.check) {\n stop(\n \"For a faster implementation of the Wilcoxon Test, please install the presto package\",\n \"\\n--------------------------------------------\",\n \"\\n devtools::install_github('immunogenomics/presto')\",\n \"\\n--------------------------------------------\",\n \"\\n Otherwise, plase set `do.fast = FALSE` for running the standard Wilcoxon Test!\\n\"\n )\n }\n if (is.null(group.dataset)) {\n genes.de <- presto::wilcoxauc(data.use, labels, groups_use = level.use)\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"clusters\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100) %>% arrange(pvalues)\n\n } else if ((!is.null(group.dataset)) & (group.DE.combined == FALSE)) {\n genes.de <- data.frame()\n for (i in 1:numCluster) {\n idx <- which(labels == level.use[i])\n data.use.i <- data.use[ ,idx]\n labels.i <- labels.dataset[idx]\n genes.de.i <- presto::wilcoxauc(data.use.i, labels.i)\n # genes.de.i <- genes.de.i[1:(nrow(genes.de.i)/2),]\n genes.de.i$clusters <- level.use[i]\n genes.de <- rbind(genes.de, genes.de.i)\n }\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"datasets\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100)\n markers.all$datasets <- factor(markers.all$datasets, levels = levels(labels.dataset))\n markers.all <- markers.all[order(markers.all$datasets, markers.all$pvalues, -markers.all$logFC), ]\n } else if ((!is.null(group.dataset)) & (group.DE.combined == TRUE)) {\n genes.de.c <- presto::wilcoxauc(data.use, labels.dataset)\n genes.de.c <- genes.de.c[1:(nrow(genes.de.c)/2),]\n genes.de <- data.frame()\n for (i in 1:numCluster) {\n genes.de.c$clusters <- level.use[i]\n genes.de <- rbind(genes.de, genes.de.c)\n }\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"datasets\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100) %>% arrange(pvalues)\n\n }\n markers.all <- dplyr::select(markers.all, -c(\"logFC_abs\",\"statistic\",\"pct.max\"))\n\n if (only.pos & nrow(markers.all) > 0) {\n markers.all <- subset(markers.all, subset = logFC > 0)\n }\n markers.all$features <- as.character(markers.all$features)\n\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- unique(features.sig)\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n\n } else {\n\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n\n mean.fxn <- function(x) {\n return(log(x = mean(x = expm1(x = x)) + 1))\n }\n labels <- as.character(labels)\n genes.de <- vector(\"list\", length = numCluster)\n for (i in 1:numCluster) {\n features <- features.use\n if (is.null(group.dataset)) {\n cell.use1 <- which(labels == level.use[i])\n cell.use2 <- base::setdiff(1:length(labels), cell.use1)\n } else if ((!is.null(group.dataset)) & (group.DE.combined == FALSE)) {\n cell.use1 <- which((labels == level.use[i]) & (labels.dataset == pos.dataset))\n cell.use2 <- which((labels == level.use[i]) & (labels.dataset != pos.dataset))\n } else if ((!is.null(group.dataset)) & (group.DE.combined == TRUE)) {\n cell.use1 <- which(labels.dataset == pos.dataset)\n cell.use2 <- which(labels.dataset != pos.dataset)\n }\n\n # feature selection (based on percentages)\n thresh.min <- 0\n pct.1 <- round(\n x = rowSums(data.use[features, cell.use1, drop = FALSE] > thresh.min) /\n length(x = cell.use1),\n digits = 3\n )\n pct.2 <- round(\n x = rowSums(data.use[features, cell.use2, drop = FALSE] > thresh.min) /\n length(x = cell.use2),\n digits = 3\n )\n data.alpha <- cbind(pct.1, pct.2)\n colnames(x = data.alpha) <- c(\"pct.1\", \"pct.2\")\n alpha.min <- apply(X = data.alpha, MARGIN = 1, FUN = max)\n names(x = alpha.min) <- rownames(x = data.alpha)\n features <- names(x = which(x = alpha.min > thresh.pc))\n if (length(x = features) == 0) {\n #stop(\"No features pass thresh.pc threshold\")\n next\n }\n\n # feature selection (based on average difference)\n data.1 <- apply(X = data.use[features, cell.use1, drop = FALSE],MARGIN = 1,FUN = mean.fxn)\n data.2 <- apply(X = data.use[features, cell.use2, drop = FALSE],MARGIN = 1,FUN = mean.fxn)\n FC <- (data.1 - data.2)\n if (only.pos) {\n features.diff <- names(which(FC > thresh.fc))\n } else {\n features.diff <- names(which(abs(FC) > thresh.fc))\n }\n\n features <- intersect(x = features, y = features.diff)\n if (length(x = features) == 0) {\n # stop(\"No features pass thresh.fc threshold\")\n next\n }\n\n data1 <- data.use[features, cell.use1, drop = FALSE]\n data2 <- data.use[features, cell.use2, drop = FALSE]\n\n pvalues <- unlist(\n x = my.sapply(\n X = 1:nrow(x = data1),\n FUN = function(x) {\n # return(wilcox.test(data1[x, ], data2[x, ], alternative = \"greater\")$p.value)\n return(wilcox.test(data1[x, ], data2[x, ])$p.value)\n }\n )\n )\n\n pval.adj = stats::p.adjust(\n p = pvalues,\n method = \"bonferroni\",\n n = nrow(X)\n )\n genes.de[[i]] <- data.frame(clusters = level.use[i], features = as.character(rownames(data1)), pvalues = pvalues, logFC = FC[features], data.alpha[features,, drop = F],pvalues.adj = pval.adj, stringsAsFactors = FALSE)\n }\n\n markers.all <- data.frame()\n for (i in 1:numCluster) {\n gde <- genes.de[[i]]\n if (!is.null(gde)) {\n gde <- gde[order(gde$pvalues, -gde$logFC), ]\n gde <- subset(gde, subset = pvalues < thresh.p)\n if (nrow(gde) > 0) {\n markers.all <- rbind(markers.all, gde)\n }\n }\n }\n if (only.pos & nrow(markers.all) > 0) {\n markers.all <- subset(markers.all, subset = logFC > 0)\n }\n if (!is.null(group.dataset)) {\n markers.all$datasets[markers.all$logFC > 0] <- pos.dataset\n markers.all$datasets[markers.all$logFC < 0] <- setdiff(unique(labels.dataset), pos.dataset)\n markers.all$datasets <- factor(markers.all$datasets, levels = levels(labels.dataset))\n markers.all <- markers.all[order(markers.all$datasets, markers.all$pvalues, -markers.all$logFC), ]\n }\n markers.all$features <- as.character(markers.all$features)\n\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- features.sig\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n }\n\n } else {\n # select genes if they are exprssed in at least `min.cells` cells\n markers.all <- data.frame(features = as.character(rownames(data.use)), nCells = rowSums(data.use > 0))\n markers.all <- dplyr::filter(markers.all, nCells >= min.cells)\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- unique(features.sig)\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n }\n\n\n if (return.object) {\n return(object)\n } else {\n return(markers.all)\n }\n}\n\n\n#' Identify over-expressed ligands and (complex) receptors associated with each cell group\n#'\n#' This function identifies the over-expressed ligands and (complex) receptors based on the identified signaling genes from 'identifyOverExpressedGenes'.\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for storing the over-expressed ligands and receptors in `object@var.features[[paste0(features.name, \".LR\")]]`\n#' @param features a vector of features to use. default use all over-expressed genes in `object@var.features[[features.name]]`\n#' @param return.object whether returning a CellChat object. If FALSE, it will return a data frame containing over-expressed ligands and (complex) receptors associated with each cell group\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom dplyr select\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, a new element named paste0(features.name, \".LR\") will be added into the list `object@var.features`\n#' @export\n#'\nidentifyOverExpressedLigandReceptor <- function(object, features.name = \"features\", features = NULL, return.object = TRUE) {\n\n features.name.LR <- paste0(features.name, \".LR\")\n features.name <- paste0(features.name, \".info\")\n DB <- object@DB\n interaction_input <- DB$interaction\n complex_input <- DB$complex\n pairLR <- select(interaction_input, ligand, receptor)\n LR.use <- unique(c(pairLR$ligand, pairLR$receptor))\n if (is.null(features)) {\n if (is.list(object@var.features)) {\n markers.all <- object@var.features[[features.name]] # use the updated CellChat object 12/2020\n } else {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n\n } else {\n features.use <- features\n rm(features)\n markers.all <- subset(markers.all, subset = features %in% features.use)\n }\n\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n complexSubunits <- complex_input[, grepl(\"subunit\" , colnames(complex_input))]\n\n markers.all.new <- data.frame()\n for (i in 1:nrow(markers.all)) {\n if (markers.all$features[i] %in% LR.use) {\n markers.all.new <- rbind(markers.all.new, markers.all[i, , drop = FALSE])\n } else {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (markers.all$features[i] %in% complexsubunitsV) {\n return(x)\n }\n }\n )\n )\n complexSubunits.sig <- rownames(complexSubunits[index.sig,])\n markers.all.complex <- data.frame()\n for (j in 1:length(complexSubunits.sig)) {\n markers.all.complex <- rbind(markers.all.complex, markers.all[i, , drop = FALSE])\n }\n markers.all.complex$features <- complexSubunits.sig\n markers.all.new <- rbind(markers.all.new, markers.all.complex)\n }\n }\n\n object@var.features[[features.name.LR]] <- markers.all.new\n\n if (return.object) {\n return(object)\n } else {\n return(markers.all.new)\n }\n}\n\n\n\n#' Identify over-expressed ligand-receptor interactions (pairs) within the used CellChatDB\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for assess the results in `object@var.features[[features.name]]`\n#' @param features a vector of features to use. default use all over-expressed genes in `object@var.features[[features.name]]`\n#' @param variable.both variable.both = TRUE will require that both ligand and receptor from one pair are over-expressed;\n#'\n#' variable.both = FALSE will only require that either ligand or receptor from one pair is over-expressed, leading to more over-expressed ligand-receptor interactions (pairs) for further analysis.\n#' @param return.object whether returning a CellChat object. If FALSE, it will return a data frame containing the over-expressed ligand-receptor pairs\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom dplyr select\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, a new element named 'LRsig' will be added into the list `object@LR`\n#' @export\n#'\nidentifyOverExpressedInteractions <- function(object, features.name = \"features\", variable.both = TRUE, features = NULL, return.object = TRUE) {\n gene.use <- row.names(object@data.signaling)\n DB <- object@DB\n if (is.null(features)) {\n if (is.list(object@var.features)) {\n features.sig <- object@var.features[[features.name]] # use the updated CellChat object 12/2020\n } else {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n\n } else {\n features.sig <- features\n }\n\n interaction_input <- DB$interaction\n complex_input <- DB$complex\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n complexSubunits <- complex_input[, grepl(\"subunit\" , colnames(complex_input))]\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (length(intersect(complexsubunitsV, features.sig)) > 0 & all(complexsubunitsV %in% gene.use)) {\n return(x)\n }\n }\n )\n )\n complexSubunits.sig <- complexSubunits[index.sig,]\n\n index.use <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (all(complexsubunitsV %in% gene.use)) {\n return(x)\n }\n }\n )\n )\n complexSubunits.use <- complexSubunits[index.use,]\n\n pairLR <- select(interaction_input, ligand, receptor)\n\n if (variable.both) {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(pairLR),\n FUN = function(x) {\n if (all(unlist(pairLR[x,], use.names = F) %in% c(features.sig, rownames(complexSubunits.sig)))) {\n return(x)\n }\n }\n )\n )\n } else {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(pairLR),\n FUN = function(x) {\n # if (all(unlist(pairLR[x,], use.names = F) %in% c(features.sig, rownames(complexSubunits.sig)))) {\n if (all(unlist(pairLR[x,], use.names = F) %in% c(gene.use, rownames(complexSubunits.use))) & (length(intersect(unlist(pairLR[x,], use.names = F), c(features.sig, rownames(complexSubunits.sig)))) > 0)) {\n return(x)\n }\n }\n )\n )\n }\n\n pairLRsig <- interaction_input[index.sig, ]\n object@LR$LRsig <- pairLRsig\n cat(\"The number of highly variable ligand-receptor pairs used for signaling inference is\", nrow(pairLRsig), '\\n')\n if (return.object) {\n return(object)\n } else {\n return(pairLRsig)\n }\n}\n\n\n#' Smooth the gene expression data\n#'\n#' A diffusion process is used to smooth genes’ expression values based on their neighbors’ defined in a high-confidence experimentally validated protein-protein network.\n#'\n#' This function is useful when analyzing single-cell data with shallow sequencing depth because the projection reduces the dropout effects of signaling genes, in particular for possible zero expression of subunits of ligands/receptors\n#'\n#' @param object CellChat object\n#' @param method When method = \"netSmooth\", smoothing a gene’s expression values based on its neighbors defined in a high-confidence experimentally validated protein-protein network.\n#' @param adj adjacency matrix of protein-protein interaction network to use\n#' @param alpha numeric in [0,1] alpha = 0: no smoothing; a larger value alpha results in increasing levels of smoothing.\n#' @param normalizeAdjMatrix how to normalize the adjacency matrix\n#' possible values are 'rows' (in-degree)\n#' and 'columns' (out-degree)\n#' @return a smoothed gene expression matrix\n#' @export\n#'\n# This function is adapted from https://github.com/BIMSBbioinfo/netSmooth\nsmoothData <- function(object, method = c(\"netSmooth\"), adj = NULL, alpha=0.5, normalizeAdjMatrix=c('rows','columns')){\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n stop(\"`object@data.smooth` is missing. Please update the CellChat object via `updateCellChat`! \\n\")\n }\n data <- as.matrix(object@data.signaling)\n normalizeAdjMatrix <- match.arg(normalizeAdjMatrix)\n if (method == \"netSmooth\") {\n if (is.null(adj)) stop(\"Please provide the `adj`. \\n\")\n stopifnot(is(adj, 'matrix') | is(adj, 'sparseMatrix'))\n stopifnot((is.numeric(alpha) & (alpha > 0 & alpha < 1)))\n if(sum(Matrix::rowSums(adj)==0)>0) stop(\"PPI cannot have zero rows/columns\")\n if(sum(Matrix::colSums(adj)==0)>0) stop(\"PPI cannot have zero rows/columns\")\n }\n if(is.numeric(alpha)) {\n if(alpha<0 | alpha > 1) {\n stop('alpha must be between 0 and 1')\n }\n data.projected <- projectAndRecombine(data, adj, alpha,normalizeAdjMatrix=normalizeAdjMatrix)\n } else stop(\"unsupported alpha value: \", class(alpha))\n object@data.smooth <- data.projected\n return(object)\n}\n\n#' Perform network projecting on network when the network genes and the\n#' experiment genes aren't exactly the same.\n#'\n#' The gene network might be defined only on a subset of genes that are\n#' measured in any experiment. Further, an experiment might not measure all\n#' genes that are present in the network. This function projects the experiment\n#' data onto the gene space defined by the network prior to projecting. Then,\n#' it projects the projected data back into the original dimansions.\n#'\n#' @param gene_expression gene expession data to be projected\n#' [N_genes x M_samples]\n#' @param adj_matrix adjacenty matrix of network to perform projecting over.\n#' Will be column-normalized.\n#' Rownames and colnames should be genes.\n#' @param alpha network projecting parameter (1 - restart probability in random\n#' walk model.\n#' @param projecting.function must be a function that takes in data, adjacency\n#' matrix, and alpha. Will be used to perform the\n#' actual projecting.\n#' @param normalizeAdjMatrix which dimension (rows or columns) should the\n#' adjacency matrix be normalized by. rows\n#' corresponds to in-degree, columns to\n#' out-degree.\n#' @return matrix with network-projected gene expression data. Genes that are\n#' not present in projecting network will retain original values.\n#' @keywords internal\n#'\nprojectAndRecombine <- function(gene_expression, adj_matrix, alpha,\n projecting.function=randomWalkBySolve,\n normalizeAdjMatrix=c('rows','columns')) {\n normalizeAdjMatrix <- match.arg(normalizeAdjMatrix)\n gene_expression_in_A_space <- projectOnNetwork(gene_expression,rownames(adj_matrix))\n gene_expression_in_A_space_project <- projecting.function(gene_expression_in_A_space, adj_matrix, alpha, normalizeAdjMatrix)\n gene_expression_project <- projectFromNetworkRecombine(gene_expression, gene_expression_in_A_space_project)\n return(gene_expression_project)\n}\n\n\n#' Project the gene expression matrix onto a lower space\n#' of the genes defined in the projecting network\n#' @param gene_expression gene expression matrix\n#' @param new_features the genes in the network, on which to project\n#' the gene expression matrix\n#' @param missing.value value to assign to genes that are in network,\n#' but missing from gene expression matrix\n#' @return the gene expression matrix projected onto the gene space defined by new_features\n#' @keywords internal\nprojectOnNetwork <- function(gene_expression, new_features, missing.value=0) {\n # data_in_new_space = matrix(rep(0, length(new_features)*dim(gene_expression)[2]),nrow=length(new_features))\n data_in_new_space = matrix(0, ncol=dim(gene_expression)[2], nrow=length(new_features))\n rownames(data_in_new_space) <- new_features\n colnames(data_in_new_space) <- colnames(gene_expression)\n genes_in_both <- intersect(rownames(data_in_new_space),rownames(gene_expression))\n data_in_new_space[genes_in_both,] <- gene_expression[genes_in_both,]\n genes_only_in_network <- setdiff(new_features, rownames(gene_expression))\n data_in_new_space[genes_only_in_network,] <- missing.value\n return(data_in_new_space)\n}\n\n#' project data on graph by solving the linear equation (I - alpha*A) * E_sm = E * (1-alpha)\n\n#' @param E initial data matrix [NxM]\n#' @param A adjacency matrix of graph to network project on will be column-normalized.\n#' @param alpha projecting coefficient (1 - restart probability of random walk)\n#' @return network-projected gene expression\n#' @keywords internal\nrandomWalkBySolve <- function(E, A, alpha, normalizeAjdMatrix=c('rows','columns')) {\n normalizeAjdMatrix <- match.arg(normalizeAjdMatrix)\n if (normalizeAjdMatrix=='rows') {\n Anorm <- l1NormalizeRows(A)\n } else if (normalizeAjdMatrix=='columns') {\n Anorm <- l1NormalizeColumns(A)\n }\n eye <- diag(dim(A)[1])\n AA <- eye - alpha*Anorm\n BB <- (1-alpha) * E\n return(solve(AA, BB))\n}\n\n#' Column-normalize a sparse, symmetric matrix (using the l1 norm) so that each\n#' column sums to 1.\n#'\n#' @param A matrix\n#' @usage l1NormalizeColumns(A)\n#' @return column-normalized sparse matrix object\n#' @keywords internal\nl1NormalizeColumns <- function(A) {\n return(Matrix::t(Matrix::t(A)/Matrix::colSums(A)))\n}\n\n#' Row-normalize a sparse, symmetric matrix (using the l1 norm) so that each\n#' row sums to 1.\n#'\n#' @param A matrix\n#' @usage l1NormalizeRows(A)\n#' @return row-normalized sparse matrix object\n#' @keywords internal\nl1NormalizeRows <- function(A) {\n return(A/Matrix::rowSums(A))\n}\n\n#' Combine gene expression from projected space (that of the network) with the\n#' expression of genes that were not projected (not present in network)\n#' @keywords internal\n#' @param original_expression the non-projected expression\n#' @param projected_expression the projected gene expression, in the space\n#' of the genes defined by the network\n#' @return a matrix in the dimensions of original_expression, where values that\n#' are present in projected_expression are copied from there.\nprojectFromNetworkRecombine <- function(original_expression, projected_expression) {\n data_in_original_space <- original_expression\n genes_in_both <- intersect(rownames(original_expression),rownames(projected_expression))\n data_in_original_space[genes_in_both,] <- as.matrix(projected_expression[genes_in_both,])\n return(data_in_original_space)\n}\n\n\n#' Dimension reduction using PCA\n#'\n#' @param data.use input data (samples in rows, features in columns)\n#' @param do.fast whether do fast PCA\n#' @param dimPC the number of components to keep\n#' @param seed.use set a seed\n#' @param weight.by.var whether use weighted pc.scores\n#' @importFrom stats prcomp\n#' @importFrom irlba irlba\n#' @return\n#' @export\n#'\n#' @examples\nrunPCA <- function(data.use, do.fast = T, dimPC = 50, seed.use = 42, weight.by.var = T) {\n set.seed(seed = seed.use)\n if (do.fast) {\n dimPC <- min(dimPC, ncol(data.use) - 1)\n pca.res <- irlba::irlba(data.use, nv = dimPC)\n sdev <- pca.res$d/sqrt(max(1, nrow(data.use) - 1))\n if (weight.by.var){\n pc.scores <- pca.res$u %*% diag(pca.res$d)\n } else {\n pc.scores <- pca.res$u\n }\n } else {\n dimPC <- min(dimPC, ncol(data.use) - 1)\n pca.res <- stats::prcomp(x = data.use, rank. = dimPC)\n sdev <- pca.res$sdev\n if (weight.by.var) {\n pc.scores <- pca.res$x %*% diag(pca.res$sdev[1:dimPC]^2)\n } else {\n pc.scores <- pca.res$x\n }\n }\n rownames(pc.scores) <- rownames(data.use)\n colnames(pc.scores) <- paste0('PC', 1:ncol(pc.scores))\n return(pc.scores)\n}\n\n\n#' Run UMAP\n#' @param data.use input data matrix\n#' @param n_neighbors This determines the number of neighboring points used in\n#' local approximations of manifold structure. Larger values will result in more\n#' global structure being preserved at the loss of detailed local structure. In general this parameter should often be in the range 5 to 50.\n#' @param n_components The dimension of the space to embed into.\n#' @param metric This determines the choice of metric used to measure distance in the input space.\n#' @param n_epochs the number of training epochs to be used in optimizing the low dimensional embedding. Larger values result in more accurate embeddings. If NULL is specified, a value will be selected based on the size of the input dataset (200 for large datasets, 500 for small).\n#' @param learning_rate The initial learning rate for the embedding optimization.\n#' @param min_dist This controls how tightly the embedding is allowed compress points together.\n#' Larger values ensure embedded points are moreevenly distributed, while smaller values allow the\n#' algorithm to optimise more accurately with regard to local structure. Sensible values are in the range 0.001 to 0.5.\n#' @param spread he effective scale of embedded points. In combination with min.dist this determines how clustered/clumped the embedded points are.\n#' @param set_op_mix_ratio Interpolate between (fuzzy) union and intersection as the set operation used to combine local fuzzy simplicial sets to obtain a global fuzzy simplicial sets.\n#' @param local_connectivity The local connectivity required - i.e. the number of nearest neighbors\n#' that should be assumed to be connected at a local level. The higher this value the more connected\n#' the manifold becomes locally. In practice this should be not more than the local intrinsic dimension of the manifold.\n#' @param repulsion_strength Weighting applied to negative samples in low dimensional embedding\n#' optimization. Values higher than one will result in greater weight being given to negative samples.\n#' @param negative_sample_rate The number of negative samples to select per positive sample in the\n#' optimization process. Increasing this value will result in greater repulsive force being applied, greater optimization cost, but slightly more accuracy.\n#' @param a More specific parameters controlling the embedding. If NULL, these values are set automatically as determined by min. dist and spread.\n#' @param b More specific parameters controlling the embedding. If NULL, these values are set automatically as determined by min. dist and spread.\n#' @param seed.use Set a random seed. By default, sets the seed to 42.\n#' @param metric_kwds,angular_rp_forest,verbose other parameters used in UMAP\n#' @import reticulate\n#' @export\n#'\nrunUMAP <- function(\n data.use,\n n_neighbors = 30L,\n n_components = 2L,\n metric = \"correlation\",\n n_epochs = NULL,\n learning_rate = 1.0,\n min_dist = 0.3,\n spread = 1.0,\n set_op_mix_ratio = 1.0,\n local_connectivity = 1L,\n repulsion_strength = 1,\n negative_sample_rate = 5,\n a = NULL,\n b = NULL,\n seed.use = 42L,\n metric_kwds = NULL,\n angular_rp_forest = FALSE,\n verbose = FALSE){\n if (!reticulate::py_module_available(module = 'umap')) {\n stop(\"Cannot find UMAP, please install through pip (e.g. pip install umap-learn or reticulate::py_install(packages = 'umap-learn')).\")\n }\n set.seed(seed.use)\n reticulate::py_set_seed(seed.use)\n umap_import <- reticulate::import(module = \"umap\", delay_load = TRUE)\n umap <- umap_import$UMAP(\n n_neighbors = as.integer(n_neighbors),\n n_components = as.integer(n_components),\n metric = metric,\n n_epochs = n_epochs,\n learning_rate = learning_rate,\n min_dist = min_dist,\n spread = spread,\n set_op_mix_ratio = set_op_mix_ratio,\n local_connectivity = local_connectivity,\n repulsion_strength = repulsion_strength,\n negative_sample_rate = negative_sample_rate,\n a = a,\n b = b,\n metric_kwds = metric_kwds,\n angular_rp_forest = angular_rp_forest,\n verbose = verbose\n )\n Rumap <- umap$fit_transform\n umap_output <- Rumap(t(data.use))\n colnames(umap_output) <- paste0('UMAP', 1:ncol(umap_output))\n rownames(umap_output) <- colnames(data.use)\n return(umap_output)\n}\n\n.error_if_no_Seurat <- function() {\n if (!requireNamespace(\"Seurat\", quietly = TRUE)) {\n stop(\"Seurat installation required for working with Seurat objects\")\n }\n}\n\n\n#' Color interpolation\n#'\n#' This function is modified from https://rdrr.io/cran/circlize/src/R/utils.R\n#' Colors are linearly interpolated according to break values and corresponding colors through CIE Lab color space (`colorspace::LAB`) by default.\n#' Values exceeding breaks will be assigned with corresponding maximum or minimum colors.\n#'\n#' @param breaks A vector indicating numeric breaks\n#' @param colors A vector of colors which correspond to values in ``breaks``\n#' @param transparency A single value in ``[0, 1]``. 0 refers to no transparency and 1 refers to full transparency\n#' @param space color space in which colors are interpolated. Value should be one of \"RGB\", \"HSV\", \"HLS\", \"LAB\", \"XYZ\", \"sRGB\", \"LUV\", see `colorspace::color-class` for detail.\n#' @importFrom colorspace coords RGB HSV HLS LAB XYZ sRGB LUV hex\n#' @importFrom grDevices col2rgb\n#' @return It returns a function which accepts a vector of numeric values and returns interpolated colors.\n#' @export\n#' @examples\n#' \\dontrun{\n#' col_fun = colorRamp3(c(-1, 0, 1), c(\"green\", \"white\", \"red\"))\n#' col_fun(c(-2, -1, -0.5, 0, 0.5, 1, 2))\n#' }\ncolorRamp3 = function(breaks, colors, transparency = 0, space = \"LAB\") {\n\n if(length(breaks) != length(colors)) {\n stop(\"Length of `breaks` should be equal to `colors`.\\n\")\n }\n\n colors = colors[order(breaks)]\n breaks = sort(breaks)\n\n l = duplicated(breaks)\n breaks = breaks[!l]\n colors = colors[!l]\n\n if(length(breaks) == 1) {\n stop(\"You should have at least two distinct break values.\")\n }\n\n\n if(! space %in% c(\"RGB\", \"HSV\", \"HLS\", \"LAB\", \"XYZ\", \"sRGB\", \"LUV\")) {\n stop(\"`space` should be in 'RGB', 'HSV', 'HLS', 'LAB', 'XYZ', 'sRGB', 'LUV'\")\n }\n\n colors = t(grDevices::col2rgb(colors)/255)\n\n attr = list(breaks = breaks, colors = colors, transparency = transparency, space = space)\n\n if(space == \"LUV\") {\n i = which(apply(colors, 1, function(x) all(x == 0)))\n colors[i, ] = 1e-5\n }\n\n transparency = 1-ifelse(transparency > 1, 1, ifelse(transparency < 0, 0, transparency))[1]\n transparency_str = sprintf(\"%X\", round(transparency*255))\n if(nchar(transparency_str) == 1) transparency_str = paste0(\"0\", transparency_str)\n\n fun = function(x = NULL, return_rgb = FALSE, max_value = 1) {\n if(is.null(x)) {\n stop(\"Please specify `x`\\n\")\n }\n\n att = attributes(x)\n if(is.data.frame(x)) x = as.matrix(x)\n\n l_na = is.na(x)\n if(all(l_na)) {\n return(rep(NA, length(l_na)))\n }\n\n x2 = x[!l_na]\n\n x2 = ifelse(x2 < breaks[1], breaks[1],\n ifelse(x2 > breaks[length(breaks)], breaks[length(breaks)],\n x2\n ))\n ibin = .bincode(x2, breaks, right = TRUE, include.lowest = TRUE)\n res_col = character(length(x2))\n for(i in unique(ibin)) {\n l = ibin == i\n res_col[l] = .get_color(x2[l], breaks[i], breaks[i+1], colors[i, ], colors[i+1, ], space = space)\n }\n res_col = paste(res_col, transparency_str[1], sep = \"\")\n\n if(return_rgb) {\n res_col = t(grDevices::col2rgb(as.vector(res_col), alpha = TRUE)/255)\n return(res_col)\n } else {\n res_col2 = character(length(x))\n res_col2[l_na] = NA\n res_col2[!l_na] = res_col\n\n attributes(res_col2) = att\n return(res_col2)\n }\n }\n\n attributes(fun) = attr\n return(fun)\n}\n\n.restrict_in = function(x, lower, upper) {\n x[x > upper] = upper\n x[x < lower] = lower\n x\n}\n\n# x: vector\n# break1 single value\n# break2 single value\n# rgb1 vector with 3 elements\n# rgb2 vector with 3 elements\n.get_color = function(x, break1, break2, col1, col2, space) {\n\n col1 = colorspace::coords(as(colorspace::sRGB(col1[1], col1[2], col1[3]), space))\n col2 = colorspace::coords(as(colorspace::sRGB(col2[1], col2[2], col2[3]), space))\n\n res_col = matrix(ncol = 3, nrow = length(x))\n for(j in 1:3) {\n xx = (x - break2)*(col2[j] - col1[j]) / (break2 - break1) + col2[j]\n res_col[, j] = xx\n }\n\n res_col = get(space)(res_col)\n res_col = colorspace::coords(as(res_col, \"sRGB\"))\n res_col[, 1] = .restrict_in(res_col[,1], 0, 1)\n res_col[, 2] = .restrict_in(res_col[,2], 0, 1)\n res_col[, 3] = .restrict_in(res_col[,3], 0, 1)\n colorspace::hex(colorspace::sRGB(res_col))\n}\n\n#' Update the cell-cell communication array from a customized cell-cell-communication scores between different cell groups\n#'\n#' Users may also check the `updateCellChatDB` function for integrating other resources or utilizing a custom database\n#'\n#' @param object CellChat object\n#' @param net a data frame with at least five columns named as `source`,`target`,`ligand`,`receptor` and `score`, which defines the customized cell-cell-communication scores between different cell groups.\n#' a p-value column named `pval`, and additional columns named `interaction_name` and `interaction_name_2` can be also provided.\n#' @return a CellChat object with updated slot `net` and slot `DB` if db is not NULL.\n#' @export\n\nupdateCCC_score <- function(object, net) {\n df.net <- net\n if (all(c(\"source\",\"target\",\"ligand\",\"receptor\",\"score\") %in% colnames(df.net)) == FALSE) {\n stop(\"The input `net` must contain at least five columns named as source,target,ligand,receptor,score\")\n }\n if (all(c(\"interaction_name\") %in% colnames(df.net)) == FALSE) {\n df.net$interaction_name <- paste0(toupper(df.net$ligand), \"_\", toupper(df.net$receptor))\n }\n if (all(c(\"interaction_name_2\") %in% colnames(df.net)) == FALSE) {\n df.net$interaction_name_2 <- paste0(df.net$ligand, \" - \", df.net$receptor)\n }\n if (all(c(\"pval\") %in% colnames(df.net)) == FALSE) {\n df.net$pval <- rep(0, nrow(df.net))\n }\n df.net$prob <- df.net$score\n\n LR <- unique(df.net$interaction_name)\n cell.levels <- levels(object@idents)\n numCluster <- length(cell.levels)\n mat.prob.all <- array(0, dim = c(numCluster,numCluster,length(LR)))\n mat.pval.all <- mat.prob.all\n for (i in 1:length(LR)) {\n df.i <- df.net[df.net$interaction_name == LR[i], , drop = FALSE]\n mat.prob <- matrix(0, nrow = numCluster, ncol = numCluster)\n mat.pval <- mat.prob\n for (j in 1:nrow(df.i)) {\n idx.s <- which(df.i$source[j] == cell.levels)\n idx.t <- which(df.i$target[j] == cell.levels)\n mat.prob[idx.s, idx.t] <- df.i$prob[j]\n mat.pval[idx.s, idx.t] <- df.i$pval[j]\n }\n mat.prob.all[,,i] <- mat.prob\n mat.pval.all[,,i] <- mat.pval\n }\n\n dimnames(mat.prob.all) <- list(cell.levels, cell.levels, LR)\n dimnames(mat.pval.all) <- dimnames(mat.prob.all)\n net <- list(\"prob\" = mat.prob.all, \"pval\" = mat.pval.all)\n object@net <- net\n\n return(object)\n}\n\n#' Preprocessing multi-omics data and preparing the L-R database\n#'\n#' @param data.list a list consisting of multi-omics data (e.g., RNA & ADT)\n#' @param db one of the CellChatDB databases: CellChatDB.human, CellChatDB.mouse, CellChatDB.zebrafish\n#' @param do.sparse whether to use sparse format\n#' @export\n#'\npreProcMultiomics <- function(data.list, db, do.sparse = TRUE) {\n # normalize the data\n data.input.rna <- data.list[[1]]\n data.input.adt <- data.list[[2]]\n data.input.rna = data.input.rna/max(data.input.rna)\n data.input.adt = data.input.adt/max(data.input.adt)\n data.input.adt.temp = data.input.adt\n X = data.input.adt\n for (i in 1:nrow(X)) {\n data.input.adt.temp[i,] = (X[i,]-min(X[i,]))/(max(X[i,])-min(X[i,]))\n }\n data.input.adt[data.input.adt.temp < 0.5] <- 0\n if (do.sparse) {\n data.input = rbind(data.input.rna, as(data.input.adt, \"dgCMatrix\"))\n } else {\n data.input = rbind(as.matrix(data.input.rna), as.matrix(data.input.adt))\n }\n\n # create a new L-R database\n proteins <- rownames(data.input.adt)\n geneInfo.subset <- db$geneInfo[db$geneInfo$AntibodyName %in% proteins, ]\n proteins.nonmapping <- setdiff(proteins, geneInfo.subset$AntibodyName)\n if (length(proteins.nonmapping) > 0) {\n warning(cat(\"The following antibodies are not found in `CellChatDB$geneInfo$AntibodyName`: \", toString(proteins.nonmapping), \"! Please manually add them via the function `updateCellChatDB`. \\n\"))\n }\n out <- extractLRfromGenes(geneSet = geneInfo.subset$Symbol, db)\n LR.use <- out$LR.use\n idx <- match(LR.use$ligand, geneInfo.subset$Symbol)\n LR.use$ligand[!is.na(idx)] <- geneInfo.subset$AntibodyName[idx[!is.na(idx)]]\n idx <- match(LR.use$receptor, geneInfo.subset$Symbol)\n LR.use$receptor[!is.na(idx)] <- geneInfo.subset$AntibodyName[idx[!is.na(idx)]]\n\n db.use <- db\n db.use$interaction <- LR.use\n db.use$geneInfo <- dplyr::add_row(db.use$geneInfo, Symbol = geneInfo.subset$AntibodyName)\n\n return(list(data.input = data.input, db.use = db.use))\n}\n\n\n \n"], ["/CellChat/R/modeling.R", "\n#' Compute the communication probability/strength between any interacting cell groups\n#'\n#' To further speed up on large-scale datasets, USER can downsample the data using the function 'subset' from Seurat package (e.g., pbmc.small <- subset(pbmc, downsample = 500)), or using the function `sketchData` from CellChat, in particular for the large cell clusters;\n#'\n#'\n#' @param object CellChat object\n#' @param type Methods for computing the average gene expression per cell group. By default = \"triMean\", producing fewer but stronger interactions;\n#' When setting `type = \"truncatedMean\"`, a value should be assigned to 'trim', producing more interactions.\n#' @param trim the fraction (0 to 0.25) of observations to be trimmed from each end of x before the mean is computed\n#' @param LR.use A subset of ligand-receptor interactions used in inferring communication network\n#' @param raw.use Whether use the raw data (i.e., `object@data.signaling`) or the smoothed data (i.e., `object@data.smooth`).\n#' Set raw.use = FALSE to use the projected data when analyzing single-cell data with shallow sequencing depth because the projected data could help to reduce the dropout effects of signaling genes, in particular for possible zero expression of subunits of ligands/receptors.\n#' @param population.size Whether consider the proportion of cells in each group across all sequenced cells.\n#' Set population.size = FALSE if analyzing sorting-enriched single cells, to remove the potential artifact of population size.\n#' Set population.size = TRUE if analyzing unsorted single-cell transcriptomes, with the reason that abundant cell populations tend to send collectively stronger signals than the rare cell populations.\n#'\n#' Parameters for spatial data analysis:\n#' @param distance.use Whether to use distance constraints to compute communication probability. Setting `distance.use = TRUE` indicates that the cell-cell communication probability is inversely proportional to the computed distance.\n#' Setting `distance.use = FALSE` will only filter out interactions between spatially distant regions, but not add distance constraints.\n#' @param interaction.range The maximum interaction/diffusion length of ligands (Unit: microns). This hard threshold is used to filter out the connections between spatially distant regions\n#' @param scale.distance A scale or normalization factor for the spatial distances when setting `distance.use = TRUE`. For example, scale.distance equals 1, 0.1, 0.01, 0.001, 0.11, or 0.011. We choose this values such that the minimum value of the scaled distances is in [1,2]. This value is not necessary when setting `distance.use = FALSE`.\n#'\n#' When comparing communication across different CellChat objects, the same scale factor should be used. For a single CellChat analysis, different scale factors will not affect the ranking of the signaling based on their interaction strength.\n#'\n#' @param k.min The minimum number of interacting cell pairs required for defining spatially proximal cell groups.\n#' @param contact.dependent Whether using the `contact-dependent` manner for inference signaling, that is determining interacting cell pairs by requiring cells to be in direct membrane-membrane contact. By default `contact.dependent = TRUE` when inferring contact-dependent and juxtacrine signaling (that is \"Cell-Cell Contact\" signaling classified in CellChatDB$interaction$annotation).\n#' If only focusing on `Secreted Signaling`, the `contact-dependent` manner will be not used except for setting `contact.dependent.forced = TRUE`.\n#' @param contact.range The interaction range (Unit: microns) to restrict the contact-dependent signaling when `contact.dependent = TRUE`.\n#' For spatial transcriptomics in a single-cell resolution, `contact.range` is approximately equal to the estimated cell diameter (i.e., the cell center-to-center distance), which means that contact-dependent and juxtacrine signaling can only happens when the two cells are contact to each other.\n#'\n#' Typically, `contact.range = 10`, which is a typical human cell size. However, for low-resolution spatial data such as 10X visium, it should be the cell center-to-center distance (i.e., `contact.range = 100` for visium data). The function `computeCellDistance` can compute the center-to-center distance.\n#'\n#' @param contact.knn.k Number of neighbors to restrict the contact-dependent signaling within the neatest neighbors when `contact.dependent = TRUE`. By default, CellChat uses `contact.range` to restrict the contact-dependent signaling; however, users can also provide a value of `contact.knn.k`, in order to determine interacting cell pairs based on the k-nearest neighbors (knn).\n#' For 10X visium, contact.knn.k = 6. For other spatial technologies, this value may be hard to determine because the sequenced cells/spots are usually not regularly arranged.\n#' @param do.symmetric Whether converting the adjacent matrix into symmetric one when determining spatially proximal cell groups. Default is TRUE, indicating that if adj(i,j) or adj(j,i) is zero, then both are zeros.\n#'\n#' @param contact.dependent.forced Whether forcing to use the `contact-dependent` manner for inference signaling for all L-R pairs including secreted signaling. Users can set `contact.dependent.forced = TRUE` if also preferring interactions within a contact manner for `Secreted Signaling`.\n#'\n#' @param nboot Threshold of p-values\n#' @param seed.use Set a random seed. By default, set the seed to 1.\n#' @param Kh Parameter in Hill function\n#' @param n Parameter in Hill function\n#'\n#'\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom stats aggregate\n#' @importFrom Matrix crossprod\n#' @importFrom utils txtProgressBar setTxtProgressBar\n#'\n#' @return A CellChat object with updated slot 'net':\n#'\n#' object@net$prob is the inferred communication probability (strength) array, where the first, second and third dimensions represent a source, target and ligand-receptor pair, respectively.\n#'\n#' USER can access all the inferred cell-cell communications using the function 'subsetCommunication(object)', which returns a data frame.\n#'\n#' object@net$pval is the corresponding p-values of each interaction\n#'\n#' @export\n#'\ncomputeCommunProb <- function(object, type = c(\"triMean\", \"truncatedMean\",\"thresholdedMean\", \"median\"), trim = 0.1, LR.use = NULL, raw.use = TRUE, population.size = FALSE,\n distance.use = TRUE, interaction.range = 250, scale.distance = 0.01, k.min = 10, contact.dependent = TRUE, contact.range = NULL, contact.knn.k = NULL, contact.dependent.forced = FALSE, do.symmetric = TRUE,\n nboot = 100, seed.use = 1L, Kh = 0.5, n = 1) {\n type <- match.arg(type)\n cat(type, \"is used for calculating the average gene expression per cell group.\", \"\\n\")\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n thresholdedMean = function(x) thresholdedMean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n if (raw.use) {\n data <- as.matrix(object@data.signaling)\n } else {\n data <- as.matrix(object@data.smooth)\n }\n if (is.null(LR.use)) {\n pairLR.use <- object@LR$LRsig\n } else {\n if (length(unique(LR.use$annotation)) > 1) {\n LR.use$annotation <- factor(LR.use$annotation, levels = c(\"Secreted Signaling\",\"ECM-Receptor\", \"Non-protein Signaling\", \"Cell-Cell Contact\"))\n LR.use <- LR.use[order(LR.use$annotation), , drop = FALSE]\n LR.use$annotation <- as.character(LR.use$annotation)\n }\n pairLR.use <- LR.use\n }\n complex_input <- object@DB$complex\n cofactor_input <- object@DB$cofactor\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n\n ptm = Sys.time()\n\n pairLRsig <- pairLR.use\n group <- object@idents\n geneL <- as.character(pairLRsig$ligand)\n geneR <- as.character(pairLRsig$receptor)\n nLR <- nrow(pairLRsig)\n numCluster <- nlevels(group)\n if (numCluster != length(unique(group))) {\n stop(\"Please check `unique(object@idents)` and ensure that the factor levels are correct!\n You may need to drop unused levels using 'droplevels' function. e.g.,\n `meta$labels = droplevels(meta$labels, exclude = setdiff(levels(meta$labels),unique(meta$labels)))`\")\n }\n\n data.use <- data/max(data)\n nC <- ncol(data.use)\n\n # compute the average expression per group\n data.use.avg <- aggregate(t(data.use), list(group), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n colnames(data.use.avg) <- levels(group)\n # compute the expression of ligand or receptor\n dataLavg <- computeExpr_LR(geneL, data.use.avg, complex_input)\n dataRavg <- computeExpr_LR(geneR, data.use.avg, complex_input)\n # take account into the effect of co-activation and co-inhibition receptors\n dataRavg.co.A.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avg, pairLRsig, type = \"A\")\n dataRavg.co.I.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avg, pairLRsig, type = \"I\")\n dataRavg <- dataRavg * dataRavg.co.A.receptor/dataRavg.co.I.receptor\n\n dataLavg2 <- t(replicate(nrow(dataLavg), as.numeric(table(group))/nC))\n dataRavg2 <- dataLavg2\n\n # compute the expression of agonist and antagonist\n index.agonist <- which(!is.na(pairLRsig$agonist) & pairLRsig$agonist != \"\")\n index.antagonist <- which(!is.na(pairLRsig$antagonist) & pairLRsig$antagonist != \"\")\n # quantify the communication probability\n\n # compute the spatial constraint\n if (object@options$datatype != \"RNA\") {\n data.spatial <- object@images$coordinates\n if (\"spatial.factors\" %in% names(object@images)) {\n ratio <- object@images$spatial.factors$ratio\n tol <- object@images$spatial.factors$tol\n } else {\n stop(\"`object@images$spatial.factors` is missing. Please update the object via `updateCellChat`! \\n\")\n }\n\n meta.t = data.frame(group = group, samples = object@meta$samples, row.names = rownames(object@meta))\n res <- computeRegionDistance(coordinates = data.spatial, meta = meta.t, interaction.range = interaction.range, ratio = ratio, tol = tol, k.min = k.min, contact.dependent = contact.dependent, contact.range = contact.range, contact.knn.k = contact.knn.k)\n d.spatial <- res$d.spatial # NaN if no nearby cell pairs\n adj.contact <- res$adj.contact # zeros if no nearby cell pairs\n if (distance.use) {\n print(paste0('>>> Run CellChat on spatial transcriptomics data using distances as constraints of the computed communication probability <<< [', Sys.time(),']'))\n d.spatial <- d.spatial * scale.distance\n diag(d.spatial) <- NaN\n d.min <- min(d.spatial, na.rm = TRUE)\n if (d.min < 1) {\n cat(\"The suggested minimum value of scaled distances is in [1,2], and the calculated value here is \", d.min,\"\\n\")\n stop(\"Please increase the value of `scale.distance` and use a value that is slighly smaller than \", format(1/d.min, digits = 2) ,\"\\n\")\n }\n P.spatial <- 1/d.spatial\n P.spatial[is.na(d.spatial)] <- 0\n diag(P.spatial) <- max(P.spatial) # if this value is 1, the self-connections will have more larger weight.\n d.spatial <- d.spatial/scale.distance # This is only for saving the data\n } else {\n print(paste0('>>> Run CellChat on spatial transcriptomics data without distance values as constraints of the computed communication probability <<< [', Sys.time(),']'))\n P.spatial <- matrix(1, nrow = numCluster, ncol = numCluster)\n P.spatial[is.na(d.spatial)] <- 0 # diagonal is 1\n }\n\n } else {\n print(paste0('>>> Run CellChat on sc/snRNA-seq data <<< [', Sys.time(),']'))\n d.spatial <- matrix(NaN, nrow = numCluster, ncol = numCluster)\n P.spatial <- matrix(1, nrow = numCluster, ncol = numCluster)\n adj.contact <- matrix(1, nrow = numCluster, ncol = numCluster)\n contact.dependent = FALSE; contact.dependent.forced = FALSE; contact.range = NULL; contact.knn.k = NULL;\n distance.use = NULL; interaction.range = NULL; ratio = NULL; tol = NULL; k.min = NULL;\n }\n\n if (object@options$datatype == \"RNA\") {\n nLR1 <- nLR\n } else {\n if (contact.dependent.forced == TRUE) {\n cat(\"Force to run CellChat in a `contact-dependent` manner for all L-R pairs including secreted signaling.\\n\")\n P.spatial <- P.spatial * adj.contact\n nLR1 <- nLR\n } else { # contact.dependent.forced == F\n if (contact.dependent == TRUE && length(unique(pairLRsig$annotation)) > 0) {\n if (all(unique(pairLRsig$annotation) %in% c(\"Cell-Cell Contact\"))) {\n cat(\"All the input L-R pairs are `Cell-Cell Contact` signaling. Run CellChat in a contact-dependent manner. \\n\")\n P.spatial <- P.spatial * adj.contact\n nLR1 <- nLR\n } else if (all(unique(pairLRsig$annotation) %in% c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\"))) {\n cat(\"Molecules of the input L-R pairs are diffusible. Run CellChat in a diffusion manner based on the `interaction.range`.\\n\")\n nLR1 <- nLR\n } else {\n cat(\"The input L-R pairs have both secreted signaling and contact-dependent signaling. Run CellChat in a contact-dependent manner for `Cell-Cell Contact` signaling, and in a diffusion manner based on the `interaction.range` for other L-R pairs. \\n\")\n nLR1 <- max(which(pairLRsig$annotation %in% c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\")))\n }\n } else { # contact.dependent == F or there is no `annotation` column in the database\n cat(\"Run CellChat in a diffusion manner based on the `interaction.range` for all L-R pairs. Setting `contact.dependent = TRUE` if preferring a contact-dependent manner for `Cell-Cell Contact` signaling. \\n\")\n nLR1 <- nLR\n }\n }\n }\n\n Prob <- array(0, dim = c(numCluster,numCluster,nLR))\n Pval <- array(0, dim = c(numCluster,numCluster,nLR))\n\n set.seed(seed.use)\n permutation <- replicate(nboot, sample.int(nC, size = nC))\n data.use.avg.boot <- my.sapply(\n X = 1:nboot,\n FUN = function(nE) {\n groupboot <- group[permutation[, nE]]\n data.use.avgB <- aggregate(t(data.use), list(groupboot), FUN = FunMean)\n data.use.avgB <- t(data.use.avgB[,-1])\n return(data.use.avgB)\n },\n simplify = FALSE\n )\n pb <- txtProgressBar(min = 0, max = nLR, style = 3, file = stderr())\n\n for (i in 1:nLR) {\n # ligand/receptor\n dataLR <- Matrix::crossprod(matrix(dataLavg[i,], nrow = 1), matrix(dataRavg[i,], nrow = 1))\n P1 <- dataLR^n/(Kh^n + dataLR^n)\n P1_Pspatial <- P1*P.spatial\n if (sum(P1_Pspatial) == 0) {\n Pnull = P1_Pspatial\n Prob[ , , i] <- Pnull\n p = 1\n Pval[, , i] <- matrix(p, nrow = numCluster, ncol = numCluster, byrow = FALSE)\n } else {\n if (i > nLR1) {\n P.spatial <- P.spatial * adj.contact\n }\n # agonist and antagonist\n if (is.element(i, index.agonist)) {\n data.agonist <- computeExpr_agonist(data.use = data.use.avg, pairLRsig, cofactor_input, index.agonist = i, Kh = Kh, n = n)\n P2 <- Matrix::crossprod(matrix(data.agonist, nrow = 1))\n } else {\n P2 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n if (is.element(i, index.antagonist)) {\n data.antagonist <- computeExpr_antagonist(data.use = data.use.avg, pairLRsig, cofactor_input, index.antagonist = i, Kh = Kh, n = n)\n P3 <- Matrix::crossprod(matrix(data.antagonist, nrow = 1))\n } else {\n P3 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n # number of cells\n if (population.size) {\n P4 <- Matrix::crossprod(matrix(dataLavg2[i,], nrow = 1), matrix(dataRavg2[i,], nrow = 1))\n } else {\n P4 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n # Pnull = P1*P2*P3*P4\n Pnull = P1*P2*P3*P4*P.spatial\n Prob[ , , i] <- Pnull\n\n Pnull <- as.vector(Pnull)\n\n #Pboot <- foreach(nE = 1:nboot) %dopar% {\n Pboot <- sapply(\n X = 1:nboot,\n FUN = function(nE) {\n data.use.avgB <- data.use.avg.boot[[nE]]\n dataLavgB <- computeExpr_LR(geneL[i], data.use.avgB, complex_input)\n dataRavgB <- computeExpr_LR(geneR[i], data.use.avgB, complex_input)\n # take account into the effect of co-activation and co-inhibition receptors\n dataRavgB.co.A.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avgB, pairLRsig[i, , drop = FALSE], type = \"A\")\n dataRavgB.co.I.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avgB, pairLRsig[i, , drop = FALSE], type = \"I\")\n dataRavgB <- dataRavgB * dataRavgB.co.A.receptor/dataRavgB.co.I.receptor\n dataLRB = Matrix::crossprod(dataLavgB, dataRavgB)\n P1.boot <- dataLRB^n/(Kh^n + dataLRB^n)\n # agonist and antagonist\n if (is.element(i, index.agonist)) {\n data.agonist <- computeExpr_agonist(data.use = data.use.avgB, pairLRsig, cofactor_input, index.agonist = i, Kh = Kh, n = n)\n P2.boot <- Matrix::crossprod(matrix(data.agonist, nrow = 1))\n } else {\n P2.boot <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n if (is.element(i, index.antagonist)) {\n data.antagonist <- computeExpr_antagonist(data.use = data.use.avgB, pairLRsig, cofactor_input, index.antagonist = i, Kh = Kh, n= n)\n P3.boot <- Matrix::crossprod(matrix(data.antagonist, nrow = 1))\n } else {\n P3.boot <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n if (population.size) {\n groupboot <- group[permutation[, nE]]\n dataLavg2B <- as.numeric(table(groupboot))/nC\n dataLavg2B <- matrix(dataLavg2B, nrow = 1)\n dataRavg2B <- dataLavg2B\n P4.boot = Matrix::crossprod(dataLavg2B, dataRavg2B)\n } else {\n P4.boot = matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n # Pboot = P1.boot*P2.boot*P3.boot*P4.boot\n Pboot = P1.boot*P2.boot*P3.boot*P4.boot*P.spatial\n return(as.vector(Pboot))\n }\n )\n Pboot <- matrix(unlist(Pboot), nrow=length(Pnull), ncol = nboot, byrow = FALSE)\n nReject <- rowSums(Pboot - Pnull > 0)\n p = nReject/nboot\n Pval[, , i] <- matrix(p, nrow = numCluster, ncol = numCluster, byrow = FALSE)\n }\n setTxtProgressBar(pb = pb, value = i)\n }\n close(con = pb)\n Pval[Prob == 0] <- 1\n dimnames(Prob) <- list(levels(group), levels(group), rownames(pairLRsig))\n dimnames(Pval) <- dimnames(Prob)\n net <- list(\"prob\" = Prob, \"pval\" = Pval)\n execution.time = Sys.time() - ptm\n object@options$run.time <- as.numeric(execution.time, units = \"secs\")\n\n object@options$parameter <- list(type.mean = type, trim = trim, raw.use = raw.use, population.size = population.size, nboot = nboot, seed.use = seed.use, Kh = Kh, n = n,\n distance.use = distance.use, interaction.range = interaction.range, ratio = ratio, tol = tol, k.min = k.min,\n contact.dependent = contact.dependent, contact.range = contact.range, contact.knn.k = contact.knn.k, contact.dependent.forced = contact.dependent.forced\n )\n if (object@options$datatype != \"RNA\") {\n object@images$distance <- d.spatial\n }\n object@net <- net\n print(paste0('>>> CellChat inference is done. Parameter values are stored in `object@options$parameter` <<< [', Sys.time(),']'))\n return(object)\n}\n\n\n#' Compute the communication probability on signaling pathway level by summarizing all related ligands/receptors\n#'\n#' @param object CellChat object\n#' @param net A list from object@net; If net = NULL, net = object@net\n#' @param pairLR.use A dataframe giving the ligand-receptor interactions; If pairLR.use = NULL, pairLR.use = object@LR$LRsig\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @return A CellChat object with updated slot 'netP':\n#'\n#' object@netP$prob is the communication probability array on signaling pathway level; USER can convert this array to a data frame using the function 'reshape2::melt()',\n#'\n#' e.g., `df.netP <- reshape2::melt(object@netP$prob, value.name = \"prob\"); colnames(df.netP)[1:3] <- c(\"source\",\"target\",\"pathway_name\")` or access all significant interactions using the function \\code{\\link{subsetCommunication}}\n#'\n#' object@netP$pathways list all the signaling pathways with significant communications.\n#'\n#' From version >= 1.1.0, pathways are ordered based on the total communication probabilities. NB: pathways with small total communication probabilities might be also very important since they might be specifically activated between only few cell types.\n#'\n#' @export\n#'\ncomputeCommunProbPathway <- function(object = NULL, net = NULL, pairLR.use = NULL, thresh = 0.05) {\n if (is.null(net)) {\n net <- object@net\n }\n if (is.null(pairLR.use)) {\n pairLR.use <- object@LR$LRsig\n }\n prob <- net$prob\n prob[net$pval > thresh] <- 0\n\n LR <- dimnames(prob)[[3]]\n LR.sig <- LR[apply(prob, 3, sum) != 0]\n\n pathways <- unique(pairLR.use$pathway_name)\n group <- factor(pairLR.use$pathway_name, levels = pathways)\n prob.pathways <- aperm(apply(prob, c(1, 2), by, group, sum), c(2, 3, 1))\n pathways.sig <- pathways[apply(prob.pathways, 3, sum) != 0]\n prob.pathways.sig <- prob.pathways[,,pathways.sig, drop = FALSE]\n idx <- sort(apply(prob.pathways.sig, 3, sum), decreasing=TRUE, index.return = TRUE)$ix\n pathways.sig <- pathways.sig[idx]\n prob.pathways.sig <- prob.pathways.sig[, , idx]\n\n if (is.null(object)) {\n netP = list(pathways = pathways.sig, prob = prob.pathways.sig)\n return(netP)\n } else {\n object@net$LRs <- LR.sig\n object@netP$pathways <- pathways.sig\n object@netP$prob <- prob.pathways.sig\n return(object)\n }\n}\n\n\n#' Calculate the aggregated network by counting the number of links or summarizing the communication probability\n#'\n#' @param object CellChat object\n#' @param sources.use,targets.use,signaling,pairLR.use Please check the description in function \\code{\\link{subsetCommunication}}\n#' @param remove.isolate whether removing the isolate cell groups without any interactions when applying \\code{\\link{subsetCommunication}}\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param return.object whether return an updated CellChat object\n#' @importFrom dplyr group_by summarize groups\n#' @importFrom stringr str_split\n#'\n#' @return Return an updated CellChat object:\n#'\n#' `object@net$count` is a matrix: rows and columns are sources and targets respectively, and elements are the number of interactions between any two cell groups. USER can convert a matrix to a data frame using the function `reshape2::melt()`\n#'\n#' `object@net$weight` is also a matrix containing the interaction weights between any two cell groups\n#'\n#' `object@net$sum` is deprecated. Use `object@net$weight`\n#'\n#' @export\n#'\naggregateNet <- function(object, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR.use = NULL, remove.isolate = TRUE, thresh = 0.05, return.object = TRUE) {\n net <- object@net\n if (is.null(sources.use) & is.null(targets.use) & is.null(signaling) & is.null(pairLR.use)) {\n prob <- net$prob\n pval <- net$pval\n pval[prob == 0] <- 1\n prob[pval >= thresh] <- 0\n net$count <- apply(prob > 0, c(1,2), sum)\n net$weight <- apply(prob, c(1,2), sum)\n net$weight[is.na(net$weight)] <- 0\n net$count[is.na(net$count)] <- 0\n } else {\n df.net <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.net$source_target <- paste(df.net$source, df.net$target, sep = \"_\")\n df.net2 <- df.net %>% group_by(source_target) %>% summarize(count = n(), .groups = 'drop')\n df.net3 <- df.net %>% group_by(source_target) %>% summarize(prob = sum(prob), .groups = 'drop')\n df.net2$prob <- df.net3$prob\n a <- stringr::str_split(df.net2$source_target, \"_\", simplify = T)\n df.net2$source <- as.character(a[, 1])\n df.net2$target <- as.character(a[, 2])\n cells.level <- levels(object@idents)\n if (remove.isolate) {\n message(\"Isolate cell groups without any interactions are removed. To block it, set `remove.isolate = FALSE`\")\n df.net2$source <- factor(df.net2$source, levels = cells.level[cells.level %in% unique(df.net2$source)])\n df.net2$target <- factor(df.net2$target, levels = cells.level[cells.level %in% unique(df.net2$target)])\n } else {\n df.net2$source <- factor(df.net2$source, levels = cells.level)\n df.net2$target <- factor(df.net2$target, levels = cells.level)\n }\n\n count <- tapply(df.net2[[\"count\"]], list(df.net2[[\"source\"]], df.net2[[\"target\"]]), sum)\n prob <- tapply(df.net2[[\"prob\"]], list(df.net2[[\"source\"]], df.net2[[\"target\"]]), sum)\n net$count <- count\n net$weight <- prob\n net$weight[is.na(net$weight)] <- 0\n net$count[is.na(net$count)] <- 0\n }\n if (return.object) {\n object@net <- net\n return(object)\n } else {\n return(net)\n }\n\n}\n\n\n#' Compute averaged expression values for each cell group\n#'\n#' @param object CellChat object\n#' @param features a char vector giving the used features. default use all features\n#' @param group.by cell group information; default is `object@idents` when input is a single object and `object@idents$joint` when input is a merged object; otherwise it should be one of the column names of the meta slot\n#' @param type methods for computing the average gene expression per cell group.\n#'\n#' By default = \"triMean\", defined as a weighted average of the distribution's median and its two quartiles (https://en.wikipedia.org/wiki/Trimean);\n#'\n#' When setting `type = \"truncatedMean\"`, a value should be assigned to 'trim'. See the function `base::mean`.\n#'\n#' @param trim the fraction (0 to 0.25) of observations to be trimmed from each end of x before the mean is computed.\n#' @param slot.name the data in the slot.name to use\n#' @param data.use a customed data matrix. Default: data.use = NULL and the expression matrix in the 'slot.name' is used\n#'\n#' @return Returns a matrix with genes as rows, cell groups as columns.\n\n#' @export\n#'\ncomputeAveExpr <- function(object, features = NULL, group.by = NULL, type = c(\"triMean\", \"truncatedMean\", \"median\"), trim = NULL,\n slot.name = c(\"data.signaling\", \"data\"), data.use = NULL) {\n type <- match.arg(type)\n slot.name <- match.arg(slot.name)\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n if (is.null(data.use)) {\n data.use <- slot(object, slot.name)\n }\n if (is.null(features)) {\n features.use <- row.names(data.use)\n } else {\n features.use <- intersect(features, row.names(data.use))\n }\n data.use <- data.use[features.use, , drop = FALSE]\n data.use <- as.matrix(data.use)\n\n if (is.null(group.by)) {\n labels <- object@idents\n if (!is.factor(labels)) {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n # compute the average expression per group\n data.use.avg <- aggregate(t(data.use), list(labels), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n rownames(data.use.avg) <- features.use\n colnames(data.use.avg) <- levels(labels)\n return(data.use.avg)\n}\n\n\n\n#' Compute the expression of complex in individual cells using geometric mean\n#' @param complex_input the complex_input from CellChatDB\n#' @param data.use data matrix (row are genes and columns are cells or cell groups)\n#' @param complex the names of complex\n#' @return\n#' @importFrom dplyr select starts_with\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @export\ncomputeExpr_complex <- function(complex_input, data.use, complex) {\n Rsubunits <- complex_input[complex,] %>% dplyr::select(starts_with(\"subunit\"))\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n data.complex = my.sapply(\n X = 1:nrow(Rsubunits),\n FUN = function(x) {\n RsubunitsV <- unlist(Rsubunits[x,], use.names = F)\n RsubunitsV <- RsubunitsV[RsubunitsV != \"\"]\n return(geometricMean(data.use[RsubunitsV, , drop = FALSE]))\n }\n )\n data.complex <- t(data.complex)\n return(data.complex)\n}\n\n# Compute the average expression of complex per cell group using geometric mean\n# @param complex_input the complex_input from CellChatDB\n# @param data.use data matrix (rows are genes and columns are cells)\n# @param complex the names of complex\n# @param group a factor defining the cell groups\n# @param FunMean the function for computing mean expression per group\n# @return\n# @importFrom dplyr select starts_with\n# @importFrom future nbrOfWorkers\n# @importFrom future.apply future_sapply\n# @importFrom pbapply pbsapply\n# #' @export\n.computeExprGroup_complex <- function(complex_input, data.use, complex, group, FunMean) {\n Rsubunits <- complex_input[complex,] %>% dplyr::select(starts_with(\"subunit\"))\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n data.complex = my.sapply(\n X = 1:nrow(Rsubunits),\n FUN = function(x) {\n RsubunitsV <- unlist(Rsubunits[x,], use.names = F)\n RsubunitsV <- RsubunitsV[RsubunitsV != \"\"]\n RsubunitsV <- intersect(RsubunitsV, rownames(data.use))\n if (length(RsubunitsV) > 1) {\n data.avg <- aggregate(t(data.use[RsubunitsV, ,drop = FALSE]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n } else if (length(RsubunitsV) == 1) {\n data.avg <- aggregate(matrix(data.use[RsubunitsV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n } else {\n data.avg = matrix(0, nrow = 1, ncol = length(unique(group)))\n }\n return(geometricMean(data.avg))\n }\n )\n data.complex <- t(data.complex)\n return(data.complex)\n}\n\n#' Compute the expression of ligands or receptors using geometric mean\n#' @param geneLR a char vector giving a set of ligands or receptors\n#' @param data.use data matrix (row are genes and columns are cells or cell groups)\n#' @param complex_input the complex_input from CellChatDB\n# #' @param group a factor defining the cell groups; If NULL, compute the expression of ligands or receptors in individual cells; otherwise, compute the average expression of ligands or receptors per cell group\n# #' @param FunMean the function for computing average expression per cell group\n#' @return\n#' @export\ncomputeExpr_LR <- function(geneLR, data.use, complex_input){\n nLR <- length(geneLR)\n numCluster <- ncol(data.use)\n index.singleL <- which(geneLR %in% rownames(data.use))\n dataL1avg <- data.use[geneLR[index.singleL],]\n dataLavg <- matrix(nrow = nLR, ncol = numCluster)\n dataLavg[index.singleL,] <- dataL1avg\n index.complexL <- setdiff(1:nLR, index.singleL)\n if (length(index.complexL) > 0) {\n complex <- geneLR[index.complexL]\n data.complex <- computeExpr_complex(complex_input, data.use, complex)\n dataLavg[index.complexL,] <- data.complex\n }\n return(dataLavg)\n}\n\n\n#' Modeling the effect of coreceptor on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig a data frame giving ligand-receptor interactions\n#' @param type when type == \"A\", computing expression of co-activation receptor; when type == \"I\", computing expression of co-inhibition receptor.\n#' @return\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @export\ncomputeExpr_coreceptor <- function(cofactor_input, data.use, pairLRsig, type = c(\"A\", \"I\")) {\n type <- match.arg(type)\n if (type == \"A\") {\n coreceptor.all = pairLRsig$co_A_receptor\n } else if (type == \"I\"){\n coreceptor.all = pairLRsig$co_I_receptor\n }\n index.coreceptor <- which(!is.na(coreceptor.all) & coreceptor.all != \"\")\n if (length(index.coreceptor) > 0) {\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n coreceptor <- coreceptor.all[index.coreceptor]\n coreceptor.ind <- cofactor_input[coreceptor, grepl(\"cofactor\" , colnames(cofactor_input) )]\n data.coreceptor.ind = my.sapply(\n X = 1:nrow(coreceptor.ind),\n FUN = function(x) {\n coreceptor.indV <- unlist(coreceptor.ind[x,], use.names = F)\n coreceptor.indV <- coreceptor.indV[coreceptor.indV != \"\"]\n coreceptor.indV <- intersect(coreceptor.indV, rownames(data.use))\n if (length(coreceptor.indV) == 1) {\n return(1 + data.use[coreceptor.indV, ])\n } else if (length(coreceptor.indV) > 1) {\n return(apply(1 + data.use[coreceptor.indV, ], 2, prod))\n } else {\n return(matrix(1, nrow = 1, ncol = ncol(data.use)))\n }\n }\n )\n data.coreceptor.ind <- t(data.coreceptor.ind)\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = ncol(data.use))\n data.coreceptor[index.coreceptor,] <- data.coreceptor.ind\n } else {\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = ncol(data.use))\n }\n return(data.coreceptor)\n}\n\n# Modeling the effect of coreceptor on the ligand-receptor interaction\n#\n# @param data.use data matrix\n# @param cofactor_input the cofactor_input from CellChatDB\n# @param pairLRsig a data frame giving ligand-receptor interactions\n# @param type when type == \"A\", computing expression of co-activation receptor; when type == \"I\", computing expression of co-inhibition receptor.\n# @param group a factor defining the cell groups\n# @param FunMean the function for computing mean expression per group\n# @return\n# @importFrom future nbrOfWorkers\n# @importFrom future.apply future_sapply\n# @importFrom pbapply pbsapply\n# #' @export\n.computeExprGroup_coreceptor <- function(cofactor_input, data.use, pairLRsig, type = c(\"A\", \"I\"), group, FunMean) {\n type <- match.arg(type)\n if (type == \"A\") {\n coreceptor.all = pairLRsig$co_A_receptor\n } else if (type == \"I\"){\n coreceptor.all = pairLRsig$co_I_receptor\n }\n index.coreceptor <- which(!is.na(coreceptor.all) & coreceptor.all != \"\")\n if (length(index.coreceptor) > 0) {\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n coreceptor <- coreceptor.all[index.coreceptor]\n coreceptor.ind <- cofactor_input[coreceptor, grepl(\"cofactor\" , colnames(cofactor_input) )]\n data.coreceptor.ind = my.sapply(\n X = 1:nrow(coreceptor.ind),\n FUN = function(x) {\n coreceptor.indV <- unlist(coreceptor.ind[x,], use.names = F)\n coreceptor.indV <- coreceptor.indV[coreceptor.indV != \"\"]\n coreceptor.indV <- intersect(coreceptor.indV, rownames(data.use))\n if (length(coreceptor.indV) > 1) {\n data.avg <- aggregate(t(data.use[coreceptor.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n return(apply(1 + data.avg, 2, prod))\n # return(1 + apply(data.avg, 2, mean))\n } else if (length(coreceptor.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[coreceptor.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n return(1 + data.avg)\n } else {\n return(matrix(1, nrow = 1, ncol = length(unique(group))))\n }\n }\n )\n data.coreceptor.ind <- t(data.coreceptor.ind)\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = length(unique(group)))\n data.coreceptor[index.coreceptor,] <- data.coreceptor.ind\n } else {\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = length(unique(group)))\n }\n\n return(data.coreceptor)\n}\n\n#' Modeling the effect of agonist on the ligand-receptor interaction\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n#' @param group a factor defining the cell groups\n#' @param index.agonist the index of agonist in the database\n#' @param Kh a parameter in Hill function\n#' @param FunMean the function for computing mean expression per group\n#' @param n Hill coefficient\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExprGroup_agonist <- function(data.use, pairLRsig, cofactor_input, group, index.agonist, Kh, FunMean, n) {\n agonist <- pairLRsig$agonist[index.agonist]\n agonist.ind <- cofactor_input[agonist, grepl(\"cofactor\" , colnames(cofactor_input))]\n agonist.indV <- unlist(agonist.ind, use.names = F)\n agonist.indV <- agonist.indV[agonist.indV != \"\"]\n agonist.indV <- intersect(agonist.indV, rownames(data.use))\n if (length(agonist.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[agonist.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.agonist <- 1 + data.avg^n/(Kh^n + data.avg^n)\n } else if (length(agonist.indV) > 1) {\n data.avg <- aggregate(t(data.use[agonist.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.agonist <- apply(1 + data.avg^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n data.agonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n }\n return(data.agonist)\n}\n\n#' Modeling the effect of antagonist on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n#' @param group a factor defining the cell groups\n#' @param index.antagonist the index of antagonist in the database\n#' @param Kh a parameter in Hill function\n#' @param n Hill coefficient\n#' @param FunMean the function for computing mean expression per group\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExprGroup_antagonist <- function(data.use, pairLRsig, cofactor_input, group, index.antagonist, Kh, FunMean, n) {\n antagonist <- pairLRsig$antagonist[index.antagonist]\n antagonist.ind <- cofactor_input[antagonist, grepl( \"cofactor\" , colnames(cofactor_input) )]\n antagonist.indV <- unlist(antagonist.ind, use.names = F)\n antagonist.indV <- antagonist.indV[antagonist.indV != \"\"]\n antagonist.indV <- intersect(antagonist.indV, rownames(data.use))\n if (length(antagonist.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[antagonist.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.antagonist <- Kh^n/(Kh^n + data.avg^n)\n } else if (length(antagonist.indV) > 1) {\n data.avg <- aggregate(t(data.use[antagonist.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.antagonist <- apply(Kh^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n data.antagonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n }\n return(data.antagonist)\n}\n\n\n#' Modeling the effect of agonist on the ligand-receptor interaction\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n# #' @param group a factor defining the cell groups\n#' @param index.agonist the index of agonist in the database\n#' @param Kh a parameter in Hill function\n# #' @param FunMean the function for computing mean expression per group\n#' @param n Hill coefficient\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExpr_agonist <- function(data.use, pairLRsig, cofactor_input, index.agonist, Kh, n) {\n agonist <- pairLRsig$agonist[index.agonist]\n agonist.ind <- cofactor_input[agonist, grepl(\"cofactor\" , colnames(cofactor_input))]\n agonist.indV <- unlist(agonist.ind, use.names = F)\n agonist.indV <- agonist.indV[agonist.indV != \"\"]\n agonist.indV <- intersect(agonist.indV, rownames(data.use))\n if (length(agonist.indV) == 1) {\n # data.avg <- aggregate(matrix(data.use[agonist.indV,], ncol = 1), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[agonist.indV,, drop = FALSE]\n data.agonist <- 1 + data.avg^n/(Kh^n + data.avg^n)\n } else if (length(agonist.indV) > 1) {\n # data.avg <- aggregate(t(data.use[agonist.indV,]), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[agonist.indV,, drop = FALSE]\n data.agonist <- apply(1 + data.avg^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n # data.agonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n data.agonist = matrix(1, nrow = 1, ncol = ncol(data.use))\n }\n return(data.agonist)\n}\n\n#' Modeling the effect of antagonist on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n# #' @param group a factor defining the cell groups\n#' @param index.antagonist the index of antagonist in the database\n#' @param Kh a parameter in Hill function\n#' @param n Hill coefficient\n# #' @param FunMean the function for computing mean expression per group\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExpr_antagonist <- function(data.use, pairLRsig, cofactor_input, index.antagonist, Kh, n) {\n antagonist <- pairLRsig$antagonist[index.antagonist]\n antagonist.ind <- cofactor_input[antagonist, grepl( \"cofactor\" , colnames(cofactor_input) )]\n antagonist.indV <- unlist(antagonist.ind, use.names = F)\n antagonist.indV <- antagonist.indV[antagonist.indV != \"\"]\n antagonist.indV <- intersect(antagonist.indV, rownames(data.use))\n if (length(antagonist.indV) == 1) {\n # data.avg <- aggregate(matrix(data.use[antagonist.indV,], ncol = 1), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[antagonist.indV,, drop = FALSE]\n data.antagonist <- Kh^n/(Kh^n + data.avg^n)\n } else if (length(antagonist.indV) > 1) {\n # data.avg <- aggregate(t(data.use[antagonist.indV,]), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[antagonist.indV,, drop = FALSE]\n data.antagonist <- apply(Kh^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n # data.antagonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n data.antagonist = matrix(1, nrow = 1, ncol = ncol(data.use))\n }\n return(data.antagonist)\n}\n\n\n#' Compute the geometric mean\n#' @param x a numeric vector\n#' @param na.rm whether remove na\n#' @return\n#' @export\ngeometricMean <- function(x,na.rm=TRUE){\n if (is.null(nrow(x))) {\n exp(mean(log(x),na.rm=na.rm))\n } else {\n exp(apply(log(x),2,mean,na.rm=na.rm))\n }\n}\n\n\n#' Compute the Tukey's trimean\n#' @param x a numeric vector\n#' @param na.rm whether remove na\n#' @return\n#' @importFrom stats quantile\n#' @export\ntriMean <- function(x, na.rm = TRUE) {\n mean(stats::quantile(x, probs = c(0.25, 0.50, 0.50, 0.75), na.rm = na.rm))\n}\n\n#' Compute the average expression per cell group when the percent of expressing cells per cell group larger than a threshold\n#' @param x a numeric vector\n#' @param trim the percent of expressing cells per cell group to be considered as zero\n#' @param na.rm whether remove na\n#' @return\n#' @importFrom Matrix nnzero\n# #' @export\nthresholdedMean <- function(x, trim = 0.1, na.rm = TRUE) {\n percent <- Matrix::nnzero(x)/length(x)\n if (percent < trim) {\n return(0)\n } else {\n return(mean(x, na.rm = na.rm))\n }\n}\n\n#' Filter cell-cell communication if there are only few number of cells in certain cell groups or inconsistent cell-cell communication across samples\n#'\n#' @param object CellChat object\n#' @param min.cells The minmum number of cells required in each cell group for cell-cell communication\n#' @param min.samples The minmum number of samples required for consistent cell-cell communication across samples (that is an interaction present in at least `min.samples` samples) when mutiple samples/replicates/batches are merged as an input for CellChat analysis.\n#' @param rare.keep Whether to keep the interactions associated with the rare populations when min.samples >= 2. When a rare population is identified in the merged samples (say 15 cells in this rare population from two samples), it is likely to filter out the interactions associated with this rare population when setting min.samples >= 2. Setting `rare.keep = TRUE` to retain the identified interactions associated with this rare population.\n#' @param nonFilter.keep Whether to keep the non-filtered cell-cell communication in the CellChat object. This is useful for avoiding re-running `computeCommunProb` if you want to adjust the parameters when running `filterCommunication`.\n#' @return CellChat object with an updated slot net\n#' @export\n#'\nfilterCommunication <- function(object, min.cells = 10, min.samples = NULL, rare.keep = FALSE, nonFilter.keep = FALSE) {\n net <- object@net\n if (nonFilter.keep == TRUE) {\n cat(\"The non-filtered cell-cell communication is stored in `object@net$prob.nonFilter` and `object@net$pval.nonFilter`. \\n\")\n object@net$prob.nonFilter <- net$prob\n object@net$pval.nonFilter <- net$pval\n }\n num.interaction0 <- sum(net$prob > 0)\n cell.excludes <- which(as.numeric(table(object@idents)) <= min.cells)\n if (length(cell.excludes) > 0) {\n cat(\"The cell-cell communication related with the following cell groups are excluded due to the few number of cells: \", toString(levels(object@idents)[cell.excludes]), \"!\",'\\t')\n net$prob[cell.excludes,,] <- 0\n net$prob[,cell.excludes,] <- 0\n num.interaction1 <- sum(net$prob > 0)\n pct.dicrease <- scales::percent((num.interaction0-num.interaction1)/num.interaction0, accuracy = .1)\n cat(paste0(pct.dicrease, \" interactions are removed!\",'\\n'))\n } else {\n num.interaction1 <- num.interaction0\n }\n\n sample.info <- object@meta$samples\n sample.id <- levels(sample.info)\n if (is.null(min.samples)) {\n min.samples <- 1\n } else if (min.samples > length(sample.id)) {\n stop(paste0(\"There are only \", length(sample.id), \" samples in the data. Please change the value of `min.samples`! \"))\n }\n if (length(sample.id) >= 2 & min.samples >= 2) {\n if (object@options$parameter$raw.use == TRUE) {\n data <- as.matrix(object@data.signaling)\n } else {\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n stop(\"`object@data.smooth` is missing. Please update the CellChat object via `updateCellChat`! \\n\")\n }\n data <- as.matrix(object@data.smooth)\n }\n data.use <- data/max(data)\n group <- object@idents\n type <- object@options$parameter$type.mean\n trim <- object@options$parameter$trim\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n thresholdedMean = function(x) thresholdedMean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n LR <- dimnames(net$prob)[[3]]\n idx.nonzero <- which(apply(net$prob, 3, sum) != 0)\n LR.nonzero <- LR[idx.nonzero] # only examine the L-R pairs with nonzero communication probabilities.\n\n interaction_input <- object@DB$interaction\n complex_input <- object@DB$complex\n geneIfo <- object@DB$geneInfo\n idx <- match(LR.nonzero, interaction_input$interaction_name)\n geneL <- as.character(interaction_input$ligand[idx])\n geneR <- as.character(interaction_input$receptor[idx])\n\n geneLR <- c(unique(geneL), unique(geneR))\n geneLR <- extractGeneSubset(geneLR, complex_input, geneIfo)\n data.use <- data.use[rownames(data.use) %in% geneLR, ]\n\n score.LR <- array(0, dim = c(nlevels(group),nlevels(group),length(LR.nonzero), length(sample.id)))\n LR.nonzero.all <- c()\n cell.excludes.sample <- c()\n for (i in 1:length(sample.id)) {\n cell.use <- which(sample.info == sample.id[i])\n group.use <- group[cell.use]\n group.use <- droplevels(group.use)\n # get the rare populations with few cells in each sample\n cell.excludes.sample.i <- which(as.numeric(table(object@idents[cell.use])) <= min.cells)\n cell.excludes.sample <- c(cell.excludes.sample, cell.excludes.sample.i)\n # compute average expression per cell group\n data.use.i <- data.use[, cell.use]\n data.use.avg <- aggregate(t(data.use.i), list(group.use), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n group.exist <- which(levels(group) %in% unique(group.use))\n if (length(group.exist) < nlevels(group)) {\n data.use.avg.temp <- matrix(0, nrow = nrow(data.use), ncol = nlevels(group))\n data.use.avg.temp[ , group.exist] <- data.use.avg\n rownames(data.use.avg.temp) <- rownames(data.use.avg)\n data.use.avg <- data.use.avg.temp\n }\n colnames(data.use.avg) <- levels(group)\n # compute the average expression of ligand or receptor in each cell group\n dataLavg <- computeExpr_LR(geneL, data.use.avg, complex_input)\n dataRavg <- computeExpr_LR(geneR, data.use.avg, complex_input)\n # compute the interaction scores for each ligand-receptor pair based on their expression\n for (jj in 1:length(LR.nonzero)) { # It is not good to use parallel here because it will change the order of LR\n score.LR[,,jj,i] <- Matrix::crossprod(matrix(dataLavg[jj, ], nrow = 1), matrix(dataRavg[jj, ], nrow = 1))\n }\n if (length(cell.excludes.sample.i) > 0) {\n cat(paste0(\"The number of cells of the following cell groups in \", sample.id[i], \" sample are less than \", min.cells, \" cells: \",toString(levels(object@idents)[cell.excludes.sample.i]), \"!\",'\\n'))\n score.LR[cell.excludes.sample.i, , , i] <- 0\n score.LR[ ,cell.excludes.sample.i, , i] <- 0\n }\n #LR.nonzero.all <- c(LR.nonzero.all, LR.nonzero[apply(score.LR[ , , , i], 3, sum) != 0])\n }\n #LR.nonzero.jointOnly <- setdiff(LR.nonzero, unique(LR.nonzero.all))\n\n # get the excluded cell groups that are not observed in the merged data, which is very possible for rare populations\n cell.excludes.sample <- unique(cell.excludes.sample)\n if (length(cell.excludes.sample) > 0) {\n cell.excludes.sample <- setdiff(cell.excludes.sample, cell.excludes)\n }\n\n score.LR[score.LR > 0] <- 1 # binarize the interaction score\n score.LR.consitent <- array(0, dim = c(nlevels(group),nlevels(group),length(LR.nonzero)))\n LR.inconsitent <- c()\n for (jj in 1:length(LR.nonzero)) {\n score.LR.sum <- apply(score.LR[ , , jj, ], c(1,2), sum) # elements 2 and 1 means consistent and inconsistent interactions across samples, respectively.\n # set communication probability to be zero for inconsistent interactions across samples\n if (sum((score.LR.sum > 0) * (score.LR.sum < min.samples)) > 0) {\n #LR.inconsitent <- c(LR.inconsitent, LR.nonzero[jj])\n score.LR.consitent <- (score.LR.sum >= min.samples) * 1\n if (rare.keep == TRUE & length(cell.excludes.sample) > 0) {\n score.LR.consitent[cell.excludes.sample, ] <- 1\n score.LR.consitent[ ,cell.excludes.sample] <- 1\n }\n net$prob[ , , LR.nonzero[jj]] <- net$prob[ , , LR.nonzero[jj]] * score.LR.consitent\n }\n }\n num.interaction2 <- sum(net$prob > 0)\n pct.dicrease <- scales::percent((num.interaction1-num.interaction2)/num.interaction1, accuracy = .1)\n cat(paste0(pct.dicrease, \" interactions are removed due to their inconsistence across \", min.samples, \" samples!\",'\\n'))\n }\n\n object@net <- net\n return(object)\n}\n\n\n#' Identify all the significant interactions (L-R pairs) from some cell groups to other cell groups\n#'\n#' @param object CellChat object\n#' @param from a vector giving the index or the name of source cell groups\n#' @param to a corresponding vector giving the index or the name of target cell groups. Note: The length of 'from' and 'to' must be the same, giving the corresponding pair of cell groups for communication.\n#' @param bidirection whether show the bidirectional communication, i.e., both 'from'->'to' and 'to'->'from'.\n#' @param pair.only whether only return ligand-receptor pairs without pathway names and communication strength\n#' @param pairLR.use0 ligand-receptor pairs to use; default is all the significant interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @return\n#' @export\n#'\nidentifyEnrichedInteractions <- function(object, from, to, bidirection = FALSE, pair.only = TRUE, pairLR.use0 = NULL, thresh = 0.05){\n pairwiseLR <- object@net$pairwiseRank\n if (is.null(pairwiseLR)) {\n stop(\"The interactions between pairwise cell groups have not been extracted!\n Please first run `object <- rankNetPairwise(object)`\")\n }\n group.names.all <- names(pairwiseLR)\n if (!is.numeric(from)) {\n from <- match(from, group.names.all)\n if (sum(is.na(from)) > 0) {\n message(\"Some input cell group names in 'from' do not exist!\")\n from <- from[!is.na(from)]\n }\n }\n if (!is.numeric(to)) {\n to <- match(to, group.names.all)\n if (sum(is.na(to)) > 0) {\n message(\"Some input cell group names in 'to' do not exist!\")\n to <- to[!is.na(to)]\n }\n }\n if (length(from) != length(to)) {\n stop(\"The length of 'from' and 'to' must be the same!\")\n }\n if (bidirection) {\n from2 <- c(from, to)\n to <- c(to, from)\n from <- from2\n }\n if (is.null(pairLR.use0)) {\n k <- 0\n pairLR.use0 <- list()\n for (i in 1:length(from)){\n pairwiseLR_ij <- pairwiseLR[[from[i]]][[to[i]]]\n idx <- pairwiseLR_ij$pval < thresh\n if (length(idx) > 0) {\n k <- k +1\n pairLR.use0[[k]] <- pairwiseLR_ij[idx,]\n }\n }\n pairLR.use0 <- do.call(rbind, pairLR.use0)\n }\n\n k <- 0\n pval <- matrix(nrow = length(rownames(pairLR.use0)), ncol = length(from))\n prob <- pval\n group.names <- c()\n for (i in 1:length(from)) {\n k <- k+1\n pairwiseLR_ij <- pairwiseLR[[from[i]]][[to[i]]]\n pairwiseLR_ij <- pairwiseLR_ij[rownames(pairLR.use0),]\n pval_ij <- pairwiseLR_ij$pval\n prob_ij <- pairwiseLR_ij$prob\n pval_ij[pval_ij > 0.05] = 1\n pval_ij[pval_ij > 0.01 & pval_ij <= 0.05] = 2\n pval_ij[pval_ij <= 0.01] = 3\n prob_ij[pval_ij ==1] <- 0\n pval[,k] <- pval_ij\n prob[,k] <- prob_ij\n group.names <- c(group.names, paste(group.names.all[from[i]], group.names.all[to[i]], sep = \" - \"))\n }\n prob[which(prob == 0)] <- NA\n # remove rows that are entirely NA\n pval <- pval[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n pairLR.use0 <- pairLR.use0[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n prob <- prob[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n if (pair.only) {\n pairLR.use0 <- dplyr::select(pairLR.use0, ligand, receptor)\n }\n return(pairLR.use0)\n}\n\n\n#' Compute the region distance based on the spatial locations of each splot/cell of the spatial transcriptomics\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param meta a data frame including at least two columns named `group` and `samples`. `meta$group` is a factor vector defining the regions/labels of each cell/spot. `meta$samples` is a factor vector defining the sample labels of each dataset.\n#' @param interaction.range The maximum interaction/diffusion range of ligands. This hard threshold is used to filter out the connections between spatially distant regions\n#' @param ratio a numerical vector giving the conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns).\n#'\n#' For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates.\n#' For 10X visium, it is the ratio of the theoretical spot size (i.e., 65um) over the number of pixels that span the diameter of a theoretical spot size in the full-resolution image (i.e., 'spot.size.fullres' in the 'scalefactors_json.json' file).\n#' @param tol a numerical vector giving the tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um.\n#'\n#' For example, for 10X visium, `tol` can be set as `65/2`; for slide-seq, `tol` can be set as `10/2`.\n#' If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance.\n#' @param k.min the minimum number of interacting cell pairs required for defining adjacent cell groups\n#' @param contact.dependent Whether determining spatially proximal cell groups based on either the contact.range or the k-nearest neighbors (knn). By default `contact.dependent = TRUE` when inferring contact-dependent and juxtacrine signaling (including ECM-Receptor and Cell-Cell Contact signaling classified in CellChatDB$interaction$annotation).\n#' If only focusing on `Secreted Signaling`, the `contact.dependent` will be automatically set as FALSE except for `contact.dependent.forced = TRUE`.\n#' @param contact.range The interaction range (Unit: microns) to restrict the contact-dependent signaling.\n#' For spatial transcriptomics in a single-cell resolution, `contact.range` is approximately equal to the estimated cell diameter (i.e., the cell center-to-center distance), which means that contact-dependent and juxtacrine signaling can only happens when the two cells are contact to each other.\n#'\n#' Typically, `contact.range = 10`, which is a typical human cell size. However, for low-resolution spatial data such as 10X visium, it should be the cell center-to-center distance (i.e., `contact.range = 100` for visium data). The function `computeCellDistance` can compute the center-to-center distance.\n#'\n#' @param contact.knn.k Number of neighbors to restrict the contact-dependent signaling within the neatest neighbors. By default, CellChat uses `contact.range` to restrict the contact-dependent signaling; however, users can also provide a value of `contact.knn.k`, in order to determine spatially proximal cell groups based on the k-nearest neighbors (knn).\n#' For 10X visium, contact.knn.k = 6. For other spatial technologies, this value may be hard to determine because the sequenced cells/spots are usually not regularly arranged.\n#' @param do.symmetric Whether converting the adjacent matrix into symmetric one when determining spatially proximal cell groups. Default is TRUE, indicating that if adj(i,j) or adj(j,i) is zero, then both are zeros.\n#'\n#' @importFrom BiocNeighbors queryKNN AnnoyParam\n#' @return A list including a square matrix giving the pairwise region distances and an adjacent matrix indicating physically contacting cell groups based on either the contact.range or the k-nearest neighbors\n#'\n#' @export\ncomputeRegionDistance <- function(coordinates, meta,\n interaction.range = NULL, ratio = NULL, tol = NULL, k.min = 10,\n contact.dependent = TRUE, contact.range = NULL, contact.knn.k = NULL, do.symmetric = TRUE\n) {\n trim <- 0.1\n FunMean <- function(x) mean(x, trim = trim, na.rm = TRUE) # This is used for computing the average distance between two cell groups\n group <- meta$group\n numCluster <- nlevels(group)\n level.use <- levels(group)\n level.use <- level.use[level.use %in% unique(group)]\n samples <- meta$samples\n samples.use <- levels(samples)\n d.spatial <- array(NaN, dim = c(numCluster,numCluster,length(samples.use)))\n adj.spatial <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n adj.contact <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n adj.contact.knn <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n\n if (contact.dependent == TRUE & !is.null(contact.knn.k)) {\n ## find the k-nearest neighbors for each single cell\n # my.knn <- FNN::get.knn(coordinates, k = contact.knn.k)\n # nn.ranked <- my.knn$nn.index # this is a matrix with the size of nCell * contact.knn.k\n nn.ranked <- matrix(NA, nrow = nrow(coordinates), ncol = contact.knn.k)\n for (k in 1:length(samples.use)) {\n idx.k <- which(samples == samples.use[k])\n my.knn <- suppressWarnings(BiocNeighbors::findKNN(coordinates[idx.k, ], k = contact.knn.k, BNPARAM = BiocNeighbors::AnnoyParam(), get.index = TRUE))\n nn.ranked[idx.k, ] <- my.knn$index # this is a matrix with the size of nCell * contact.knn.k\n }\n k.min.contact <- k.min\n } else {\n nn.ranked <- matrix(1, nrow = nrow(coordinates), ncol = 1)\n k.min.contact <- -1 # this produces adj.contact.knn with all elements being 1\n }\n if (contact.dependent == TRUE) {\n if (is.null(contact.range) & is.null(contact.knn.k)) {\n stop(\"Please check the documentation of `computeCommunProb` and provide the value of either `contact.range` or `contact.knn.k`\")\n }\n } else {\n contact.range <- 10000 # this produces adj.contact with all elements being 1\n }\n\n for (k in 1:length(samples.use)) {\n idx.k <- samples == samples.use[k]\n for (i in 1:numCluster) {\n for (j in 1:numCluster) {\n idx.i <- which((group == level.use[i]) & idx.k)\n idx.j <- which((group == level.use[j]) & idx.k)\n if (length(idx.i) == 0 | length(idx.j) == 0) {\n next # if one cell group is missing in one sample, just goes to next loop\n }\n data.spatial.i <- coordinates[idx.i, , drop = FALSE]\n data.spatial.j <- coordinates[idx.j, , drop = FALSE]\n # for each point in the i-th cell group, find its 1-nearest neighbor in the j-th cell group\n #qout <- suppressWarnings(BiocNeighbors::queryKNN(data.spatial.j, data.spatial.i, k = 1, BNPARAM = BiocNeighbors::KmknnParam(), get.index = TRUE))\n qout <- suppressWarnings(BiocNeighbors::queryKNN(data.spatial.j, data.spatial.i, k = 1, BNPARAM = BiocNeighbors::AnnoyParam(), get.index = TRUE))\n # qout$index is an one column matrix with length being `length(idx.i)`, which is the index of the 1-nearest neighbor in the j-th cell group defined by `idx.j`\n # qout$distance is an one column matrix with length being `length(idx.i)`, which is the distance to the 1-nearest neighbor in the j-th cell group defined by `idx.j`\n\n # conver the calculated distance into the distance in micrometers\n qout$distance <- qout$distance*ratio[k]\n # long-range distance\n idx <- qout$distance - interaction.range < tol[k]\n adj.spatial[i,j,k] <- (length(unique(qout$index[idx])) >= k.min) * 1\n # short-range distance based on contact.range\n idx2 <- qout$distance - contact.range < tol[k]\n adj.contact[i,j,k] <- (length(unique(qout$index[idx2])) >= k.min) * 1\n # short-range distance based on knn\n knn.i <- unique(as.vector(nn.ranked[idx.i, ]))\n #adj.contact.knn[i,j,k] <- (length(intersect(knn.i, idx.j)) >= k.min.contact) * 1\n adj.contact.knn[i,j,k] <- (length(intersect(knn.i, unique(qout$index[idx]))) >= k.min.contact) * 1 # knn within the long-range distance\n # computing the average distance between two cell groups\n d.spatial[i,j,k] <- FunMean(qout$distance) # since distances are positive values, different ways for computing the mean have little effects.\n\n }\n }\n }\n\n # merged spatial information from different samples\n d.spatial <- apply(d.spatial, c(1,2), function(x) mean(x, na.rm = TRUE))\n adj.spatial <- apply(adj.spatial, c(1,2), mean)\n adj.contact <- apply(adj.contact, c(1,2), mean)\n adj.contact.knn <- apply(adj.contact.knn, c(1,2), mean)\n # for multi-samples analysis, the following is needed\n adj.spatial[adj.spatial > 0] <- 1\n adj.contact[adj.contact > 0] <- 1\n adj.contact.knn[adj.contact.knn > 0] <- 1\n\n # make these adjacent matrix as symmetric\n if (do.symmetric) {\n adj.spatial <- adj.spatial * t(adj.spatial) # if one is zero, then both are zeros.\n adj.contact <- adj.contact * t(adj.contact) # if one is zero, then both are zeros.\n adj.contact.knn <- adj.contact.knn * t(adj.contact.knn) # if one is zero, then both are zeros.\n }\n d.spatial <- (d.spatial + t(d.spatial))/2\n\n # filter out the spatially distant cell groups\n adj.spatial[adj.spatial == 0] <- NaN\n d.spatial <- d.spatial * adj.spatial\n\n rownames(d.spatial) <- levels(group); colnames(d.spatial) <- levels(group)\n\n if (length(contact.knn.k) > 0) {\n adj.contact = adj.contact.knn\n }\n res <- list(d.spatial = d.spatial, adj.contact = adj.contact)\n return(res)\n\n}\n\n#' Compute cell-cell distance based on the spatial coordinates\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param interaction.range The maximum interaction/diffusion range of ligands. This hard threshold is used to filter out the connections between spatially distant cells\n#' @param ratio The conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns).\n#'\n#' For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates.\n#' For 10X visium, it is the ratio of the theoretical spot size (i.e., 65um) over the number of pixels that span the diameter of a theoretical spot size in the full-resolution image (i.e., 'spot.size.fullres' in the 'scalefactors_json.json' file).\n#' @param tol The tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um.\n#'\n#' For example, for 10X visium, `tol` can be set as `65/2`; for slide-seq, `tol` can be set as `10/2`.\n#' If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance.\n#'\n#' @return an object of class \"dist\" giving the pairwise cell-cell distance\n#' @export\n#'\ncomputeCellDistance <- function(coordinates, interaction.range = NULL, ratio = NULL, tol = NULL){\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n d.spatial <- stats::dist(coordinates)\n if (!is.null(ratio)) {\n d.spatial <- d.spatial*ratio\n }\n\n if(!is.null(interaction.range) & !is.null(tol)){\n message(\"\\n Apply a predefined spatial distance threshold based on the interaction length...\")\n d.spatial[d.spatial > (interaction.range + tol)] <- NaN\n }\n return(d.spatial)\n}\n\n\n"], ["/CellChat/R/CellChat_class.R", "\n#' The CellChat Class\n#'\n#' The CellChat object is created from a single-cell transcriptomic data matrix, Seurat V3 or SingleCellExperiment object.\n#' When inputting an data matrix, it takes a digital data matrices as input. Genes should be in rows and cells in columns. rownames and colnames should be included.\n#' The class provides functions for data preprocessing, intercellular communication network inference, communication network analysis, and visualization.\n#'\n#'\n#'# Class definitions\n#' @importFrom methods setClassUnion\n#' @importClassesFrom Matrix dgCMatrix\nsetClassUnion(name = 'AnyMatrix', members = c(\"matrix\", \"dgCMatrix\"))\nsetClassUnion(name = 'AnyFactor', members = c(\"factor\", \"list\"))\n\n#' The key slots used in the CellChat object are described below.\n#'\n#' @slot data.raw raw count data matrix\n#' @slot data normalized data matrix for CellChat analysis (Genes should be in rows and cells in columns)\n#' @slot data.signaling a subset of normalized matrix only containing signaling genes\n#' @slot data.scale scaled data matrix\n#' @slot data.smooth smoothed data\n#' @slot images a list of information of spatial transcriptomics data\n#' @slot net a three-dimensional array P (K×K×N), where K is the number of cell groups and N is the number of ligand-receptor pairs. Each row of P indicates the communication probability originating from the sender cell group to other cell groups.\n#' @slot netP a three-dimensional array representing cel-cell communication networks on a signaling pathway level\n#' @slot DB ligand-receptor interaction database used in the analysis (a subset of CellChatDB)\n#' @slot LR a list of information related with ligand-receptor pairs\n#' @slot meta data frame storing the information associated with each cell\n#' @slot idents a factor defining the cell identity used for all analysis. It becomes a list for a merged CellChat object\n#' @slot var.features A list: one element is a vector consisting of the identified over-expressed signaling genes; one element is a data frame returned from the differential expression analysis\n#' @slot dr List of the reduced 2D coordinates, one per method, e.g., umap/tsne/dm\n#' @slot options List of miscellaneous data, such as parameters used throughout analysis, and a indicator whether the CellChat object is a single or merged\n#'\n#' @exportClass CellChat\n#' @importFrom Rcpp evalCpp\n#' @importFrom methods setClass\n# #' @useDynLib CellChat\nCellChat <- methods::setClass(\"CellChat\",\n slots = c(data.raw = 'AnyMatrix',\n data = 'AnyMatrix',\n data.signaling = \"AnyMatrix\",\n data.scale = \"matrix\",\n data.smooth = \"AnyMatrix\",\n images = \"list\",\n net = \"list\",\n netP = \"list\",\n meta = \"data.frame\",\n idents = \"AnyFactor\",\n DB = \"list\",\n LR = \"list\",\n var.features = \"list\",\n dr = \"list\",\n options = \"list\")\n)\n#' show method for CellChat\n#'\n#' @param CellChat object\n#' @param show show the object\n#' @param object object\n#' @docType methods\n#'\nsetMethod(f = \"show\", signature = \"CellChat\", definition = function(object) {\n if (object@options$mode == \"single\") {\n cat(\"An object of class\", class(object), \"created from a single dataset\", \"\\n\", nrow(object@data), \"genes.\\n\", ncol(object@data), \"cells. \\n\")\n } else if (object@options$mode == \"merged\") {\n cat(\"An object of class\", class(object), \"created from a merged object with multiple datasets\", \"\\n\", nrow(object@data.signaling), \"signaling genes.\\n\", ncol(object@data.signaling), \"cells. \\n\")\n }\n if (object@options$datatype == \"RNA\") {\n cat(\"CellChat analysis of single cell RNA-seq data! \\n\")\n } else {\n cat(\"CellChat analysis of\", object@options$datatype, \"data! The input spatial locations are \\n\")\n print(head(object@images$coordinates))\n }\n\n\n invisible(x = NULL)\n})\n\n\n\n#' Create a new CellChat object from a data matrix, Seurat or SingleCellExperiment object\n#'\n#' @param object a normalized (NOT count) data matrix (genes by cells), Seurat or SingleCellExperiment object\n#' @param meta a data frame (rows are cells with rownames) consisting of cell information, which will be used for defining cell groups.\n#' If input is a Seurat or SingleCellExperiment object, the meta data in the object will be used\n#' @param group.by a char name of the variable in meta data, defining cell groups.\n#' If input is a data matrix and group.by is NULL, the input `meta` should contain a column named 'labels',\n#' If input is a Seurat or SingleCellExperiment object, USER must provide `group.by` to define the cell groups. e.g, group.by = \"ident\" for Seurat object\n#' @param datatype By default datatype = \"RNA\"; when running CellChat on spatial imaging data, set datatype = \"spatial\" and input `spatial.factors`\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param spatial.factors a data frame containing two distance factors `ratio` and `tol`, which is dependent on spatial transcriptomics technologies (and specific datasets).\n#'\n#' USER must input this data frame when datatype = \"spatial\". spatial.factors must contain an element named `ratio`, which is the conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns). For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates,\n#'\n#' and another element named `tol`, which is the tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um. If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the cell center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance. Of note, CellChat does not need an accurate tolerance factor, which is used for determining whether considering the cell-pair as spatially proximal if their distance is greater than `interaction.range` but smaller than \"`interaction.range` + `tol`\".\n#'\n#'\n#' @param assay Assay to use when the input is a Seurat or SingleCellExperiment object. NB: The data in the `integrated` assay in Seurat is not suitable for CellChat analysis because it contains negative values.\n#' @param do.sparse whether use sparse format\n#'\n#' @return\n#' @export\n#' @importFrom methods as new\n#' @examples\n#' \\dontrun{\n#' Create a CellChat object from single-cell transcriptomics data\n#' # Input is a data matrix\n#' ## create a dataframe consisting of the cell labels\n#' meta = data.frame(labels = cell.labels, row.names = names(cell.labels))\n#' cellChat <- createCellChat(object = data.input, meta = meta, group.by = \"labels\")\n#'\n#' # input is a Seurat object\n#' ## use the default cell identities of Seurat object\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"ident\", assay = \"RNA\")\n#' ## use other meta information as cell groups\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"seurat.clusters\")\n#'\n#' # input is a SingleCellExperiment object\n#' cellChat <- createCellChat(object = sce.obj, group.by = \"sce.clusters\")\n#'\n#' # input is a AnnData object\n#' sce <- zellkonverter::readH5AD(file = \"adata.h5ad\")\n#' assayNames(sce) # retrieve all the available assays within sce object\n#' counts <- assay(sce, \"X\") # add a new assay entry \"logcounts\" if not available and make sure this is the original count data matrix\n#' library.size <- Matrix::colSums(counts)\n#' logcounts(sce) <- log1p(Matrix::t(Matrix::t(counts)/library.size) * 10000)\n#' meta <- as.data.frame(SingleCellExperiment::colData(sce))\n#' cellChat <- createCellChat(object = sce, group.by = \"sce.clusters\")\n#'\n#'\n#' Create a CellChat object from spatial transcriptomics data\n#' # Input is a data matrix\n#' cellChat <- createCellChat(object = data.input, meta = meta, group.by = \"labels\",\n#' datatype = \"spatial\", coordinates = coordinates, spatial.factors = spatial.factors)\n#'\n#' # input is a Seurat object\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"ident\", assay = \"SCT\",\n#' datatype = \"spatial\", spatial.factors = spatial.factors)\n#'\n#' }\ncreateCellChat <- function(object, meta = NULL, group.by = NULL,\n datatype = c(\"RNA\", \"spatial\"), coordinates = NULL, spatial.factors = NULL,\n assay = NULL, do.sparse = T) {\n datatype <- match.arg(datatype)\n # data matrix as input\n if (inherits(x = object, what = c(\"matrix\", \"Matrix\", \"dgCMatrix\", \"dgRMatrix\",\"CsparseMatrix\"))) {\n print(\"Create a CellChat object from a data matrix\")\n data <- object\n if (is.null(group.by)) {\n group.by <- \"labels\"\n }\n }\n # Seurat object as input\n if (is(object,\"Seurat\")) {\n .error_if_no_Seurat()\n print(\"Create a CellChat object from a Seurat object\")\n if (is.null(assay)) {\n assay = Seurat::DefaultAssay(object)\n if (assay == \"integrated\") {\n warning(\"The data in the `integrated` assay is not suitable for CellChat analysis! Please use the `RNA`, `SCT` or `Spatial` assay! \")\n }\n cat(paste0(\"The `data` slot in the default assay is used. The default assay is \", assay),'\\n')\n }\n if (packageVersion(\"Seurat\") < \"5.0.0\") {\n # data <- Seurat::GetAssayData(object, assay = assay, slot = \"data\") # normalized data matrix\n data <- object[[assay]]@data\n } else {\n data <- object[[assay]]$data\n }\n if (min(data) < 0) {\n stop(\"The data matrix contains negative values. Please ensure the normalized data matrix is used.\")\n }\n if (is.null(meta)) {\n cat(\"The `meta.data` slot in the Seurat object is used as cell meta information\",'\\n')\n meta <- object@meta.data\n meta$ident <- Seurat::Idents(object)\n }\n if (is.null(group.by)) {\n group.by <- \"ident\"\n }\n if (datatype %in% c(\"spatial\")) {\n if (is.null(coordinates)) {\n coordinates <- Seurat::GetTissueCoordinates(object, scale = NULL, cols = c(\"imagerow\", \"imagecol\"))\n }\n }\n\n\n }\n # SingleCellExperiment object as input\n if (is(object,\"SingleCellExperiment\")) {\n print(\"Create a CellChat object from a SingleCellExperiment object\")\n if (is.null(assay)) {\n assay = \"logcounts\"\n }\n if (assay %in% SummarizedExperiment::assayNames(object)) {\n cat(paste0(\"The data in the \", assay, \" assay is used! \"),'\\n')\n data <- SummarizedExperiment::assay(object, assay)\n } else {\n stop(\"SingleCellExperiment object must contain an assay named `logcounts` or the input assay name! Please check the available assaynames via `assayNames(object)`. \\n\")\n }\n if (is.null(meta)) {\n cat(\"The `colData` assay in the SingleCellExperiment object is used as cell meta information\",'\\n')\n meta <- as.data.frame(SingleCellExperiment::colData(object))\n }\n if (is.null(group.by)) {\n stop(\"`group.by` should be defined!\")\n }\n }\n\n if (!inherits(x = data, what = c(\"dgCMatrix\")) & do.sparse) {\n if (inherits(x = data, what = c(\"dgRMatrix\"))) {\n data <- as(data, \"CsparseMatrix\")\n }\n data <- as(data, \"dgCMatrix\")\n }\n\n if (!is.null(meta)) {\n if (inherits(x = meta, what = c(\"matrix\", \"Matrix\",\"DataFrame\"))) {\n meta <- as.data.frame(x = meta)\n }\n if (!is.data.frame(meta)) {\n stop(\"The input `meta` should be a data frame\")\n }\n if (!identical(rownames(meta), colnames(data))) {\n cat(\"The cell barcodes in 'meta' is \", head(rownames(meta)),'\\n')\n warning(\"The cell barcodes in 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of 'mata'!\")\n rownames(meta) <- colnames(data)\n }\n } else {\n meta <- data.frame()\n }\n if (datatype %in% c(\"spatial\")) {\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n if (is.null(spatial.factors) | !(\"ratio\" %in% names(spatial.factors)) | !(\"tol\" %in% names(spatial.factors))) {\n stop(\"spatial.factors with colnames `ratio` and `tol` should be provided!\")\n } else {\n images = list(\"coordinates\" = coordinates,\n \"spatial.factors\" = spatial.factors)\n }\n cat(\"Create a CellChat object from spatial transcriptomics data...\",'\\n')\n } else {\n images <- list()\n }\n\n object <- methods::new(Class = \"CellChat\",\n data = data,\n images = images,\n meta = meta)\n\n if (!is.null(meta) & nrow(meta) > 0) {\n if (!(\"samples\" %in% colnames(meta))) {\n warning(\"The 'meta' data does not have a column named `samples`. We now add this column and all cells are assumed to belong to `sample1`! \\n\")\n meta$samples <- \"sample1\"\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n } else if (is.factor(meta$samples) == FALSE) {\n warning(\"The 'meta$samples' is not a factor. We now force it as a factor! \\n\")\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n }\n\n cat(\"Set cell identities for the new CellChat object\", '\\n')\n if (!(group.by %in% colnames(meta))) {\n stop(\"The 'group.by' is not a column name in the `meta`, which will be used for cell grouping.\")\n }\n object <- setIdent(object, ident.use = group.by) # set \"labels\" as default cell identity\n cat(\"The cell groups used for CellChat analysis are \", toString(levels(object@idents)), '\\n')\n }\n\n object@options$mode <- \"single\"\n object@options$datatype <- datatype\n return(object)\n}\n\n\n#' Merge CellChat objects\n#'\n#' @param object.list A list of multiple CellChat objects\n#' @param add.names A vector containing the name of each dataset\n#' @param merge.data whether merging the data for ALL genes. Default only merges the data of signaling genes\n#' @param cell.prefix whether prefix cell names\n#' @importFrom methods slot new\n#'\n#' @return\n#' @export\n#'\n#' @examples\nmergeCellChat <- function(object.list, add.names = NULL, merge.data = FALSE, cell.prefix = FALSE) {\n if (is.null(add.names)) {\n add.names <- paste(\"Dataset\",1:length(object.list),sep = \"_\")\n }\n slot.name <- c(\"net\", \"netP\", \"idents\" ,\"LR\", \"var.features\", \"images\")\n slot.combined <- vector(\"list\", length(slot.name))\n names(slot.combined) <- slot.name\n for (i in 1:length(slot.name)) {\n object.slot <- vector(\"list\", length(object.list))\n for (j in 1:length(object.list)) {\n object.slot[[j]] <- slot(object.list[[j]], slot.name[i])\n }\n slot.combined[[i]] <- object.slot\n names(slot.combined[[i]]) <- add.names\n }\n\n if (cell.prefix) {\n warning(\"Prefix cell names!\")\n for (i in 1:length(object.list)) {colnames(object.list[[i]]@data) <- paste(colnames(object.list[[i]]@data), add.names[i], sep = \"_\")}\n } else {\n cell.names <- c()\n for (i in 1:length(object.list)) {\n cell.names <- c(cell.names, colnames(object.list[[i]]@data))\n }\n if (sum(duplicated(cell.names))) {\n stop(\"Duplicated cell names were detected across datasets!! Please set cell.prefix = TRUE\")\n }\n }\n\n meta.use <- colnames(object.list[[1]]@meta)\n for (i in 2:length(object.list)) {\n meta.use <- meta.use[meta.use %in% colnames(object.list[[i]]@meta)]\n }\n\n dataset.name <- c()\n cell.names <- c()\n meta.joint <- data.frame()\n for (i in 1:length(object.list)) {\n dataset.name <- c(dataset.name, rep(add.names[i], length(colnames(object.list[[i]]@data))))\n cell.names <- c(cell.names, colnames(object.list[[i]]@data))\n meta.joint <- rbind(meta.joint, object.list[[i]]@meta[ , meta.use, drop = FALSE])\n }\n if (!identical(rownames(meta.joint), cell.names)) {\n cat(\"The cell barcodes in merged 'meta' is \", head(rownames(meta.joint)),'\\n')\n warning(\"The cell barcodes in merged 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of merged 'mata'!\")\n rownames(meta.joint) <- cell.names\n }\n\n #dataset.name <- data.frame(dataset.name = dataset.name, row.names = cell.names)\n meta.joint$datasets <- factor(dataset.name, levels = add.names)\n\n genes.use <- rownames(object.list[[1]]@data)\n for (i in 2:length(object.list)) {\n genes.use <- genes.use[genes.use %in% rownames(object.list[[i]]@data)]\n }\n data.joint <- c()\n for (i in 1:length(object.list)) {\n data.joint <- cbind(data.joint, object.list[[i]]@data[genes.use, ])\n }\n gene.signaling.joint = unique(unlist(lapply(object.list, function(x) rownames(x@data.signaling))))\n data.signaling.joint <- data.joint[rownames(data.joint) %in% gene.signaling.joint, ]\n\n idents.joint <- c()\n idents.levels <- c()\n for (i in 1:length(object.list)) {\n idents.joint <- c(idents.joint, as.character(object.list[[i]]@idents))\n idents.levels <- union(idents.levels, levels(object.list[[i]]@idents))\n }\n names(idents.joint) <- cell.names\n idents.joint <- factor(idents.joint, levels = idents.levels)\n slot.combined$idents$joint <- idents.joint\n\n if (merge.data) {\n message(\"Merge the following slots: 'data','data.signaling','images','net', 'netP','meta', 'idents', 'var.features', 'DB', and 'LR'.\")\n merged.object <- methods::new(\n Class = \"CellChat\",\n data = data.joint,\n data.signaling = data.signaling.joint,\n images = slot.combined$images,\n net = slot.combined$net,\n netP = slot.combined$netP,\n meta = meta.joint,\n idents = slot.combined$idents,\n var.features = slot.combined$var.features,\n LR = slot.combined$LR,\n DB = object.list[[1]]@DB)\n } else {\n message(\"Merge the following slots: 'data.signaling','images','net', 'netP','meta', 'idents', 'var.features' , 'DB', and 'LR'.\")\n merged.object <- methods::new(\n Class = \"CellChat\",\n data.signaling = data.signaling.joint,\n images = slot.combined$images,\n net = slot.combined$net,\n netP = slot.combined$netP,\n meta = meta.joint,\n idents = slot.combined$idents,\n var.features = slot.combined$var.features,\n LR = slot.combined$LR,\n DB = object.list[[1]]@DB)\n }\n merged.object@options$mode <- \"merged\"\n\n datatype.joint <- c()\n for (j in 1:length(object.list)) {\n datatype.joint <- union(datatype.joint, slot(object.list[[j]], \"options\")$datatype)\n }\n if (length(datatype.joint) == 1){\n merged.object@options$datatype <- datatype.joint\n } else {\n message(\"The data types in these objects are \", datatype.joint,'\\n')\n stop(\"Comparison analysis is not suggested for different types of data.\")\n }\n return(merged.object)\n}\n\n\n\n#' Update a single CellChat object\n#'\n#' Update a single previously calculated CellChat object for spatial transcriptomics data analysis (version < 2.1.0)\n#'\n#' Update a single previously calculated CellChat object (version < 1.6.0)\n#'\n#' version < 0.5.0: `object@var.features` is now `object@var.features$features`; `object@net$sum` is now `object@net$weight` if `aggregateNet` has been run.\n#'\n#' version 1.6.0: a `object@images` slot is added and `datatype` is added in `object@options$datatype`\n#'\n#' version 2.1.0: a column named `slices` is added in `meta` data for spatial transcriptomics data analysis.\n#'\n#' version 2.1.1: `images$scale.factors` is changed to `images$spatial.factors` for spatial transcriptomics data analysis.\n#'\n#' version 2.1.2: the column `slices` in `object@meta` is renamed as `samples` in order to identify consistent signaling across samples for cell-cell communication analysis.\n#'\n#' version 2.1.3: the slot `object@data.project` is renamed as `object@data.smooth`.\n#'\n#' @param object CellChat object\n#'\n#' @return a updated CellChat object\n#' @export\n#'\nupdateCellChat <- function(object) {\n DB <- object@DB\n # interaction_input <- DB$interaction\n # if ((\"category\" %in% colnames(interaction_input) == FALSE) & (\"annotation\" %in% colnames(interaction_input) == TRUE)) {\n # message(\"Change the column name `annotation` in object@DB$interaction to `category` since CellChat v2\")\n # colnames(interaction_input) <- plyr::mapvalues(colnames(interaction_input),from = c(\"annotation\"), to = c(\"category\"), warn_missing = TRUE)\n # DB$interaction <- interaction_input\n # }\n if (is.character(object@var.features)) {\n message(\"Update slot 'var.features' from a vector to a list\")\n var.features.new <- list(features = object@var.features)\n } else {\n var.features.new <- object@var.features\n }\n if (\"sum\" %in% names(object@net)) {\n net <- object@net\n net$weight <- net$sum\n } else {\n net <- object@net\n }\n if (!(\"mode\" %in% names(object@options))) {\n object@options$mode <- \"single\"\n }\n if (!(\"datatype\" %in% names(object@options))) {\n object@options$datatype <- \"RNA\"\n images = list()\n } else {\n images = object@images\n }\n meta = object@meta\n if (\"slices\" %in% colnames(meta)) {\n meta$samples <- meta$slices\n meta$slices = NULL\n }\n if (!(\"samples\" %in% colnames(meta))) {\n warning(\"The 'meta' data does not have a column named `samples`. We now add this column and all cells are assumed to belong to `sample1`!\")\n meta$samples <- \"sample1\"\n meta$samples <- factor(meta$samples)\n } else if (is.factor(meta$samples) == FALSE) {\n warning(\"The 'meta$samples' is not a factor. We now force it as a factor!\")\n meta$samples <- factor(meta$samples)\n }\n if (object@options$datatype %in% c(\"spatial\")) {\n if (\"scale.factors\" %in% names(object@images)) {\n images$spatial.factors <- as.data.frame(images$scale.factors)\n images$scale.factors <- NULL\n }\n }\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n data.smooth <- object@data.project\n } else {\n data.smooth <- object@data.smooth\n }\n object.new <- methods::new(\n Class = \"CellChat\",\n data.raw = object@data.raw,\n data = object@data,\n data.signaling = object@data.signaling,\n data.scale = object@data.scale,\n data.smooth = data.smooth,\n images = images,\n net = net,\n netP = object@netP,\n meta = meta,\n idents = object@idents,\n DB = DB,\n LR = object@LR,\n var.features = var.features.new,\n dr = object@dr,\n options = object@options\n )\n return(object.new)\n}\n\n#' Update a CellChat object by lifting up the cell groups to the same cell labels across all datasets\n#'\n#' This function is useful when comparing inferred communications across different datasets with different cellular compositions\n#'\n#' @param object A single or merged CellChat object\n#' @param group.new A char vector giving the cell labels to lift up. The order of cell labels in the vector will be used for setting the new cell identity.\n#'\n#' If the input is a merged CellChat object and group.new = NULL, it will use the cell labels from one dataset with the maximum number of cell groups\n#'\n#' If the input is a single CellChat object, `group.new` must be defined.\n#'\n#' @return a updated CellChat object\n#'\n#' @export\n#'\nliftCellChat <- function(object, group.new = NULL) {\n if (object@options$mode == \"merged\") {\n idents <- object@idents[1:(length(object@idents)-1)]\n if (is.null(group.new)) {\n group.max.all <- unique(unlist(sapply(idents, levels)))\n group.num <- sapply(idents, nlevels)\n group.num.max <- max(group.num)\n group.max <- levels(idents[[which(group.num == group.num.max)]])\n if (length(group.max) != length(group.max.all)) {\n stop(\"CellChat object cannot lift up due to the missing cell groups in any dataset. Please define the parameter `group.new`!\")\n }\n } else {\n group.max <- group.new\n group.num.max <- length(group.new)\n }\n message(paste0(\"The CellChat object will be lifted up using the cell labels \", paste(group.max, collapse=\", \")))\n for (i in 1:length(idents)) {\n cat(\"Update slots object@net, object@netP, object@idents in dataset \", names(object@idents)[i],'\\n')\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net[[i]]\n group.i <- levels(idents[[i]])\n # group.existing <- group.max[group.max %in% group.i]\n group.existing <- group.i[group.i %in% group.max]\n group.existing.index <- which(group.max %in% group.existing)\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max),\n dimnames = list(group.max, group.max))\n values.new[group.existing.index, group.existing.index] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"pairwiseRank\")) {\n for (k in 1:length(values)) {\n values.new1 <- vector(\"list\", group.num.max)\n values.new1[group.existing.index] <- values[[k]]\n temp <- values[[k]][[1]]\n temp$prob <- 0; temp$pval <- 1\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new1[[kk]] <- temp\n }\n names(values.new1) <- group.max\n values[[k]] <- values.new1\n }\n values.new <- vector(\"list\", group.num.max)\n values.new[group.existing.index] <- values\n temp <- lapply(values.new1, function(x) {\n x$prob <- 0; x$pval <- 1\n return(x)\n })\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new[[kk]] <- temp\n }\n names(values.new) <- group.max\n }\n net[[net.j]] <- values.new\n }\n object@net[[i]] <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n netP <- object@netP[[i]]\n for (netP.j in names(netP)) {\n values <- netP[[netP.j]]\n if (netP.j %in% c(\"pathways\")) {\n values.new <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"prob\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"centr\")) {\n for (k in 1:length(values)) {\n values.new <- lapply(values, function(x) {\n values.new2 <- lapply(x, function(x) {\n values.new1 = as.vector(matrix(0, nrow = 1, ncol = group.num.max))\n values.new1[group.existing.index] <- x\n names(values.new1) <- group.max\n return(values.new1)\n })\n names(values.new2) <- names(x)\n return(values.new2)\n })\n names(values.new) <- names(values)\n }\n netP[[netP.j]] <- values.new\n }\n\n }\n object@netP[[i]] <- netP\n # cat(\"Update slot object@idents...\", '\\n')\n # idents[[i]] <- factor(group.max, levels = group.max)\n idents[[i]] <- factor(idents[[i]], levels = group.max)\n }\n object@idents[1:(length(object@idents)-1)] <- idents\n } else {\n if (is.null(group.new)) {\n stop(\"Please define the parameter `group.new`!\")\n } else {\n group.max <- as.character(group.new)\n group.num.max <- length(group.new)\n message(paste0(\"The CellChat object will be lifted up using the cell labels \", paste(group.max, collapse=\", \")))\n }\n cat(\"Update slots object@net, object@netP, object@idents in a single dataset...\", '\\n')\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net\n idents <- object@idents\n group.i <- levels(idents)\n # group.existing <- group.max[group.max %in% group.i]\n group.existing <- group.i[group.i %in% group.max]\n group.existing.index <- which(group.max %in% group.existing)\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max),\n dimnames = list(group.max, group.max))\n values.new[group.existing.index, group.existing.index] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"pairwiseRank\")) {\n for (k in 1:length(values)) {\n values.new1 <- vector(\"list\", group.num.max)\n values.new1[group.existing.index] <- values[[k]]\n temp <- values[[k]][[1]]\n temp$prob <- 0; temp$pval <- 1\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new1[[kk]] <- temp\n }\n names(values.new1) <- group.max\n values[[k]] <- values.new1\n }\n values.new <- vector(\"list\", group.num.max)\n values.new[group.existing.index] <- values\n temp <- lapply(values.new1, function(x) {\n x$prob <- 0; x$pval <- 1\n return(x)\n })\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new[[kk]] <- temp\n }\n names(values.new) <- group.max\n }\n net[[net.j]] <- values.new\n }\n object@net <- net\n\n\n # cat(\"Update slot object@netP...\", '\\n')\n netP <- object@netP\n for (netP.j in names(netP)) {\n values <- netP[[netP.j]]\n if (netP.j %in% c(\"pathways\")) {\n values.new <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"prob\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"centr\")) {\n for (k in 1:length(values)) {\n values.new <- lapply(values, function(x) {\n values.new2 <- lapply(x, function(x) {\n values.new1 = as.vector(matrix(0, nrow = 1, ncol = group.num.max))\n values.new1[group.existing.index] <- x\n names(values.new1) <- group.max\n return(values.new1)\n })\n names(values.new2) <- names(x)\n return(values.new2)\n })\n names(values.new) <- names(values)\n }\n }\n netP[[netP.j]] <- values.new\n }\n object@netP <- netP\n\n # cat(\"Update slot object@idents...\", '\\n')\n idents <- factor(idents, levels = group.max)\n object@idents <- idents\n }\n\n return(object)\n}\n\n\n#' Subset CellChat object using a portion of cells\n#'\n#' @param object A CellChat object (either an object from a single dataset or a merged objects from multiple datasets)\n#' @param cells.use a char vector giving the cell barcodes to subset. If cells.use = NULL, USER must define `idents.use`\n#' @param idents.use a subset of cell groups used for analysis\n#' @param group.by cell group information; default is `object@idents`; otherwise it should be one of the column names of the meta slot\n#' @param invert whether invert the idents.use\n#' @param thresh threshold of the p-value for determining significant interaction. A parameter as an input of the function `computeCommunProbPathway`\n#' @importFrom methods slot new\n#'\n#' @return\n#' @export\n#'\nsubsetCellChat <- function(object, cells.use = NULL, idents.use = NULL, group.by = NULL, invert = FALSE, thresh = 0.05) {\n if (!is.null(idents.use)) {\n if (is.null(group.by)) {\n labels <- object@idents\n if (object@options$mode == \"merged\") {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n level.use0 <- levels(labels)\n level.use <- levels(labels)[levels(labels) %in% unique(labels)]\n\n if (invert) {\n level.use <- level.use[!(level.use %in% idents.use)]\n } else {\n level.use <- level.use[level.use %in% idents.use]\n }\n cells.use.index <- which(as.character(labels) %in% level.use)\n cells.use <- names(labels)[cells.use.index]\n } else if (!is.null(cells.use)) {\n labels <- object@idents\n if (object@options$mode == \"merged\") {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n level.use0 <- levels(labels)\n level.use <- levels(labels)[levels(labels) %in% unique(as.character(labels[cells.use]))]\n cells.use.index <- which(names(labels) %in% cells.use)\n } else {\n stop(\"USER should define either `cells.use` or `idents.use`!\")\n }\n cat(\"The subset of cell groups used for CellChat analysis are \", level.use, '\\n')\n\n if (nrow(object@data) > 0) {\n data.subset <- object@data[, cells.use.index]\n } else {\n data.subset <- matrix(0, nrow = 0, ncol = 0)\n }\n if (nrow(object@data.smooth) > 0) {\n data.smooth.subset <- object@data.smooth[, cells.use.index]\n } else {\n data.smooth.subset <- matrix(0, nrow = 0, ncol = 0)\n }\n data.signaling.subset <- object@data.signaling[, cells.use.index]\n\n meta.subset <- object@meta[cells.use.index, , drop = FALSE]\n\n\n if (object@options$mode == \"merged\") {\n idents <- object@idents[1:(length(object@idents)-1)]\n group.existing <- level.use0[level.use0 %in% level.use]\n group.existing.index <- which(level.use0 %in% level.use)\n net.subset <- vector(\"list\", length = length(object@net))\n netP.subset <- vector(\"list\", length = length(object@netP))\n idents.subset <- vector(\"list\", length = length(idents))\n names(net.subset) <- names(object@net)\n names(netP.subset) <- names(object@netP)\n names(idents.subset) <- names(object@idents[1:(length(object@idents)-1)])\n images.subset <- vector(\"list\", length = length(idents))\n names(images.subset) <- names(object@idents[1:(length(object@idents)-1)])\n\n for (i in 1:length(idents)) {\n cat(\"Update slots object@images, object@net, object@netP, object@idents in dataset \", names(object@idents)[i],'\\n')\n images <- object@images[[i]]\n for (images.j in names(images)) {\n values <- images[[images.j]]\n if (images.j %in% c(\"coordinates\")) {\n values.new <- values[cells.use.index, ]\n images[[images.j]] <- values.new\n }\n if (images.j %in% c(\"distance\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n images[[images.j]] <- values.new\n }\n }\n images.subset[[i]] <- images\n\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net[[i]]\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- values[group.existing.index, group.existing.index, , drop = FALSE]\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n net[[net.j]] <- values.new\n }\n # net[[net.j]] <- values.new\n }\n net.subset[[i]] <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n # netP <- object@netP[[i]]\n # for (netP.j in names(netP)) {\n # values <- netP[[netP.j]]\n # if (netP.j %in% c(\"pathways\")) {\n # values.new <- values\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"prob\")) {\n # values.new <- values[group.existing.index, group.existing.index, ]\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"centr\")) {\n # for (k in 1:length(values)) {\n # values.new <- lapply(values, function(x) {\n # values.new2 <- lapply(x, function(x) {\n # values.new1 <- x[group.existing.index]\n # names(values.new1) <- group.existing\n # return(values.new1)\n # })\n # names(values.new2) <- names(x)\n # return(values.new2)\n # })\n # names(values.new) <- names(values)\n # }\n # }\n # netP[[netP.j]] <- values.new\n # }\n netP = computeCommunProbPathway(net = net.subset[[i]], pairLR.use = object@LR[[i]]$LRsig, thresh = thresh)\n netP$centr = netAnalysis_computeCentrality(net = net.subset[[i]]$prob)\n netP.subset[[i]] <- netP\n idents.subset[[i]] <- idents[[i]][names(idents[[i]]) %in% cells.use]\n idents.subset[[i]] <- factor(idents.subset[[i]], levels = levels(idents[[i]])[levels(idents[[i]]) %in% level.use])\n }\n idents.subset$joint <- factor(object@idents$joint[cells.use.index], levels = level.use)\n\n } else {\n cat(\"Update slots object@images, object@net, object@netP in a single dataset...\", '\\n')\n\n group.existing <- level.use0[level.use0 %in% level.use]\n group.existing.index <- which(level.use0 %in% level.use)\n\n images <- object@images\n for (images.j in names(images)) {\n values <- images[[images.j]]\n if (images.j %in% c(\"coordinates\")) {\n values.new <- values[cells.use.index, ]\n images[[images.j]] <- values.new\n }\n if (images.j %in% c(\"distance\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n images[[images.j]] <- values.new\n }\n }\n images.subset <- images\n\n\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- values[group.existing.index, group.existing.index, , drop = FALSE]\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n net[[net.j]] <- values.new\n }\n }\n net.subset <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n # netP <- object@netP\n # for (netP.j in names(netP)) {\n # values <- netP[[netP.j]]\n # if (netP.j %in% c(\"pathways\")) {\n # values.new <- values\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"prob\")) {\n # values.new <- values[group.existing.index, group.existing.index, ]\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"centr\")) {\n # for (k in 1:length(values)) {\n # values.new <- lapply(values, function(x) {\n # values.new2 <- lapply(x, function(x) {\n # values.new1 <- x[group.existing.index]\n # names(values.new1) <- group.existing\n # return(values.new1)\n # })\n # names(values.new2) <- names(x)\n # return(values.new2)\n # })\n # names(values.new) <- names(values)\n # }\n # }\n # netP[[netP.j]] <- values.new\n # }\n netP = computeCommunProbPathway(net = net.subset, pairLR.use = object@LR$LRsig, thresh = thresh)\n netP$centr = netAnalysis_computeCentrality(net = net.subset$prob)\n netP.subset <- netP\n idents.subset <- object@idents[cells.use.index]\n idents.subset <- factor(idents.subset, levels = level.use)\n }\n\n\n object.subset <- methods::new(\n Class = \"CellChat\",\n data = data.subset,\n data.signaling = data.signaling.subset,\n data.smooth = data.smooth.subset,\n images = images.subset,\n net = net.subset,\n netP = netP.subset,\n meta = meta.subset,\n idents = idents.subset,\n var.features = object@var.features,\n LR = object@LR,\n DB = object@DB,\n options = object@options\n )\n return(object.subset)\n}\n\n\n"], ["/CellChat/R/database.R", "#' Show the description of CellChatDB databse\n#'\n#' @param CellChatDB CellChatDB databse\n#' @param nrow the number of rows in the plot\n#' @importFrom dplyr group_by summarise n %>%\n#'\n#' @return\n#' @export\n#'\nshowDatabaseCategory <- function(CellChatDB, nrow = 1) {\n interaction_input <- CellChatDB$interaction\n geneIfo <- CellChatDB$geneInfo\n df <- interaction_input %>% group_by(annotation) %>% summarise(value=n())\n #df$group <- factor(df$annotation, levels = unique(df$annotation))\n df$group <- factor(df$annotation, levels = c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\"))\n gg1 <- pieChart(df)\n binary <- (interaction_input$ligand %in% geneIfo$Symbol) & (interaction_input$receptor %in% geneIfo$Symbol)\n df <- data.frame(group = rep(\"Heterodimers\", dim(interaction_input)[1]),stringsAsFactors = FALSE)\n df$group[binary] <- rep(\"Others\",sum(binary),1)\n df <- df %>% group_by(group) %>% summarise(value=n())\n df$group <- factor(df$group, levels = c(\"Heterodimers\",\"Others\"))\n gg2 <- pieChart(df)\n\n kegg <- grepl(\"KEGG\", interaction_input$evidence)\n df <- data.frame(group = rep(\"Literature\", dim(interaction_input)[1]),stringsAsFactors = FALSE)\n df$group[kegg] <- rep(\"KEGG\",sum(kegg),1)\n df <- df %>% group_by(group) %>% summarise(value=n())\n df$group <- factor(df$group, levels = c(\"KEGG\",\"Literature\"))\n gg3 <- pieChart(df)\n\n gg <- cowplot::plot_grid(gg1, gg2, gg3, nrow = nrow, align = \"h\", rel_widths = c(1, 1,1))\n return(gg)\n}\n\n\n#' Plot pie chart\n#'\n#' @param df a dataframe\n#' @param label.size a character\n#' @param color.use the name of the variable in CellChatDB interaction_input\n#' @param title the title of plot\n#' @import ggplot2\n#' @importFrom scales percent\n#' @importFrom dplyr arrange desc mutate\n#' @importFrom ggrepel geom_text_repel\n#' @return\n#' @export\n#'\npieChart <- function(df, label.size = 2.5, color.use = NULL, title = \"\") {\n df %>% arrange(dplyr::desc(value)) %>%\n mutate(prop = scales::percent(value/sum(value))) -> df\n\n gg <- ggplot(df, aes(x=\"\", y=value, fill=group)) +\n geom_bar(stat=\"identity\", width=1) +\n coord_polar(\"y\", start=0)+theme_void() +\n ggrepel::geom_text_repel(aes(label = prop), size= label.size, show.legend = F, position = position_stack(vjust=0.5))\n # ggrepel::geom_text_repel(aes(label = prop), size= label.size, show.legend = F, nudge_x = 0)\n gg <- gg + theme(legend.position=\"bottom\", legend.direction = \"vertical\")\n\n if(!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values=color.use)\n # gg <- gg + scale_color_manual(color.use)\n }\n\n if (!is.null(title)) {\n gg <- gg + guides(fill = guide_legend(title = title))\n }\n gg\n}\n\n\n#' Subset the ligand-receptor interactions for given specific signals in CellChatDB\n#'\n#' @param signaling a character vector\n#' @param pairLR.use a dataframe containing ligand-receptor interactions\n#' @param key the keyword to match\n#' @param matching.exact whether perform exact matching\n#' @param pair.only whether only return ligand-receptor pairs without cofactors\n#' @importFrom future.apply future_sapply\n#' @importFrom dplyr select\n#' @return\n#' @export\nsearchPair <- function(signaling = c(), pairLR.use, key = c(\"pathway_name\",\"ligand\"), matching.exact = FALSE, pair.only = TRUE) {\n key <- match.arg(key)\n pairLR = future.apply::future_sapply(\n X = 1:length(signaling),\n FUN = function(x) {\n if (!matching.exact) {\n index <- grep(signaling[x], pairLR.use[[key]])\n } else {\n index <- which(pairLR.use[[key]] %in% signaling[x])\n }\n if (length(index) > 0) {\n if (pair.only) {\n pairLR <- dplyr::select(pairLR.use[index, ], interaction_name, pathway_name, ligand, receptor)\n } else {\n pairLR <- pairLR.use[index, ]\n }\n return(pairLR)\n } else {\n stop(cat(paste(\"Cannot find \", signaling[x], \".\", \"Please input a correct name!\"),'\\n'))\n }\n }\n )\n if (pair.only) {\n pairLR0 <- vector(\"list\", length(signaling))\n for (i in 1:length(signaling)) {\n pairLR0[[i]] <- matrix(unlist(pairLR[c(4*i-3, 4*i-2, 4*i-1, 4*i)]), ncol=4, byrow=F)\n }\n pairLR <- do.call(rbind, pairLR0)\n dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]][1:4]\n rownames(pairLR) <- pairLR[,1]\n } else {\n pairLR0 <- vector(\"list\", length(signaling))\n for (i in 1:length(signaling)) {\n pairLR0[[i]] <- matrix(unlist(pairLR[(i*ncol(pairLR.use)-(ncol(pairLR.use)-1)):(i*ncol(pairLR.use))]), ncol=ncol(pairLR.use), byrow=F)\n }\n pairLR <- do.call(rbind, pairLR0)\n dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]]\n rownames(pairLR) <- pairLR[,1]\n }\n return(as.data.frame(pairLR, stringsAsFactors = FALSE))\n}\n\n#' Subset CellChatDB databse by only including interactions of interest\n#'\n#' @param CellChatDB CellChatDB databse\n#' @param search a character vector, which is a subset of c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\"); Setting search = NULL & non_protein = FALSE will return all signaling except for \"Non-protein Signaling\".\n#'\n#' When `key` is a vector, the `search` should be a list with the size being `length(key)`, where each element is a character vector.\n#' @param key a character vector and each element should be one of the column names of the interaction_input from CellChatDB.\n#' @param non_protein whether to use the non-protein signaling for CellChat analysis. By default, non_protein = FALSE because most of non-protein signaling are the special synaptic signaling interactions that can only be used when inferring neuron-neuron communication.\n#'\n#' @return\n#' @export\n#'\nsubsetDB <- function(CellChatDB, search = c(), key = \"annotation\", non_protein = FALSE) {\n interaction_input <- CellChatDB$interaction\n if (is.null(search) & non_protein == FALSE & any(key == \"annotation\")) {\n search <- c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\")\n } else if (is.null(search) & non_protein == TRUE & any(key == \"annotation\")) {\n search <- c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\")\n }\n\n if (\"Non-protein Signaling\" %in% unlist(search)) {\n non_protein = TRUE\n message(\"The non-protein signaling is now included for CellChat analysis, which is usually used for neuron-neuron and metabolic communication!\")\n }\n if (non_protein == FALSE) {\n interaction_input <- subset(interaction_input, annotation != \"Non-protein Signaling\")\n }\n if (all(key %in% colnames(interaction_input)) == FALSE) {\n stop(\"Each element of the `key` should be one of the column names of the interaction_input from CellChatDB\")\n }\n if (length(key) == 1) {\n interaction_input <- interaction_input[interaction_input[[key]] %in% search, ]\n } else {\n if (!is.list(search)) {\n stop(\"When `key` is a vector, the `search` should be a list. \")\n }\n idx.use <- TRUE\n for (i in 1:length(key)) {\n idx.use <- idx.use & (interaction_input[[key[i]]] %in% search[[i]])\n }\n interaction_input <- interaction_input[idx.use, , drop = FALSE]\n }\n\n CellChatDB$interaction <- interaction_input\n return(CellChatDB)\n}\n\n\n\n#' Extract the genes involved in CellChatDB\n#'\n#' @param CellChatDB CellChatDB databse used in the analysis\n#'\n#' @return\n#' @export\n#' @importFrom dplyr select\n#'\nextractGene <- function(CellChatDB) {\n interaction_input <- CellChatDB$interaction\n complex_input <- CellChatDB$complex\n cofactor_input <- CellChatDB$cofactor\n geneIfo <- CellChatDB$geneInfo\n # check whether all gene names in complex_input and cofactor_input are official gene symbol in geneIfo\n checkGeneSymbol(geneSet = unlist(complex_input), geneIfo)\n checkGeneSymbol(geneSet = unlist(cofactor_input), geneIfo)\n\n geneL <- unique(interaction_input$ligand)\n geneR <- unique(interaction_input$receptor)\n geneLR <- c(geneL, geneR)\n checkGeneSymbol(geneSet = geneLR[geneLR %in% rownames(complex_input) == \"FALSE\"], geneIfo)\n\n geneL <- extractGeneSubset(geneL, complex_input, geneIfo)\n geneR <- extractGeneSubset(geneR, complex_input, geneIfo)\n geneLR <- c(geneL, geneR)\n\n cofactor <- c(interaction_input$agonist, interaction_input$antagonist, interaction_input$co_A_receptor, interaction_input$co_I_receptor)\n cofactor <- unique(cofactor[cofactor != \"\"])\n cofactorsubunits <- select(cofactor_input[match(cofactor, rownames(cofactor_input), nomatch=0),], starts_with(\"cofactor\"))\n cofactorsubunitsV <- unlist(cofactorsubunits)\n geneCofactor <- unique(cofactorsubunitsV[cofactorsubunitsV != \"\"])\n\n gene.use <- unique(c(geneLR, geneCofactor))\n return(gene.use)\n\n}\n\n\n#' Extract the gene name\n#'\n#' @param geneSet gene set\n#' @param complex_input complex in CellChatDB databse\n#' @param geneIfo official gene symbol\n#'\n#' @return\n#' @importFrom dplyr select starts_with\n#' @export\nextractGeneSubset <- function(geneSet, complex_input, geneIfo) {\n complex <- geneSet[which(geneSet %in% geneIfo$Symbol == \"FALSE\")]\n geneSet <- intersect(geneSet, geneIfo$Symbol)\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complex <- intersect(complex, rownames(complexsubunits))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n geneSet <- unique(c(geneSet, complexsubunitsV))\n return(geneSet)\n}\n\n\n#' Extract the signaling gene names from ligand-receptor pairs\n#'\n#' @param pairLR data frame must contain columns named `ligand` and `receptor`\n#' @param object a CellChat object\n#' @param complex_input complex in CellChatDB databse\n#' @param geneInfo official gene symbol\n#' @param combined whether combining the ligand genes and receptor genes\n#'\n#' @return\n#' @export\nextractGeneSubsetFromPair <- function(pairLR, object = NULL, complex_input = NULL, geneInfo = NULL, combined = TRUE) {\n if (!all(c(\"ligand\", \"receptor\") %in% colnames(pairLR))) {\n stop(\"The input data frame must contain columns named `ligand` and `receptor`\")\n }\n if (is.null(object)) {\n if (is.null(complex_input) | is.null(geneInfo)) {\n stop(\"Either `object` or `complex_input` and `geneInfo` should be provided!\")\n } else {\n complex <- complex_input\n }\n } else {\n complex <- object@DB$complex\n geneInfo <- object@DB$geneInfo\n }\n geneL <- unique(pairLR$ligand)\n geneR <- unique(pairLR$receptor)\n geneL <- extractGeneSubset(geneL, complex, geneInfo)\n geneR <- extractGeneSubset(geneR, complex, geneInfo)\n geneLR <- c(geneL, geneR)\n if (combined) {\n return(geneLR)\n } else {\n return(list(geneL = geneL, geneR = geneR))\n }\n}\n\n\n\n#' check the official Gene Symbol\n#'\n#' @param geneSet gene set to check\n#' @param geneIfo official Gene Symbol\n#' @return\n#' @export\n#'\ncheckGeneSymbol <- function(geneSet, geneIfo) {\n geneSet <- unique(geneSet[geneSet != \"\"])\n genes_notOfficial <- geneSet[geneSet %in% geneIfo$Symbol == \"FALSE\"]\n if (length(genes_notOfficial) > 0) {\n cat(\"Issue identified!! Please check the official Gene Symbol of the following genes: \", \"\\n\", genes_notOfficial, \"\\n\")\n }\n return(FALSE)\n}\n\n#' Extract L-R pairs associated with a given gene set\n#'\n#' @param geneSet a vector of genes\n#' @param db one of the CellChatDB databases (e.g., CellChatDB.human, CellChatDB.mouse...)\n#' @export\n#'\nextractLRfromGenes <- function(geneSet, db) {\n interaction_input <- db$interaction\n complex_input <- db$complex\n geneIfo <- db$geneInfo\n geneSet1 <- intersect(geneSet, geneIfo$Symbol)\n idx1 <- which(interaction_input$ligand %in% geneSet1)\n idx2 <- which(interaction_input$receptor %in% geneSet1)\n idx <- unique(c(idx1, idx2)); idx <- setdiff(idx,0)\n LR.use <- interaction_input[idx,,drop = FALSE]\n genes.use <- extractGeneSubsetFromPair(LR.use, complex_input = complex_input, geneInfo = geneIfo)\n return(list(LR.use = LR.use, genes.use=genes.use))\n}\n\n\n#' Update CellChatDB by integrating new L-R pairs from other resources or adding more information\n#'\n#' @param db a data frame of the customized ligand-receptor database with at least two columns named as `ligand` and `receptor`. We highly suggest users to provide a column of pathway information named `pathway_name` associated with each L-R pair.\n#' Other optional columns include `interaction_name` and `interaction_name_2`. The default columns of CellChatDB can be checked via `colnames(CellChatDB.human$interaction)`.\n#' @param gene_info a data frame with at least one column named as `Symbol`. \"When setting gene_info = NULL, the input `species_target` should be provided: either `human` or `mouse`.\n#' @param other_info a list consisting of other information including a dataframe named as `complex` and a dataframe named as `cofactor`. This additional information is not necessary. If other_info is provided, the `complex` and `cofactor` are dataframes with defined rownames.\n#' @param gene_info_columnNew a data frame with at least two columns named as `Symbol` and `AntibodyName`, which will add a new column named `AntibodyName` into `db$geneInfo`.\n#' @param trim.pathway whether to delete the interactions with missing pathway names when the column `pathway_name` is provided in `db`.\n#' @param merged whether merging the input database with the existing CellChatDB. setting merged = TRUE, the input `species_target` should be provided: either `human` or `mouse`.\n#' @param species_target the target species for output: either `human` or `mouse`.\n#' @return a list consisting of the customized L-R database for further CellChat analysis\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # integrating new L-R pairs from other resources or utilizing a custom database `db.user`\n#' db.new <- updateCellChatDB(db = db.user, gene_info = gene_info)\n#' db.new <- updateCellChatDB(db = db.user, gene_info = NULL, species_target = \"human\")\n#' # Alternatively, users can integrate the customized L-R pairs into the built-in CellChatDB\n#' db.new <- updateCellChatDB(db = db.user, merged = TRUE, species_target = \"human\")\n#' # Add new columns (e.g., AntibodyName) into gene_info\n#' db.new.human <- updateCellChatDB(db = CellChatDB.human$interaction, gene_info = CellChatDB.human$geneInfo, other_info=list(complex = CellChatDB.human$complex, cofactor = CellChatDB.human$cofactor),gene_info_columnNew = gene_info_columnNew)\n#'\n#' # Users can now use this new database in CellChat analysis\n#' cellchat@DB <- db.new\n#'}\nupdateCellChatDB <- function(db, gene_info = NULL, other_info = NULL, gene_info_columnNew = NULL, trim.pathway = FALSE, merged = FALSE, species_target = NULL) {\n db <- dplyr::mutate(db, across(everything(), as.character))\n if (all(c(\"ligand\",\"receptor\") %in% colnames(db)) == FALSE) {\n stop(\"The input `db` must contain at least two columns named as ligand,receptor\")\n }\n if (all(c(\"pathway_name\") %in% colnames(db)) == FALSE) {\n warning(\"The pathway_name associated with each L-R pair is not provided in `db`. We suggest to provide this information so that the versatile functionalities of CellChat can be fully used! \\n\")\n db$pathway_name <- rep(\"\", nrow(db))\n } else {\n pathway.missing <- which(db$pathway_name == \"\")\n if (length(pathway.missing) > 0) {\n if (trim.pathway) {\n cat(paste0(\"The pathway names of \", length(pathway.missing) ,\" interactions are missing and the corresponding interactions are now deleted. \\n\"))\n db <- db[-pathway.missing, , drop = FALSE]\n } else {\n warning(paste0(\"The pathway names of \", length(pathway.missing) ,\" interactions are missing and it may cause error in the downstream analysis. Setting `trim.pathway = TRUE` to avoid such possible errors. \\n\"))\n }\n }\n }\n if (all(c(\"interaction_name\") %in% colnames(db)) == FALSE) {\n db$interaction_name <- paste0(toupper(db$ligand), \"_\", toupper(db$receptor))\n }\n if (all(c(\"interaction_name_2\") %in% colnames(db)) == FALSE) {\n db$interaction_name_2 <- paste0(db$ligand, \" - \", db$receptor)\n }\n if (\"agonist\" %in% colnames(db) == FALSE) {\n db$agonist <- rep(\"\", nrow(db))\n }\n if (\"antagonist\" %in% colnames(db) == FALSE) {\n db$antagonist <- rep(\"\", nrow(db))\n }\n if (\"co_A_receptor\" %in% colnames(db) == FALSE) {\n db$co_A_receptor <- rep(\"\", nrow(db))\n }\n if (\"co_I_receptor\" %in% colnames(db) == FALSE) {\n db$co_I_receptor <- rep(\"\", nrow(db))\n }\n ## construct database\n idx.remove <- duplicated(db$interaction_name)\n if (sum(idx.remove) > 0) {\n warning(paste0(sum(idx.remove), \" duplicated interaction_names are identified and the corresponding interactions are now deleted. \\n\"))\n db <- db[-which(idx.remove), ]\n }\n\n # build the interaction file\n interaction_input <- db\n rownames(interaction_input) <- interaction_input$interaction_name\n cols.default <- c(\"interaction_name\",\"pathway_name\",\"ligand\",\"receptor\",\"agonist\",\"antagonist\",\"co_A_receptor\",\"co_I_receptor\",\"annotation\",\"interaction_name_2\")\n cols.common <- intersect(cols.default,colnames(interaction_input))\n cols.specific <- setdiff(colnames(interaction_input), cols.default)\n interaction_input <- dplyr::select(interaction_input, c(cols.common, cols.specific))\n\n # build the complex file\n if (!is.null(other_info)) {\n if (\"complex\" %in% names(other_info) == TRUE) {\n complex_input <- other_info$complex\n if (all(colnames(complex_input) %in% paste0(\"subunit_\", seq_len(100))) == FALSE) {\n stop(\"The colnames of the input `other_info$complex` should be `subunit_1`,`subunit_2`,...\")\n }\n } else {\n complex_input <- data.frame()\n }\n # build the cofactor file\n if (\"cofactor\" %in% names(other_info) == TRUE) {\n cofactor_input <- other_info$cofactor\n if (all(colnames(cofactor_input) %in% paste0(\"cofactor\", seq_len(100))) == FALSE) {\n stop(\"The colnames of the input `other_info$cofactor` should be `cofactor1`,`cofactor2`,...\")\n }\n } else {\n cofactor_input <- data.frame()\n }\n } else {\n complex_input <- data.frame()\n cofactor_input <- data.frame()\n }\n\n # build the geneInfo file\n if (!is.null(gene_info)) {\n if (\"Symbol\" %in% colnames(gene_info) == FALSE) {\n stop(\"The input `gene_info` must contain at least one column named as `Symbol`\")\n }\n } else {\n if (is.null(species_target)) {\n stop(\"When setting gene_info = NULL, the input `species_target` should be provided: either `human` or `mouse`. \")\n }\n if (species_target == \"human\") {\n gene_info <- CellChatDB.human$geneInfo\n } else if (species_target == \"mouse\") {\n gene_info <- CellChatDB.mouse$geneInfo\n }\n }\n geneInfo_input <- gene_info\n\n if (merged == TRUE) {\n if (is.null(species_target)) {\n stop(\"When setting merged = TRUE, the input `species_target` should be provided: either `human` or `mouse`. \")\n }\n if (species_target == \"human\") {\n db.cellchat <- CellChatDB.human\n cat(\"Starting to merge the input database with CellChatDB.human... \\n\")\n } else if (species_target == \"mouse\") {\n db.cellchat <- CellChatDB.mouse\n cat(\"Starting to merge the input database with CellChatDB.mouse... \\n\")\n }\n\n # build the interaction file\n interaction_input.cellchat <- db.cellchat$interaction\n interaction_input.cellchat$source.merged <- \"CellChatDB\"\n interaction_input$source.merged <- \"User\"\n cols.common <- intersect(colnames(interaction_input), colnames(interaction_input.cellchat))\n interaction_input <- interaction_input[, cols.common]\n interaction_input.cellchat <- interaction_input.cellchat[, cols.common]\n interaction_input.merged <- rbind(interaction_input.cellchat, interaction_input)\n idx.remove <- duplicated(interaction_input.merged$interaction_name)\n if (sum(idx.remove) > 0) {\n interaction_input.merged <- interaction_input.merged[-which(idx.remove), ]\n }\n\n # build the complex file\n complex_input.cellchat <- db.cellchat$complex\n num.subunit <- max(ncol(complex_input), ncol(complex_input.cellchat))\n if (ncol(complex_input) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(complex_input)))\n complex_input <- cbind(complex_input, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(complex_input)))))\n colnames(complex_input) <- paste0(\"subunit_\", seq_len(num.subunit))\n }\n if (ncol(complex_input.cellchat) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(complex_input.cellchat)))\n complex_input.cellchat <- cbind(complex_input.cellchat, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(complex_input.cellchat)))))\n colnames(complex_input.cellchat) <- paste0(\"subunit_\", seq_len(num.subunit))\n }\n complex_input.merged <- rbind(complex_input.cellchat, complex_input)\n idx.remove <- duplicated(rownames(complex_input.merged))\n if (sum(idx.remove) > 0) {\n complex_input.merged <- complex_input.merged[-which(idx.remove), ]\n }\n\n # build the cofactor file\n cofactor_input.cellchat <- db.cellchat$cofactor\n num.subunit <- max(ncol(cofactor_input), ncol(cofactor_input.cellchat))\n if (ncol(cofactor_input) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(cofactor_input)))\n cofactor_input <- cbind(cofactor_input, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(cofactor_input)))))\n colnames(cofactor_input) <- paste0(\"cofactor\", seq_len(num.subunit))\n }\n if (ncol(cofactor_input.cellchat) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(cofactor_input.cellchat)))\n cofactor_input.cellchat <- cbind(cofactor_input.cellchat, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(cofactor_input.cellchat)))))\n colnames(cofactor_input.cellchat) <- paste0(\"cofactor\", seq_len(num.subunit))\n }\n cofactor_input.merged <- rbind(cofactor_input.cellchat, cofactor_input)\n idx.remove <- duplicated(rownames(cofactor_input.merged))\n if (sum(idx.remove) > 0) {\n cofactor_input.merged <- cofactor_input.merged[-which(idx.remove), ]\n }\n\n interaction_input <- interaction_input.merged\n complex_input <- complex_input.merged\n cofactor_input <- cofactor_input.merged\n }\n\n if (!is.null(gene_info_columnNew)) {\n checkGeneSymbol(gene_info_columnNew$Symbol, geneInfo_input)\n idx <- match(gene_info_columnNew$Symbol, geneInfo_input$Symbol)\n geneInfo_input$AntibodyName <- NA\n geneInfo_input$AntibodyName[idx[!is.na(idx)]] <- gene_info_columnNew$AntibodyName[!is.na(idx)]\n }\n db.new <- list()\n db.new$interaction <- interaction_input\n db.new$complex <- complex_input\n db.new$cofactor <- cofactor_input\n db.new$geneInfo <- geneInfo_input\n\n return(db.new)\n}\n"], ["/CellChat/R/RcppExports.R", "# Generated by using Rcpp::compileAttributes() -> do not edit by hand\n# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393\n\nComputeSNN <- function(nn_ranked, prune) {\n .Call(`_CellChat_ComputeSNN`, nn_ranked, prune)\n}\n\n"], ["/CellChat/R/CellChat-package.R", "## usethis namespace: start\n#' @useDynLib CellChat, .registration = TRUE\n## usethis namespace: end\nNULL\n\n## usethis namespace: start\n#' @importFrom Rcpp sourceCpp\n## usethis namespace: end\nNULL\n"], ["/CellChat/R/data.R", "#' Ligand-receptor interactions in CellChat database for mouse\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.mouse\"\n\n#' Ligand-receptor interactions in CellChat database for human\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.human\"\n\n#' Mouse Protein-Protein interactions\n#'\n#' An adjacency matrix of the high confidence known experimental interactions\n#' between mouse proteins on STRINGdb.\n#'\n#' @format A square matrix where A_{ij}=1 if protein i interacts with protein j\n#' @source \\url{http://www.string-db.org/}\n\"PPI.mouse\"\n\n#' Ligand-receptor interactions in CellChat database for Zebrafish\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.zebrafish\"\n\n#' Human Protein-Protein interactions\n#'\n#' An adjacency matrix of the high confidence known experimental interactions\n#' between human proteins on STRINGdb.\n#'\n#' @format A square matrix where A_{ij}=1 if protein i interacts with protein j\n#' @source \\url{http://www.string-db.org/}\n\"PPI.human\"\n"]], "task_instance_info": {"created_time": "2025-08-21 00:57:36", "created_task_model": "DeepSeek-R1", "function_skeleton": "function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n reduction = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1) {}", "code_description": "This code segment functions to: Generate an interactive visualization of dimensional reduction plots for exploring cell group distributions with dynamic highlighting capabilities based on user-selected parameters."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nfunction (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n reduction = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1) {\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(\"Please make sure `object@dr` contains a low-dimensional space of the data and specify the dimensionality reduction to use.\")\n }\n }\n \n samples <- object@meta$samples\n cell_labels <- if (is.null(group.by)) object@idents else object@meta[,group.by]\n \n if (ncol(coords) >= 2) {\n coords <- coords[, c(1,2)]\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1 && !is.null(sample.use)) {\n if (!sample.use %in% unique(samples)) \n stop(\"Invalid sample.use\")\n coords <- coords[samples == sample.use, ]\n cell_labels <- cell_labels[samples == sample.use]\n }\n } else {\n stop(\"Reduction coordinates must have at least 2 dimensions\")\n }\n \n cells.level <- levels(cell_labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) idents.use <- cells.level[idents.use]\n cell_labels[!(cell_labels %in% idents.use)] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n cell_labels <- factor(cell_labels, levels = cells.level)\n }\n \n if (is.null(sources.use) && is.null(targets.use)) {\n if (is.null(color.use)) \n color.use <- scPalette(nlevels(cell_labels))\n } else {\n if (is.numeric(sources.use)) sources.use <- cells.level[sources.use]\n if (is.numeric(targets.use)) targets.use <- cells.level[targets.use]\n \n group <- rep(\"Others\", length(cell_labels))\n group[cell_labels %in% sources.use] <- \"Sources\"\n group[cell_labels %in% targets.use] <- \"Targets\"\n group <- factor(group, levels = c(\"Sources\", \"Targets\", \"Others\"))\n \n if (is.null(color.use)) {\n color.use <- scPalette(3)\n color.use[3] <- \"grey90\"\n }\n cell_labels <- group\n }\n \n coordinates <- data.frame(coords, cell_labels = cell_labels)\n \n plotly::highlight_key(coordinates, ~cell_labels) %>%\n plotly::plot_ly(\n x = ~x_cent, \n y = ~y_cent, \n color = ~cell_labels,\n colors = color.use,\n alpha = alpha,\n marker = list(size = point.size),\n type = 'scatter',\n mode = 'markers'\n ) %>%\n plotly::add_markers() %>%\n plotly::layout(\n title = title.name,\n yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),\n xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)\n ) %>%\n plotly::highlight(on = \"plotly_click\", off = \"plotly_relayout\")\n}\n[TASK_END]\n```", "inference_time": "2025-08-21 00-58-53"}, "editdistance_info": {"edit_distance": 47.9365, "calculate_time": "2025-08-21 00:58:53", "true_code_clean": "function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n reduction = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1)\n {\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[, group.by]\n labels <- factor(labels)\n }\n if (length(names(object@dr)) == 0) {\n stop(\"Please check `addReduction` to add a new reduced space into `object@dr`. \\n\")\n }\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please specify the dimensionality reduction to use. \\n\"))\n }\n }\n coordinates <- as.data.frame(coords)\n samples <- object@meta$samples\n if (ncol(coordinates) >= 2) {\n coordinates <- coordinates[, c(1,2)]\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n cells.level <- levels(labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n if (is.null(sources.use) & is.null(targets.use)) {\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n }\n else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use,\n \"Others\"))\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use,\n targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n coordinates$cell_labels <- labels\n py <- plotly::highlight_key(coordinates,~cell_labels) %>%\n plotly::plot_ly(x = ~x_cent, y = ~y_cent,marker = list(size = point.size)) %>%\n plotly::add_markers(color=~cell_labels,alpha=alpha,colors=color.use) %>%\n plotly::layout(\n title = title.name,\n yaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n ),\n xaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n )\n ) %>%\n plotly::highlight(on = \"plotly_click\",\n off = \"plotly_relayout\")\n return(py)\n }", "predict_code_clean": "function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n reduction = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1) {\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(\"Please make sure `object@dr` contains a low-dimensional space of the data and specify the dimensionality reduction to use.\")\n }\n }\n samples <- object@meta$samples\n cell_labels <- if (is.null(group.by)) object@idents else object@meta[,group.by]\n if (ncol(coords) >= 2) {\n coords <- coords[, c(1,2)]\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1 && !is.null(sample.use)) {\n if (!sample.use %in% unique(samples)) \n stop(\"Invalid sample.use\")\n coords <- coords[samples == sample.use, ]\n cell_labels <- cell_labels[samples == sample.use]\n }\n } else {\n stop(\"Reduction coordinates must have at least 2 dimensions\")\n }\n cells.level <- levels(cell_labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) idents.use <- cells.level[idents.use]\n cell_labels[!(cell_labels %in% idents.use)] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n cell_labels <- factor(cell_labels, levels = cells.level)\n }\n if (is.null(sources.use) && is.null(targets.use)) {\n if (is.null(color.use)) \n color.use <- scPalette(nlevels(cell_labels))\n } else {\n if (is.numeric(sources.use)) sources.use <- cells.level[sources.use]\n if (is.numeric(targets.use)) targets.use <- cells.level[targets.use]\n group <- rep(\"Others\", length(cell_labels))\n group[cell_labels %in% sources.use] <- \"Sources\"\n group[cell_labels %in% targets.use] <- \"Targets\"\n group <- factor(group, levels = c(\"Sources\", \"Targets\", \"Others\"))\n if (is.null(color.use)) {\n color.use <- scPalette(3)\n color.use[3] <- \"grey90\"\n }\n cell_labels <- group\n }\n coordinates <- data.frame(coords, cell_labels = cell_labels)\n plotly::highlight_key(coordinates, ~cell_labels) %>%\n plotly::plot_ly(\n x = ~x_cent, \n y = ~y_cent, \n color = ~cell_labels,\n colors = color.use,\n alpha = alpha,\n marker = list(size = point.size),\n type = 'scatter',\n mode = 'markers'\n ) %>%\n plotly::add_markers() %>%\n plotly::layout(\n title = title.name,\n yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),\n xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)\n ) %>%\n plotly::highlight(on = \"plotly_click\", off = \"plotly_relayout\")\n}"}} {"repo_name": "CellChat", "file_name": "/CellChat/R/app.R", "inference_info": {"prefix_code": "#' Generate a Shiny App for interactive exploration of CellChat's outputs\n#'\n#' @param object CellChat object\n#' @param ... Other parameters of `shinyApp` function from shiny R package\n#' @return A Shiny app object on the basis of one CellChat object\n#' @export\n#' @importFrom stringr str_split_1\n# #' @importFrom plotly subplot plot_ly ggplotly add_markers highlight highlight_key plotlyOutput layout\n# #' @importFrom bsicons bs_icon\n#' @import shiny bslib\n#'\nrunCellChatApp <- function(object,...) {\n # ##########################################################################\n # set some global options\n # ##########################################################################\n options(stringsAsFactors = FALSE)\n\n # ##########################################################################\n # some useful elements for ui.R\n # ##########################################################################\n choices_cell_groups <-levels(object@idents)\n names(choices_cell_groups) <- levels(object@idents)\n\n choices_pathways <- object@netP$pathways\n names(choices_pathways) <- object@netP$pathways\n\n # all signaling gene names\n choices_gene_names <- CellChat::extractGene(object@DB)\n # all ligand-receptor pair names\n #choices_pairLR_use <- object@DB$interaction$interaction_name\n if (\"LRs\" %in% names(object@net)) {\n choices_pairLR_use <- object@net$LRs\n } else {\n thresh = 0.05\n prob <- object@net$prob\n prob[object@net$pval > thresh] <- 0\n LR <- dimnames(prob)[[3]]\n LR.sig <- LR[apply(prob, 3, sum) != 0]\n choices_pairLR_use <- LR.sig\n }\n\n\n # Palettes (sequential)\n choices_palettes_sequential <- stringr::str_split_1(\"Blues, BuGn, BuPu, GnBu, Greens, Greys, Oranges, OrRd, PuBu, PuBuGn, PuRd, Purples, RdPu, Reds, YlGn, YlGnBu, YlOrBr, YlOrRd\",\", \")\n names(choices_palettes_sequential) <- choices_palettes_sequential\n choices_palettes_diverging <- stringr::str_split_1(\"BrBG, PiYG, PRGn, PuOr, RdBu, RdGy, RdYlBu, RdYlGn, Spectral\",\", \")\n names(choices_palettes_diverging) <- choices_palettes_diverging\n\n # ##########################################################################\n # interactive visualization\n # ##########################################################################\n\n # interactive Heatmap\n # [Colors (ggplot2)](http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/)\n plotly_netVisual_heatmap <- function(obj_heatmap,palette.heatmap,direction.heatmap=1) {\n gg_heatmap <- obj_heatmap@matrix %>%\n as.data.frame() %>%\n mutate(row = rownames(.)) %>%\n tidyr::pivot_longer(\n data = .,\n cols = colnames(.)[-length(colnames(.))],\n names_to = \"column\",\n values_to = \"value\"\n ) %>%\n ggplot() +\n geom_tile(aes(row, column, fill = value),\n width = 0.95,\n height = 0.95) +\n # guides(fill=guide_legend(title=obj_heatmap@row_title))+\n labs(title = '',\n x = '',\n y = obj_heatmap@row_title,\n # I can't set the direction of the legend title, I thick it's a bug\n # fill = obj_heatmap@column_title,\n ) +\n scale_fill_distiller(\n palette = palette.heatmap,\n na.value = 'white',\n direction = direction.heatmap,\n ) +\n theme_minimal()+\n theme(axis.title.y = element_text(size = 14))\n\n # ggplot transpose the matrix, so we need use colSums to calc the 'rowSums'\n # of the matrix\n gg_right <- obj_heatmap@matrix %>%\n colSums(abs(.)) %>%\n tibble(row_sum = ., sources_name = names(.)) %>%\n ggplot() +\n geom_bar(aes(x = sources_name, y = row_sum, fill = sources_name),\n stat = 'identity') +\n labs(title = '',\n x = '',\n y = '',) +\n guides(fill = FALSE) +\n scale_fill_brewer(palette = \"Set1\", direction = 1) +\n theme_minimal() +\n coord_flip()\n\n gg_top <- obj_heatmap@matrix %>%\n rowSums(abs(.)) %>%\n tibble(col_sum = ., sources_name = names(.)) %>%\n ggplot() +\n # use fill to set the columns' colors\n geom_bar(aes(x = sources_name, y = col_sum, fill = sources_name),\n stat = 'identity') +\n labs(title = obj_heatmap@column_title,\n x = '',\n y = '',) +\n guides(fill = FALSE)+\n scale_fill_brewer(palette = \"Set1\", direction = 1) +\n # theme() function should be used behind the theme_*()\n theme_minimal()+\n theme(plot.title = element_text(hjust = 0.5,size = 14))\n\n return(plotly::subplot(\n gg_top,\n plotly::plotly_empty(),\n gg_heatmap,\n gg_right,\n nrows = 2,\n heights = c(0.2, 0.8),\n widths = c(0.8, 0.2),\n margin = 0,\n shareX = TRUE,\n shareY = TRUE,\n titleX = TRUE,\n titleY = TRUE\n )\n )\n }\n\n # interactive DimPlot\n plotly_DimPlot <- function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n reduction = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1)\n {\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[, group.by]\n labels <- factor(labels)\n }\n if (length(names(object@dr)) == 0) {\n stop(\"Please check `addReduction` to add a new reduced space into `object@dr`. \\n\")\n }\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please specify the dimensionality reduction to use. \\n\"))\n }\n }\n coordinates <- as.data.frame(coords)\n samples <- object@meta$samples\n if (ncol(coordinates) >= 2) {\n coordinates <- coordinates[, c(1,2)]\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n # temp_coordinates = coordinates\n # coordinates[,1] = temp_coordinates[,2]\n # coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n\n\n\n cells.level <- levels(labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n if (is.null(sources.use) & is.null(targets.use)) {\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n }\n else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use,\n \"Others\"))\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use,\n targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n # print(color.use)->return a color vector\n coordinates$cell_labels <- labels\n\n py <- plotly::highlight_key(coordinates,~cell_labels) %>%\n plotly::plot_ly(x = ~x_cent, y = ~y_cent,marker = list(size = point.size)) %>%\n plotly::add_markers(color=~cell_labels,alpha=alpha,colors=color.use) %>%\n plotly::layout(\n title = title.name,\n yaxis = list(\n title = \"\",\n #autorange = \"reversed\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n ),\n xaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n )\n ) %>%\n plotly::highlight(on = \"plotly_click\",\n off = \"plotly_relayout\")\n\n return(py)\n }\n\n # interactive FeaturePlot\n # https://plotly.com/r/subplots/\n plotly_FeaturePlot <- ", "suffix_code": "\n\n # interactive spatialDimPlot\n plotly_spatialDimPlot <- function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1)\n {\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[, group.by]\n labels <- factor(labels)\n }\n\n coordinates <- as.data.frame(object@images$coordinates)\n samples <- object@meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n\n\n cells.level <- levels(labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n if (is.null(sources.use) & is.null(targets.use)) {\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n }\n else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use,\n \"Others\"))\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use,\n targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n # print(color.use)->return a color vector\n coordinates$cell_labels <- labels\n\n py <- plotly::highlight_key(coordinates,~cell_labels) %>%\n plotly::plot_ly(x = ~x_cent, y = ~y_cent,marker = list(size = point.size)) %>%\n plotly::add_markers(color=~cell_labels,alpha=alpha,colors=color.use) %>%\n plotly::layout(\n title = title.name,\n yaxis = list(\n autorange = \"reversed\",\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n showline = FALSE\n ),\n xaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n showline = FALSE\n )\n ) %>%\n plotly::highlight(on = \"plotly_click\",\n off = \"plotly_relayout\")\n\n return(py)\n }\n\n # interactive spatialFeaturePlot\n # https://plotly.com/r/subplots/\n plotly_spatialFeaturePlot <- function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE){\n coords <- as.data.frame(object@images$coordinates)\n samples <- object@meta$samples\n cell_labels <- object@idents\n data <- as.matrix(object@data)\n meta <- object@meta\n\n if (ncol(coords) == 2) {\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coords = coords\n coords[,1] = temp_coords[,2]\n coords[,2] = temp_coords[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n # add idents info\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = -1))(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n }\n else {\n colormap <- color.heatmap\n }\n if (is.null(features) &\n is.null(signaling) & is.null(pairLR.use)) {\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)) {\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)) {\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)) {\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n df <- data.frame(x = coords[, 1], y = coords[, 2],\n cell_labels = cell_labels)\n\n\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n geneLR.return = TRUE,\n enriched.only = enriched.only,\n thresh = thresh\n )\n feature.use <- res$geneLR\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex,\n object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex,\n object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n }\n else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) >\n 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n }\n else if (length(intersect(feature.use, colnames(meta))) >\n 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[, feature.use, drop = FALSE])\n }\n else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \", cutoff, \"to the values...\",\n \"\\n\")\n data.use[data.use <= cutoff] <- 0\n }\n\n\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 0.95) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_colour_gradientn(\n colours = colormap,\n guide = guide_colorbar(\n title = NULL,\n ticks = T,\n label = T,\n barwidth = 0.5\n ),\n na.value = \"grey90\"\n ) +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + ggtitle(feature.name) +\n theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n g <- g + coord_fixed() +\n scale_y_reverse()\n\n gg[[i]] <- g %>% plotly::ggplotly(height = 400)\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n # print(annotations_pos)\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',annotations = annotations)\n }\n else {\n gg <- plotly::ggplotly(gg[[1]])\n }\n }\n else {\n # do.binary\n set_individual_legend <- function(plt) {\n # plt is a plotly plot obj\n plt_build <- plotly::plotly_build(plt)\n\n # get the num of traces\n len_legend <- length(plt_build$x$data)\n\n for (i in 1:len_legend) {\n # set legendgroup\n plt_build$x$data[[i]]$legendgroup <- feature.name\n # set legendtitle\n plt_build$x$data[[i]]$legendgrouptitle <- list(text=feature.name,font=list(size=12))\n }\n return(plt_build)\n }\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n enriched.only = enriched.only,\n thresh = thresh\n )\n LR.pair <- object@LR$LRsig[res$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL\n rownames(dataR) <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \")\n }\n gg <- vector(\"list\", numFeature)\n\n # set subplot title pos\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 1) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i,] > cutoff\n idx2 = dataR[i,] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\", ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i], geneR[i],\n \"Both\", \"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i], geneR[i], \"Both\",\n \"None\")\n if (length(setdiff(levels(group), unique(group))) >\n 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group),\n unique(group)))\n }\n df$feature.data <- group\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + guides(color = guide_legend(override.aes = list(size = legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n g <- g + coord_fixed() +\n scale_y_reverse()\n\n # cat(feature.name)\n gg[[i]] <- g %>% plotly::ggplotly(\n type = 'scatter',\n mode='markers+text',\n ) %>% set_individual_legend()\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',\n annotations = annotations,\n legend = list(tracegroupgap = 10,title=list(text=''))\n )\n }\n else {\n gg <- plotly::ggplotly(gg[[1]],\n type = 'scatter',\n mode = 'markers') %>%\n plotly::layout(legend = list(title = list(text = '')))\n }\n }\n return(gg)\n }\n\n\n\n # ##########################################################################\n # Shiny App's UI\n # ##########################################################################\n ui <- fluidPage(\n theme = bslib::bs_theme(version = 5),\n # ##########################################################################\n # meta info of the HTML pages\n # ##########################################################################\n tags$head(\n # title\n tags$title(\"Interactive CellChat Explorer\"),\n # icon\n tags$link(rel = \"shortcut icon\", type = \"image/x-icon\", href = \"favicon.ico\"),\n tags$link(rel=\"stylesheet\",href=\"https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css\"),\n ),\n tags$body(\n # ##########################################################################\n # logo and title of the website\n # ##########################################################################\n tags$nav(class=\"navbar navbar-light bg-light\",\n div(class=\"container-fluid justify-content-center\",\n tags$a(\n class=\"navbar-brand\",href=\"http://www.cellchat.org/\",\n img(src=\"https://s2.loli.net/2023/08/08/2qjSoRACDtHByOY.png\",class=\"d-inline\",alt=\"\",height=\"30\"),\n tags$p(\"Interactive CellChat Explorer\",class=\"fs-1 d-inline\")\n )\n\n )),\n # ##########################################################################\n # 1.Basic exploration of spatial-resolved gene expression\n # ##########################################################################\n\n # Visualize cell groups and signaling expression\n h3(tags$i(class=\"bi bi-1-square-fill\"),\n \"Visualize cell groups and signaling expression\",class=\"h3\"),\n bslib::card(\n bslib::card_header(\n h6(tags$i(class=\"bi bi-bookmark\"),\n \"Dim Plot\",class=\"h6\")),\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n sliderInput(\n \"dimplot_point_size\",\n label = \"Point size\",\n min = 3,\n max = 8,\n step = 0.5,\n value = 3\n ),\n sliderInput(\n \"dimplot_alpha\",\n label = \"Alpha\",\n min = 0,\n max = 1,\n step = 0.2,\n value = 1\n ),\n )\n ),\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"DimPlot\",\n width = 664,height = 498)\n )\n\n ),\n\n ),\n\n # gene expression distribution\n # https://shiny.posit.co/r/gallery/widgets/datatables-options/\n # https://shiny.posit.co/r/gallery/widgets/selectize-examples/\n navset_card_tab(\n title = h6(tags$i(class=\"bi bi-bookmark-dash\"),\n \"Feature Plot\",class=\"h6\"),\n sidebar = NULL,\n # content\n nav_panel(\n title = \"use gene names\",\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectizeInput(\n inputId = 'selectize_gene_names',\n label = 'Gene Names',\n choices = NULL,\n multiple = TRUE,\n # options = list(maxItems = 4)\n ),\n numericInput(\n \"nrows_feature_plot1\",\n label = \"nrows\",\n min = 1,\n step = 1,\n value = 1,\n ),\n ),\n\n accordion_panel(\n title = \"Color\",\n icon = tags$i(class=\"bi bi-palette-fill\"),\n selectInput(\n \"direction_feature_plot1\",\n label = \"direction\",\n choices = list(\"1\"=1,\"-1\"=-1),\n selected = 1,\n multiple = F\n ),\n selectInput(\n \"palette_feature_plot1\",\n label = \"palette\",\n choices = c(choices_palettes_diverging,choices_palettes_sequential),\n selected = \"Reds\",\n multiple = F\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n numericInput(\n \"cut.off_feature_plot1\",\n label = \"cut.off\",\n min = 0,\n step = 0.1,\n value = 0,\n ),\n sliderInput(\n \"point.size_feature_plot1\",\n label = \"point.size\",\n min = 0,\n max = 2,\n step = 0.1,\n value = 0.4\n )\n )\n\n ),\n # nav content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"gene_expression_distribution\",width = 664,height = 498),\n ),\n )\n ),\n nav_panel(\n title = \"use L-R pairs\",\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectizeInput(\n inputId = 'selectize_pairLR_use',\n label = 'pairLR_use',\n choices = NULL,\n multiple = T\n ),\n numericInput(\n \"nrows_feature_plot2\",\n label = \"nrows\",\n min = 1,\n step = 1,\n value = 1,\n ),\n checkboxInput(\n \"do.binary_feature_plot\",\n label = \"do.binary\",\n value = TRUE),\n ),\n accordion_panel(\n title = \"Color\",\n icon = tags$i(class=\"bi bi-palette-fill\"),\n selectInput(\n \"direction_feature_plot2\",\n label = \"direction\",\n choices = list(\"1\"=1,\"-1\"=-1),\n selected = 1,\n multiple = F\n ),\n selectInput(\n \"palette_feature_plot2\",\n label = \"palette\",\n choices = c(choices_palettes_diverging,choices_palettes_sequential),\n selected = \"Reds\",\n multiple = F\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n numericInput(\n \"cut.off_feature_plot2\",\n label = \"cut.off\",\n min = 0,\n step = 0.1,\n value = 0,\n ),\n sliderInput(\n \"point.size_feature_plot2\",\n label = \"point.size\",\n min = 0,\n max = 2,\n step = 0.1,\n value = 0.4\n )\n )\n ),\n # nav content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"gene_expression_distribution2\",width = 664,height = 498)\n )\n ),\n )\n ),\n\n # ##########################################################################\n # 2.Examine signaling between cell groups\n # ##########################################################################\n h2(tags$i(class=\"bi bi-2-square-fill\"),\n \"Examine signaling between cell groups\"),\n navset_card_tab(\n title = NULL,\n sidebar = NULL,\n nav_panel(\"Heatmap\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"The number of interactions/interaction strength between any two cell groups\",\n class=\"h6\"),\n hr(),\n\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"measure_heatmap\",\n label = \"measurement\",\n choices = list(\"count\" = \"count\", \"weight\" = \"weight\"),\n selected = \"count\"\n ),\n selectInput(\n \"palette_heatmap\",\n label = \"palette (sequential)\",\n choices = choices_palettes_sequential,\n selected = \"Blues\"\n ),\n # Sets the order of colours in the scale. If 1, the default, colours are as output by RColorBrewer::brewer.pal(). If -1, the order of colours is reversed.\n selectInput(\n \"direction_heatmap\",\n label = \"direction\",\n choices = list(\n \"1\"=1,\n \"-1\"=-1\n ),\n selected = 1,\n )\n\n # refer to: https://ggplot2.tidyverse.org/reference/scale_brewer.html\n ),\n ),\n\n # content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"netVisual_heatmap\",width = 664,height = 498)\n )\n )\n ),\n\n # the enriched signaling among one selected pair of cell groups\n nav_panel(\"rankNet\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"The enriched signaling\",\n class=\"h6\"),\n hr(),\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"select1_cell_group\",\n label = \"cell groups for sources.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[1],\n multiple = TRUE\n ),\n selectInput(\n \"select2_cell_group\",\n label = \"cell groups for targets.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[2],\n multiple = TRUE\n ),\n\n # selectInput(\n # \"measure_ranknet\",\n # label = \"measurement\",\n # choices = list(\"count\" = \"count\", \"weight\" = \"weight\"),\n # selected = \"count\"\n # ),\n selectInput(\n \"slot.name_ranknet\",\n label = \"slot.name\",\n choices = list(\"net\" = \"net\", \"netP\" = \"netP\"),\n selected = \"netP\"\n ),\n # selectInput(\n # \"palette_ranknet\",\n # label = \"palette (sequential)\",\n # choices = choices_palettes_sequential,\n # selected = \"Blues\"\n # ),\n ),\n ),\n\n # content\n plotly::plotlyOutput(outputId = \"rankNet\")\n )\n ),\n nav_panel(\"Contribution Plot\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"Contribution of each L-R pair to overall signaling\",\n class = \"h6\"),\n hr(),\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"pathway_contribution_plot\",\n label = \"a pathway to show\",\n choices = choices_pathways,\n selected = choices_pathways[1]\n ),\n selectInput(\n \"select3_cell_group\",\n label = \"a cell group for sources.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[1]\n ),\n selectInput(\n \"select4_cell_group\",\n label = \"a cell group for targets.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[2]\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n sliderInput(\n \"font.size_contribution_plot\",\n label = \"font.size\",\n min = 10,\n max=30,\n step = 5,\n value = 20\n )\n )\n ),\n\n # content\n plotOutput(outputId = \"netAnalysis_contribution\"),\n )\n ),\n ),\n\n # Contribution of each L-R pair to overall signaling\n # width = 3.2inch, height = 1.5inch,\n # height might change dependent on dataset\n\n ## Examine individual signaling pathway\n ## (the following four plots will be appeared based on user's input)\n h2(tags$i(class=\"bi bi-3-square-fill\"),\n \"Examine individual signaling pathway\"),\n navset_card_tab(\n title = h6(\"Plots\",class=\"h6\"),\n sidebar = accordion(\n selectizeInput(\n inputId = 'selectize_pathway',\n label = 'Select a pathway to show',\n choices = NULL,\n multiple = FALSE\n ),\n hr(),\n accordion_panel(\n title = \"Circle plot\",\n icon = tags$i(class=\"bi bi-circle-fill\"),\n # edge.width.max = 5, vertex.size.max = 12, vertex.label.cex = 0.8\n sliderInput(\n \"slider_Circle_plot_edge.width.max\",\n label = \"edge.width.max\",\n min = 5,\n max = 15,\n value = 8,\n step = 1\n ),\n sliderInput(\n \"slider_Circle_plot_vertex.size.max\",\n label = \"vertex.size.max\",\n min = 8,\n max = 16,\n value = 12,\n step = 2),\n sliderInput(\n \"slider_Circle_plot_vertex.label.cex\",\n label = \"vertex.label.cex\",\n min = 1,\n max = 2,\n value = 1,\n step = 0.2\n ),\n ),\n accordion_panel(\n title = \"Spatial plot\",\n icon = tags$i(class=\"bi bi-layers-half\"),\n # edge.width.max = 5, vertex.size.max = 1,\n # point.size = 2.5,\n # alpha.image = 0.2, vertex.label.cex = 5\n sliderInput(\n \"slider_Spatial_plot_edge.width.max\",\n label = \"edge.width.max\",\n min = 2,\n max = 8,\n value = 5,\n step = 1\n ),\n sliderInput(\n \"slider_Spatial_plot_vertex.size.max\",\n label = \"vertex.size.max\",\n min = 2,\n max = 8,\n value = 5,\n step = 1),\n sliderInput(\n \"slider_Spatial_plot_vertex.label.cex\",\n label = \"vertex.label.cex\",\n min = 5,\n max = 10,\n value = 8,\n step = 1\n ),\n\n sliderInput(\n \"slider_Spatial_plot_point.size\",\n label = \"point.size\",\n min = 1,\n max = 3,\n value = 2.4,\n step = 0.2\n ),\n sliderInput(\n \"slider_Spatial_plot_alpha.image\",\n label = \"alpha.image\",\n min = 0,\n max = 1,\n value = 0.2,\n step = 0.05\n ),\n ),\n accordion_panel(\n title = \"Contribution of each L-R pair\",\n icon = tags$i(class=\"bi bi-bar-chart-fill\"),\n ),\n ),\n\n # nav tab\n nav_panel(\n title = \"Circle plot\",\n div(class=\"d-flex justify-content-center\",\n plotOutput(outputId = \"Circle_plot\",\n height = \"780px\",width = \"580px\")\n )\n ),\n nav_panel(\n title = \"Spatial plot\",\n div(class=\"d-flex justify-content-center\",\n plotOutput(outputId = \"Spatial_plot\",\n height = \"780px\",width = \"580px\")\n )\n ),\n nav_panel(\n title = \"Contribution of each L-R pair\",\n plotly::plotlyOutput(outputId = \"LR_pair_contribution\",\n height = \"900px\")\n ),\n\n ),\n # body\n\n ),\n # page\n )\n # ##########################################################################\n # Shiny App's Server\n # ##########################################################################\n server <- function(input, output, session) {\n ############################################################################\n if (object@options$datatype == \"RNA\") {\n output$DimPlot <- plotly::renderPlotly({\n plotly_DimPlot(\n object,\n point.size = input$dimplot_point_size,\n alpha = input$dimplot_alpha,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"DimPlot\",\n width = 800,\n height = 600\n ))\n })\n } else {\n output$spatialDimPlot <- plotly::renderPlotly({\n plotly_spatialDimPlot(\n object,\n point.size = input$dimplot_point_size,\n alpha = input$dimplot_alpha,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialDimPlot\",\n width = 800,\n height = 600\n ))\n })\n }\n\n\n observe({\n updateSelectizeInput(\n session,\n \"selectize_gene_names\",\n # selected = c(\"Wnt10a\", \"Fzd1\", \"Lrp6\"),\n selected = choices_gene_names[1:2],\n # selected = c(\"Wnt10a\", \"Fzd1\", \"Lrp6\",\"Ror2\",\n # \"Nrp1\",\"Nrp2\",\"Bmpr2\",\"Ret\"),\n choices = choices_gene_names,\n server = TRUE\n )\n })\n # output$out6 <- renderPrint(input$selectize_gene_names)\n\n if (object@options$datatype == \"RNA\") {\n output$gene_expression_distribution <- plotly::renderPlotly(plotly_FeaturePlot(\n object,\n features = input$selectize_gene_names,\n plot_nrows = input$nrows_feature_plot1,\n point.size = input$point.size_feature_plot1,\n cutoff = input$cut.off_feature_plot1,\n color.heatmap = input$palette_feature_plot1,\n direction = input$direction_feature_plot1,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"FeaturePlot (use gene names)\",\n width = 600,\n height = 600\n ))\n )\n } else {\n output$gene_expression_distribution <- plotly::renderPlotly(plotly_spatialFeaturePlot(\n object,\n features = input$selectize_gene_names,\n plot_nrows = input$nrows_feature_plot1,\n point.size = input$point.size_feature_plot1,\n cutoff = input$cut.off_feature_plot1,\n color.heatmap = input$palette_feature_plot1,\n direction = input$direction_feature_plot1,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialFeaturePlot (use gene names)\",\n width = 600,\n height = 600\n ))\n )\n }\n\n\n observe({\n updateSelectizeInput(\n session,\n \"selectize_pairLR_use\",\n selected = choices_pairLR_use[1],\n # selected = c(\"WNT10A_FZD1_LRP6\",\"WNT10A_FZD10_LRP6\",\"BMP2_BMPR1A_ACVR2A\"),\n choices = choices_pairLR_use,\n server = TRUE\n )\n })\n # output$out7 <- renderPrint(input$selectize_pairLR_use)\n if (object@options$datatype == \"RNA\") {\n output$gene_expression_distribution2 <- plotly::renderPlotly({\n plotly_FeaturePlot(\n object,\n pairLR.use = input$selectize_pairLR_use,\n point.size = input$point.size_feature_plot2,\n do.binary = input$do.binary_feature_plot,\n cutoff = input$cut.off_feature_plot2,\n enriched.only = F,\n color.heatmap = input$palette_feature_plot2,\n direction = input$direction_feature_plot2,\n plot_nrows = as.numeric(input$nrows_feature_plot2)\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"FeaturePlot(use pairLRs)\",\n width = 600,\n height = 600\n ))\n })\n } else {\n output$gene_expression_distribution2 <- plotly::renderPlotly({\n plotly_spatialFeaturePlot(\n object,\n pairLR.use = input$selectize_pairLR_use,\n point.size = input$point.size_feature_plot2,\n do.binary = input$do.binary_feature_plot,\n cutoff = input$cut.off_feature_plot2,\n enriched.only = F,\n color.heatmap = input$palette_feature_plot2,\n direction = input$direction_feature_plot2,\n plot_nrows = as.numeric(input$nrows_feature_plot2)\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialFeaturePlot(use pairLRs)\",\n width = 600,\n height = 600\n ))\n })\n }\n\n\n ############################################################################\n output$netVisual_heatmap <- plotly::renderPlotly({\n suppressWarnings({\n netVisual_heatmap(object,\n measure = input$measure_heatmap,\n ) %>%\n plotly_netVisual_heatmap(\n palette.heatmap = input$palette_heatmap,\n direction.heatmap = input$direction_heatmap)\n })\n })\n\n output$rankNet <- plotly::renderPlotly({\n rankNet(\n object,\n mode = \"single\",\n measure = \"weight\",\n sources.use = input$select1_cell_group,\n targets.use = input$select2_cell_group,\n slot.name = input$slot.name_ranknet\n ) %>%\n plotly::ggplotly()\n })\n\n output$netAnalysis_contribution <- renderPlot({\n netAnalysis_contribution(\n object,\n signaling = input$pathway_contribution_plot,\n sources.use = input$select3_cell_group,\n targets.use = input$select4_cell_group,\n font.size = input$font.size_contribution_plot,\n font.size.title = input$font.size_contribution_plot,\n )\n },res = 96)\n ############################################################################\n observe({\n updateSelectizeInput(\n session,\n \"selectize_pathway\",\n selected = choices_pathways[1],\n choices = choices_pathways,\n server = TRUE\n )\n })\n output$Circle_plot <- renderPlot({\n netVisual_aggregate(\n object,\n signaling = input$selectize_pathway,\n layout = \"circle\",\n edge.width.max = input$slider_Circle_plot_edge.width.max,\n vertex.size.max = input$slider_Circle_plot_vertex.size.max,\n vertex.label.cex = input$slider_Circle_plot_vertex.label.cex\n )\n },res = 96)\n output$Spatial_plot <- renderPlot({\n netVisual_aggregate(\n object,\n signaling = input$selectize_pathway,\n layout = \"spatial\",\n edge.width.max = input$slider_Spatial_plot_edge.width.max,\n vertex.size.max = input$slider_Spatial_plot_vertex.size.max,\n vertex.label.cex = input$slider_Spatial_plot_vertex.label.cex,\n alpha.image = input$slider_Spatial_plot_alpha.image,\n point.size = input$slider_Spatial_plot_point.size,\n )\n })\n output$LR_pair_contribution <- plotly::renderPlotly({\n netAnalysis_contribution(\n object,\n signaling = input$selectize_pathway,\n font.size = 12,\n font.size.title = 14\n )\n })\n ############################################################################\n }\n\n\n # Running a Shiny app\n shinyApp(ui = ui, server = server,...)\n}\n", "middle_code": "function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n reduction = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE){\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(\"Please make sure `object@dr` contains a low-dimensional space of the data and specify the dimensionality reduction to use.\")\n }\n }\n samples <- object@meta$samples\n cell_labels <- object@idents\n data <- as.matrix(object@data)\n meta <- object@meta\n coords <- as.data.frame(coords)\n if (ncol(coords) >= 2) {\n coords <- coords[, c(1,2)]\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = -1))(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"\n }\n else {\n colormap <- color.heatmap\n }\n if (is.null(features) &\n is.null(signaling) & is.null(pairLR.use)) {\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)) {\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)) {\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)) {\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n df <- data.frame(x = coords[, 1], y = coords[, 2],\n cell_labels = cell_labels)\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n geneLR.return = TRUE,\n enriched.only = enriched.only,\n thresh = thresh\n )\n feature.use <- res$geneLR\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex,\n object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex,\n object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n }\n else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) >\n 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n }\n else if (length(intersect(feature.use, colnames(meta))) >\n 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[, feature.use, drop = FALSE])\n }\n else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \", cutoff, \"to the values...\",\n \"\\n\")\n data.use[data.use <= cutoff] <- 0\n }\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 0.95) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n }\n annotations <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_colour_gradientn(\n colours = colormap,\n guide = guide_colorbar(\n title = NULL,\n ticks = T,\n label = T,\n barwidth = 0.5\n ),\n na.value = \"grey90\"\n ) +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + ggtitle(feature.name) +\n theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n gg[[i]] <- g %>% plotly::ggplotly(height = 400)\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',annotations = annotations)\n }\n else {\n gg <- plotly::ggplotly(gg[[1]])\n }\n }\n else {\n set_individual_legend <- function(plt) {\n plt_build <- plotly::plotly_build(plt)\n len_legend <- length(plt_build$x$data)\n for (i in 1:len_legend) {\n plt_build$x$data[[i]]$legendgroup <- feature.name\n plt_build$x$data[[i]]$legendgrouptitle <- list(text=feature.name,font=list(size=12))\n }\n return(plt_build)\n }\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n enriched.only = enriched.only,\n thresh = thresh\n )\n LR.pair <- object@LR$LRsig[res$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL\n rownames(dataR) <- geneR\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \")\n }\n gg <- vector(\"list\", numFeature)\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 1) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n }\n annotations <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i,] > cutoff\n idx2 = dataR[i,] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\", ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i], geneR[i],\n \"Both\", \"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i], geneR[i], \"Both\",\n \"None\")\n if (length(setdiff(levels(group), unique(group))) >\n 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group),\n unique(group)))\n }\n df$feature.data <- group\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + guides(color = guide_legend(override.aes = list(size = legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n gg[[i]] <- g %>% plotly::ggplotly(\n type = 'scatter',\n mode='markers+text',\n ) %>% set_individual_legend()\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',\n annotations = annotations,\n legend = list(tracegroupgap = 10,title=list(text=''))\n )\n }\n else {\n gg <- plotly::ggplotly(gg[[1]],\n type = 'scatter',\n mode = 'markers') %>%\n plotly::layout(legend = list(title = list(text = '')))\n }\n }\n return(gg)\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/CellChat/R/visualization.R", "#' ggplot theme in CellChat\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#' @importFrom ggplot2 theme_classic element_rect theme element_blank element_line element_text\nCellChat_theme_opts <- function() {\n theme(strip.background = element_rect(colour = \"white\", fill = \"white\")) +\n theme_classic() +\n theme(panel.border = element_blank()) +\n theme(axis.line.x = element_line(color = \"black\")) +\n theme(axis.line.y = element_line(color = \"black\")) +\n theme(panel.grid.minor.x = element_blank(), panel.grid.minor.y = element_blank()) +\n theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_blank()) +\n theme(panel.background = element_rect(fill = \"white\")) +\n theme(legend.key = element_blank()) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))\n}\n\n\n#' Generate ggplot2 colors\n#'\n#' @param n number of colors to generate\n#' @importFrom grDevices hcl\n#' @export\n#'\nggPalette <- function(n) {\n hues = seq(15, 375, length = n + 1)\n grDevices::hcl(h = hues, l = 65, c = 100)[1:n]\n}\n\n#' Generate colors from a customed color palette\n#'\n#' @param n number of colors\n#'\n#' @return A color palette for plotting\n#' @importFrom grDevices colorRampPalette\n#'\n#' @export\n#'\nscPalette <- function(n) {\n colorSpace <- c('#E41A1C','#377EB8','#4DAF4A','#984EA3','#F29403','#F781BF','#BC9DCC','#A65628','#54B0E4','#222F75','#1B9E77','#B2DF8A',\n '#E3BE00','#FB9A99','#E7298A','#910241','#00CDD1','#A6CEE3','#CE1261','#5E4FA2','#8CA77B','#00441B','#DEDC00','#DCF0B9','#8DD3C7','#999999')\n if (n <= length(colorSpace)) {\n colors <- colorSpace[1:n]\n } else {\n colors <- grDevices::colorRampPalette(colorSpace)(n)\n }\n return(colors)\n}\n\n#' Visualize the inferred cell-cell communication network\n#'\n#' Automatically save plots in the current working directory.\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param top the fraction of interactions to show (0 < top <= 1)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max.individual the maximum weight of edge when plotting the individual L-R netwrok; defualt = max(net)\n#' @param edge.weight.max.aggregate the maximum weight of edge when plotting the aggregated signaling pathway network\n#' @param edge.width.max The maximum edge width for visualization\n#' @param layout \"hierarchy\", \"circle\" or \"chord\"\n#' @param height height of plot\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param pt.title font size of the text\n#' @param title.space the space between the title and plot\n#' @param vertex.label.cex The label size of vertex in the network\n#' @param out.format the format of output figures: svg, png and pdf\n#'\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the network mediated by ligand-receptor using \"circle\" or \"chord\"\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x, text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`. NB: some parameters might be not supported\n#' @importFrom svglite svglite\n#' @importFrom grDevices dev.off pdf\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#'\nnetVisual <- function(object, signaling, signaling.name = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max.individual = NULL, edge.weight.max.aggregate = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, pt.title = 12, title.space = 6, vertex.label.cex = 0.8,from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n out.format = c(\"svg\",\"png\"),\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n if (is.null(edge.weight.max.individual)) {\n edge.weight.max.individual = max(prob)\n }\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.null(edge.weight.max.aggregate)) {\n edge.weight.max.aggregate = max(prob.sum)\n }\n\n if (layout == \"hierarchy\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_individual.svg\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_individual.png\"), width = 8, height = nRow*height, units = \"in\",res = 300)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name, \"_hierarchy_individual.pdf\"), width = 8, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_individual.pdf\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n\n\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_aggregate.svg\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_aggregate.png\"), width = 7, height = 1*height, units = \"in\",res = 300)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name, \"_hierarchy_aggregate.pdf\"), width = 7, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_aggregate.pdf\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n\n } else if (layout == \"circle\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"spatial\") {\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n # par(mfrow=c(nRow,1))\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n #signalName_i <- paste0(pairLR$ligand[i], \"-\",pairLR$receptor[i], sep = \"\")\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"chord\") {\n if (is.element(\"svg\", out.format)) {\n\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n # gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n\n # prob.sum <- apply(prob, c(1,2), sum)\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n # grDevices::pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n }\n\n}\n\n\n#' Visualize the inferred signaling network of signaling pathways by aggregating all L-R pairs\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param layout \"hierarchy\", \"circle\", \"chord\" or \"spatial\"\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param pt.title font size of the text\n#' @param title.space the space between the title and plot\n#' @param vertex.label.cex The label size of vertex in the network\n#'\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x,text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`,`netVisual_spatial`. NB: some parameters might be not supported\n#' @importFrom grDevices recordPlot\n#'\n#' @return an object of class \"recordedplot\" or ggplot\n#' @export\n#'\n#'\nnetVisual_aggregate <- function(object, signaling, signaling.name = NULL, color.use = NULL, thresh = 0.05, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"),\n pt.title = 12, title.space = 6, vertex.label.cex = 0.8,\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20,\n ...) {\n layout <- match.arg(layout)\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n\n if (layout == \"hierarchy\") {\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.null(edge.weight.max)) {\n edge.weight.max = max(prob.sum)\n }\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n } else if (layout == \"circle\") {\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n gg <- netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n } else if (layout == \"spatial\") {\n prob.sum <- apply(prob, c(1,2), sum)\n if (vertex.weight == \"incoming\"){\n if (length(slot(object, \"netP\")$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n vertex.weight = object@netP$centr[[signaling]]$indeg\n } else if (vertex.weight == \"outgoing\"){\n if (length(slot(object, \"netP\")$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n vertex.weight = object@netP$centr[[signaling]]$outdeg\n }\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n\n } else if (layout == \"chord\") {\n prob.sum <- apply(prob, c(1,2), sum)\n gg <- netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y= legend.pos.y)\n }\n\n return(gg)\n\n}\n\n\n\n#' Visualize the inferred signaling network of individual L-R pairs\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param pairLR.use a char vector or a data frame consisting of one column named \"interaction_name\", defining the L-R pairs of interest\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector.\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex in the network\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param graphics.init whether do graphics initiation using par(...). If graphics.init=FALSE, USERS can use par() in a more fexible way\n#' @param layout \"hierarchy\", \"circle\" or \"chord\"\n#' @param height height of plot\n#' @param thresh threshold of the p-value for determining significant interaction\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n# #' @param vertex.size Deprecated. Use `vertex.weight`\n\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the figures using \"circle\" or \"chord\"\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x, text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`. NB: some parameters might be not supported\n#' @importFrom grDevices dev.off pdf\n#'\n#' @return an object of class \"recordedplot\"\n#' @export\n#'\n#'\nnetVisual_individual <- function(object, signaling, signaling.name = NULL, pairLR.use = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex = 0.8,\n weight.scale = TRUE, edge.weight.max = NULL, edge.width.max=8, graphics.init = TRUE,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, #from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n # if (!is.null(vertex.size)) {\n # warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n # }\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n if (!is.null(pairLR.use)) {\n if (is.data.frame(pairLR.use)) {\n pairLR.name <- intersect(pairLR.name, as.character(pairLR.use$interaction_name))\n } else {\n pairLR.name <- intersect(pairLR.name, as.character(pairLR.use))\n }\n\n if (length(pairLR.name) == 0) {\n stop(\"There is no significant communication for the input L-R pairs!\")\n }\n }\n\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n if (is.null(edge.weight.max)) {\n edge.weight.max = max(prob)\n }\n\n if (layout == \"hierarchy\") {\n if (graphics.init) {\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n }\n\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i,...)\n }\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n\n } else if (layout == \"circle\") {\n # par(mfrow=c(nRow,1))\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n gg[[i]] <- netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n } else if (layout == \"spatial\") {\n # par(mfrow=c(nRow,1))\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n gg[[i]] <- netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n } else if (layout == \"chord\") {\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n gg[[i]] <- netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y)\n }\n }\n return(gg)\n}\n\n\n\n#' Hierarchy plot of cell-cell communications sending to cell groups in vertex.receiver\n#'\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net a weighted matrix defining the signaling network\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether rescale the edge weights\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.dist the distance between labels and dot position\n#' @param space.v the space between different columns in the plot\n#' @param space.h the space between different rows in the plot\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param alpha.edge the transprency of edge\n#' @param label.edge whether label edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_\n#' @importFrom grDevices adjustcolor recordPlot\n#' @importFrom shape Arrows\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_hierarchy1 <- function(net, vertex.receiver, color.use = NULL, title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight=20, vertex.weight.max = NULL, vertex.size.max = NULL,\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6,\n label.dist = 2.8, space.v = 1.5, space.h = 1.6, shape= NULL, label.edge=FALSE,edge.curved=0, margin=0.2,\n vertex.label.cex=0.6,vertex.label.color= \"black\",arrow.width=1,arrow.size = 0.2,edge.label.color='black',edge.label.cex=0.5, vertex.size = NULL){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n cells.level <- rownames(net)\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n if (is.null(color.use)) {\n color.use <- scPalette(nrow(net))\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+6\n\n m <- length(vertex.receiver)\n net2 <- net\n reorder.row <- c(vertex.receiver, setdiff(1:nrow(net),vertex.receiver))\n net2 <- net2[reorder.row,vertex.receiver]\n # Expand out to symmetric (M+N)x(M+N) matrix\n m1 <- nrow(net2); n1 <- ncol(net2)\n net3 <- rbind(cbind(matrix(0, m1, m1), net2), matrix(0, n1, m1+n1))\n\n row.names(net3) <- c(row.names(net)[vertex.receiver], row.names(net)[setdiff(1:m1,vertex.receiver)], rep(\"\",m))\n colnames(net3) <- row.names(net3)\n color.use3 <- c(color.use[vertex.receiver], color.use[setdiff(1:m1,vertex.receiver)], rep(\"#FFFFFF\",length(vertex.receiver)))\n color.use3.frame <- c(color.use[vertex.receiver], color.use[setdiff(1:m1,vertex.receiver)], color.use[vertex.receiver])\n\n if (length(vertex.weight) != 1) {\n vertex.weight = c(vertex.weight[vertex.receiver], vertex.weight[setdiff(1:m1,vertex.receiver)],vertex.weight[vertex.receiver])\n }\n if (is.null(shape)) {\n shape <- c(rep(\"circle\",m), rep(\"circle\", m1-m), rep(\"circle\",m))\n }\n\n g <- graph_from_adjacency_matrix(net3, mode = \"directed\", weighted = T)\n edge.start <- ends(g, es=E(g), names=FALSE)\n coords <- matrix(NA, nrow(net3), 2)\n coords[1:m,1] <- 0; coords[(m+1):m1,1] <- space.h; coords[(m1+1):nrow(net3),1] <- space.h/2;\n coords[1:m,2] <- seq(space.v, 0, by = -space.v/(m-1)); coords[(m+1):m1,2] <- seq(space.v, 0, by = -space.v/(m1-m-1));coords[(m1+1):nrow(net3),2] <- seq(space.v, 0, by = -space.v/(n1-1));\n coords_scale<-coords\n\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use3[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use3.frame[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n E(g)$label<-E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n # E(g)$width<-0.3+edge.max.width/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n E(g)$width<- 0.3+E(g)$weight/edge.weight.max*edge.width.max\n }else{\n E(g)$width<-0.3+edge.width.max*E(g)$weight\n }\n\n E(g)$arrow.width<-arrow.width\n E(g)$arrow.size<-arrow.size\n E(g)$label.color<-edge.label.color\n E(g)$label.cex<-edge.label.cex\n E(g)$color<-adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n\n label.dist <- c(rep(space.h*label.dist,m), rep(space.h*label.dist, m1-m),rep(0, nrow(net3)-m1))\n label.locs <- c(rep(-pi, m), rep(0, m1-m),rep(-pi, nrow(net3)-m1))\n # text.pos <- cbind(c(-space.h/1.5, space.h/10, space.h/1.2), space.v-space.v/10)\n text.pos <- cbind(c(-space.h/1.5, space.h/22, space.h/1.5), space.v-space.v/7)\n igraph::add.vertex.shape(\"fcircle\", clip=igraph::igraph.shape.noclip,plot=mycircle, parameters=list(vertex.frame.color=1, vertex.frame.width=1))\n plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin,rescale=T,vertex.shape=\"fcircle\", vertex.frame.width = c(rep(1,m1), rep(2,nrow(net3)-m1)),\n vertex.label.degree=label.locs, vertex.label.dist=label.dist, vertex.label.family=\"Helvetica\")\n text(text.pos, c(\"Source\",\"Target\",\"Source\"), cex = 0.8, col = c(\"#c51b7d\",\"#c51b7d\",\"#2f6661\"))\n arrow.pos1 <- c(-space.h/1.5, space.v-space.v/4, space.h/100000, space.v-space.v/4)\n arrow.pos2 <- c(space.h/1.5, space.v-space.v/4, space.h/20, space.v-space.v/4)\n shape::Arrows(arrow.pos1[1], arrow.pos1[2], arrow.pos1[3], arrow.pos1[4], col = \"#c51b7d\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n shape::Arrows(arrow.pos2[1], arrow.pos2[2], arrow.pos2[3], arrow.pos2[4], col = \"#2f6661\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n if (!is.null(title.name)) {\n title.pos = c(space.h/8, space.v)\n text(title.pos[1],title.pos[2],paste0(title.name, \" signaling network\"), cex = 1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Hierarchy plot of cell-cell communication sending to cell groups not in vertex.receiver\n#'\n#' This function loads the significant interactions as a weighted matrix, and colors\n#' represent different types of cells as a structure. The width of edges represent the strength of the communication.\n#'\n#' @param net a weighted matrix defining the signaling network\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether rescale the edge weights\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.dist the distance between labels and dot position\n#' @param space.v the space between different columns in the plot\n#' @param space.h the space between different rows in the plot\n#' @param label.edge Whether or not shows the label of edges (number of connections between different cell types)\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_\n#' @importFrom grDevices adjustcolor recordPlot\n#' @importFrom shape Arrows\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_hierarchy2 <-function(net, vertex.receiver, color.use = NULL, title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight=20, vertex.weight.max = NULL, vertex.size.max = NULL,\n edge.weight.max = NULL, edge.width.max=8,alpha.edge = 0.6,\n label.dist = 2.8, space.v = 1.5, space.h = 1.6, shape= NULL, label.edge=FALSE,edge.curved=0, margin=0.2,\n vertex.label.cex=0.6,vertex.label.color= \"black\",arrow.width=1,arrow.size = 0.2,edge.label.color='black',edge.label.cex=0.5, vertex.size = NULL){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- levels(object@idents)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- levels(object@idents)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- levels(object@idents)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n\n if (is.null(color.use)) {\n color.use <- scPalette(nrow(net))\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+6\n\n m <- length(vertex.receiver)\n m0 <- nrow(net)-length(vertex.receiver)\n net2 <- net\n reorder.row <- c(setdiff(1:nrow(net),vertex.receiver), vertex.receiver)\n net2 <- net2[reorder.row,vertex.receiver]\n # Expand out to symmetric (M+N)x(M+N) matrix\n m1 <- nrow(net2); n1 <- ncol(net2)\n net3 <- rbind(cbind(matrix(0, m1, m1), net2), matrix(0, n1, m1+n1))\n row.names(net3) <- c(row.names(net)[setdiff(1:m1,vertex.receiver)],row.names(net)[vertex.receiver], rep(\"\",m))\n colnames(net3) <- row.names(net3)\n color.use3 <- c(color.use[setdiff(1:m1,vertex.receiver)],color.use[vertex.receiver], rep(\"#FFFFFF\",length(vertex.receiver)))\n color.use3.frame <- c(color.use[setdiff(1:m1,vertex.receiver)], color.use[vertex.receiver], color.use[vertex.receiver])\n\n\n if (length(vertex.weight) != 1) {\n vertex.weight = c(vertex.weight[setdiff(1:m1,vertex.receiver)], vertex.weight[vertex.receiver], vertex.weight[vertex.receiver])\n }\n if (is.null(shape)) {\n shape <- rep(\"circle\",nrow(net3))\n }\n\n g <- graph_from_adjacency_matrix(net3, mode = \"directed\", weighted = T)\n edge.start <- ends(g, es=igraph::E(g), names=FALSE)\n coords <- matrix(NA, nrow(net3), 2)\n coords[1:m0,1] <- 0; coords[(m0+1):m1,1] <- space.h; coords[(m1+1):nrow(net3),1] <- space.h/2;\n coords[1:m0,2] <- seq(space.v, 0, by = -space.v/(m0-1)); coords[(m0+1):m1,2] <- seq(space.v, 0, by = -space.v/(m1-m0-1));coords[(m1+1):nrow(net3),2] <- seq(space.v, 0, by = -space.v/(n1-1));\n coords_scale<-coords\n\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use3[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use3.frame[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n # E(g)$width<-0.3+edge.max.width/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n igraph::E(g)$color<-adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n\n label.dist <- c(rep(space.h*label.dist,m), rep(space.h*label.dist, m1-m),rep(0, nrow(net3)-m1))\n label.locs <- c(rep(-pi, m0), rep(0, m1-m0),rep(-pi, nrow(net3)-m1))\n #text.pos <- cbind(c(-space.h/1.5, space.h/10, space.h/1.2), space.v-space.v/10)\n text.pos <- cbind(c(-space.h/1.5, space.h/22, space.h/1.5), space.v-space.v/7)\n igraph::add.vertex.shape(\"fcircle\", clip=igraph::igraph.shape.noclip,plot=mycircle, parameters=list(vertex.frame.color=1, vertex.frame.width=1))\n plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin,rescale=T,vertex.shape=\"fcircle\", vertex.frame.width = c(rep(1,m1), rep(2,nrow(net3)-m1)),\n vertex.label.degree=label.locs, vertex.label.dist=label.dist, vertex.label.family=\"Helvetica\")\n text(text.pos, c(\"Source\",\"Target\",\"Source\"), cex = 0.8, col = c(\"#c51b7d\",\"#2f6661\",\"#2f6661\"))\n\n arrow.pos1 <- c(-space.h/1.5, space.v-space.v/4, space.h/100000, space.v-space.v/4)\n arrow.pos2 <- c(space.h/1.5, space.v-space.v/4, space.h/20, space.v-space.v/4)\n shape::Arrows(arrow.pos1[1], arrow.pos1[2], arrow.pos1[3], arrow.pos1[4], col = \"#c51b7d\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n shape::Arrows(arrow.pos2[1], arrow.pos2[2], arrow.pos2[3], arrow.pos2[4], col = \"#2f6661\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n\n if (!is.null(title.name)) {\n title.pos = c(space.h/8, space.v)\n text(title.pos[1],title.pos[2],paste0(title.name, \" signaling network\"), cex = 1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Circle plot of cell-cell communication network\n#'\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net A weighted matrix representing the connections\n#' @param color.use Colors represent different cell groups\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.edge Whether or not shows the label of edges\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param layout The layout specification. It must be a call to a layout\n#' specification function.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param text.x,text.y the x- and y-coordinates to add the text\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_ in_circle\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_circle <-function(net, color.use = NULL,title.name = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex=1,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6, label.edge = FALSE,edge.label.color='black',edge.label.cex=0.8,\n edge.curved=0.2,shape='circle',layout=in_circle(), margin=0.2, vertex.size = NULL,\n arrow.width=1,arrow.size = 0.2,\n text.x = 0, text.y = 1.5){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use)) | (!is.null(idents.use)) ) {\n if (is.null(rownames(net))) {\n stop(\"The input weighted matrix should have rownames!\")\n }\n cells.level <- rownames(net)\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n df.net <- filter(df.net, (source %in% idents.use) | (target %in% idents.use))\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (is.null(color.use)) {\n color.use = scPalette(nrow(net))\n names(color.use) <- rownames(net)\n } else {\n if (is.null(names(color.use))) {\n stop(\"The input `color.use` should be a named vector! \\n\")\n }\n }\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx.isolate <- intersect(idx1, idx2)\n if (length(idx.isolate) > 0) {\n net <- net[-idx.isolate, ]\n net <- net[, -idx.isolate]\n color.use = color.use[-idx.isolate]\n if (length(unique(vertex.weight)) > 1) {\n vertex.weight <- vertex.weight[-idx.isolate]\n }\n }\n }\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edge.start <- igraph::ends(g, es=igraph::E(g), names=FALSE)\n coords<-layout_(g,layout)\n if(nrow(coords)!=1){\n coords_scale=scale(coords)\n }else{\n coords_scale<-coords\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n\n loop.angle<-ifelse(coords_scale[igraph::V(g),1]>0,-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]),pi-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]))\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n #E(g)$width<-0.3+edge.width.max/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n igraph::E(g)$color<- grDevices::adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n igraph::E(g)$loop.angle <- rep(0, length(igraph::E(g)))\n\n if(sum(edge.start[,2]==edge.start[,1])!=0){\n igraph::E(g)$loop.angle[which(edge.start[,2]==edge.start[,1])]<-loop.angle[edge.start[which(edge.start[,2]==edge.start[,1]),1]]\n }\n radian.rescale <- function(x, start=0, direction=1) {\n c.rotate <- function(x) (x + start) %% (2 * pi) * direction\n c.rotate(scales::rescale(x, c(0, 2 * pi), range(x)))\n }\n label.locs <- radian.rescale(x=1:length(igraph::V(g)), direction=-1, start=0)\n label.dist <- vertex.weight/max(vertex.weight)+2\n plot(g,edge.curved=edge.curved,vertex.shape=shape,layout=coords_scale,margin=margin, vertex.label.dist=label.dist,\n vertex.label.degree=label.locs, vertex.label.family=\"Helvetica\", edge.label.family=\"Helvetica\") # \"sans\"\n if (!is.null(title.name)) {\n text(text.x,text.y,title.name, cex = 1.1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n\n#' generate circle symbol\n#'\n#' @param coords coordinates of points\n#' @param v vetex\n#' @param params parameters\n#' @importFrom graphics symbols\n#' @return\nmycircle <- function(coords, v=NULL, params) {\n vertex.color <- params(\"vertex\", \"color\")\n if (length(vertex.color) != 1 && !is.null(v)) {\n vertex.color <- vertex.color[v]\n }\n vertex.size <- 1/200 * params(\"vertex\", \"size\")\n if (length(vertex.size) != 1 && !is.null(v)) {\n vertex.size <- vertex.size[v]\n }\n vertex.frame.color <- params(\"vertex\", \"frame.color\")\n if (length(vertex.frame.color) != 1 && !is.null(v)) {\n vertex.frame.color <- vertex.frame.color[v]\n }\n vertex.frame.width <- params(\"vertex\", \"frame.width\")\n if (length(vertex.frame.width) != 1 && !is.null(v)) {\n vertex.frame.width <- vertex.frame.width[v]\n }\n\n mapply(coords[,1], coords[,2], vertex.color, vertex.frame.color,\n vertex.size, vertex.frame.width,\n FUN=function(x, y, bg, fg, size, lwd) {\n symbols(x=x, y=y, bg=bg, fg=fg, lwd=lwd,\n circles=size, add=TRUE, inches=FALSE)\n })\n}\n\n\n#' Spatial plot of cell-cell communication network\n#'\n#' Autocrine interactions are omitted on this plot. Group centroids may be not accurate for some data due to complex geometry.\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net A weighted matrix representing the connections\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param meta a data frame with at least two columns named `labels` and `samples`.\n#' `meta$labels` is a vector giving the group label of each cell/spot. `meta$samples` is a factor vector defining the sample labels of each dataset. The length should be the same as the number of rows in `coordinates`.\n#' @param sample.use the sample used for visualization, which should be the element in `meta$samples`.\n#' @param color.use Colors represent different cell groups\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param remove.loop whether remove the self-loop in the communication network. Default: TRUE\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param alpha.edge the transprency of edge\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param arrow.angle The width of arrows\n#' @param alpha.image the transparency of individual spots\n# #' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param point.size the size of spots\n#' @param legend.size the size of legend\n#' @importFrom igraph graph_from_adjacency_matrix get.edgelist ends E V\n#' @import ggplot2\n#' @importFrom ggnetwork geom_nodetext_repel\n#' @return an object of ggplot\n#' @export\nnetVisual_spatial <-function(net, coordinates, meta, sample.use = NULL, color.use = NULL,title.name = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE, remove.loop = TRUE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex = 5,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, edge.curved=0.2, alpha.edge = 0.6, arrow.angle = 5, arrow.size = 0.2, alpha.image = 0.15, point.size = 1.5, legend.size = 5){\n cells.level <- rownames(net)\n labels <- meta$labels\n samples <- meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n num_cluster <- length(cells.level)\n node_coords <- matrix(0, nrow = num_cluster, ncol = 2)\n for (i in c(1:num_cluster)) {\n node_coords[i,1] <- median(coordinates[as.character(labels) == cells.level[i], 1])\n node_coords[i,2] <- median(coordinates[as.character(labels) == cells.level[i], 2])\n }\n rownames(node_coords) <- cells.level\n\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use)) | (!is.null(idents.use)) ) {\n if (is.null(rownames(net))) {\n stop(\"The input weighted matrix should have rownames!\")\n }\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n df.net <- filter(df.net, (source %in% idents.use) | (target %in% idents.use))\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n\n if (remove.loop) {\n diag(net) <- 0\n }\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n node_coords <- node_coords[-idx, ]\n cells.level <- cells.level[-idx]\n }\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edgelist <- get.edgelist(g)\n # loop_curve = c()\n # for (i in c(1:nrow(edgelist))) {\n # if (edgelist[i,1] == edgelist[i,2]){\n # loop_curve = c(loop_curve ,i)\n # }\n # }\n # edgelist <- edgelist[-loop_curve,]\n\n edges <- data.frame(node_coords[edgelist[,1],,drop =FALSE], node_coords[edgelist[,2],,drop =FALSE])\n colnames(edges) <- c(\"X1\",\"Y1\",\"X2\",\"Y2\")\n node_coords = data.frame(node_coords)\n node_idents = factor(cells.level, levels = cells.level)\n node_family = data.frame(node_coords,node_idents)\n if (is.null(color.use)) {\n color.use = scPalette(length(igraph::V(g)))\n names(color.use) <- cells.level\n }\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n # width of edge\n if (weight.scale == TRUE) {\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n gg <- ggplot(data=node_family,aes(X1, X2)) +\n geom_curve(aes(x=X1, y=Y1, xend = X2, yend = Y2), data=edges, size = igraph::E(g)$width, curvature = edge.curved, alpha = alpha.edge, arrow = arrow(angle = arrow.angle, type = \"closed\",length = unit(arrow.size, \"inches\")),colour=color.use[edgelist[,1]]) +\n geom_point(aes(X1, X2,colour = node_idents), data=node_family, size = vertex.weight,show.legend = TRUE) +scale_color_manual(values = color.use) +\n guides(color = guide_legend(override.aes = list(size=legend.size))) +\n xlab(NULL) + ylab(NULL) +\n coord_fixed() + theme(aspect.ratio = 1)+ theme(legend.key = element_blank()) +\n theme(panel.background = element_blank(),axis.ticks = element_blank(), panel.border = element_blank(),axis.text=element_blank(),legend.title = element_blank())\n\n gg <- gg + geom_point(aes(x_cent, y_cent), data = coordinates,colour = color.use[labels],alpha = alpha.image, size = point.size, show.legend = FALSE)\n gg <- gg + scale_y_reverse()\n if (vertex.label.cex > 0){\n gg <- gg + ggnetwork::geom_nodetext_repel(aes(label = node_idents), color=\"black\", size = vertex.label.cex)\n }\n if (!is.null(title.name)){\n gg <- gg + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0))\n }\n\n gg\n return(gg)\n\n}\n\n\n\n\n\n\n#' Circle plot showing differential cell-cell communication network between two datasets\n#'\n#' The width of edges represent the relative number of interactions or interaction strength.\n#' Red (or blue) colored edges represent increased (or decreased) signaling in the second dataset compared to the first one.\n#'\n#' @param object A merged CellChat objects\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param color.use Colors represent different cell groups\n#' @param color.edge Colors for indicating whether the signaling is increased (`color.edge[1]`) or decreased (`color.edge[2]`)\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.edge Whether or not shows the label of edges\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param layout The layout specification. It must be a call to a layout\n#' specification function.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n# #' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_ in_circle\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_diffInteraction <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\", \"count.merged\", \"weight.merged\"), color.use = NULL, color.edge = c('#b2182b','#2166ac'), title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = 15, vertex.label.cex=1,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6, label.edge = FALSE,edge.label.color='black',edge.label.cex=0.8,\n edge.curved=0.2,shape='circle',layout=in_circle(), margin=0.2,\n arrow.width=1,arrow.size = 0.2){\n options(warn = -1)\n measure <- match.arg(measure)\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n if (measure %in% c(\"count\", \"count.merged\")) {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure %in% c(\"weight\", \"weight.merged\")) {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n net <- net.diff\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- rownames(net.diff)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n net[is.na(net)] <- 0\n }\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n net[abs(net) < stats::quantile(abs(net), probs = 1-top, na.rm= T)] <- 0\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edge.start <- igraph::ends(g, es=igraph::E(g), names=FALSE)\n coords<-layout_(g,layout)\n if(nrow(coords)!=1){\n coords_scale=scale(coords)\n }else{\n coords_scale<-coords\n }\n if (is.null(color.use)) {\n color.use = scPalette(length(igraph::V(g)))\n }\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n\n loop.angle<-ifelse(coords_scale[igraph::V(g),1]>0,-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]),pi-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]))\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n #igraph::E(g)$color<- grDevices::adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n igraph::E(g)$color <- ifelse(igraph::E(g)$weight > 0, color.edge[1],color.edge[2])\n igraph::E(g)$color <- grDevices::adjustcolor(igraph::E(g)$color, alpha.edge)\n\n igraph::E(g)$weight <- abs(igraph::E(g)$weight)\n\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n #E(g)$width<-0.3+edge.width.max/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n igraph::E(g)$loop.angle <- 0\n if(sum(edge.start[,2]==edge.start[,1])!=0){\n igraph::E(g)$loop.angle[which(edge.start[,2]==edge.start[,1])]<-loop.angle[edge.start[which(edge.start[,2]==edge.start[,1]),1]]\n }\n radian.rescale <- function(x, start=0, direction=1) {\n c.rotate <- function(x) (x + start) %% (2 * pi) * direction\n c.rotate(scales::rescale(x, c(0, 2 * pi), range(x)))\n }\n label.locs <- radian.rescale(x=1:length(igraph::V(g)), direction=-1, start=0)\n label.dist <- vertex.weight/max(vertex.weight)+2\n plot(g,edge.curved=edge.curved,vertex.shape=shape,layout=coords_scale,margin=margin, vertex.label.dist=label.dist,\n vertex.label.degree=label.locs, vertex.label.family=\"Helvetica\", edge.label.family=\"Helvetica\") # \"sans\"\n if (!is.null(title.name)) {\n text(0,1.5,title.name, cex = 1.1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Visualization of network using heatmap\n#'\n#' This heatmap can be used to 1) show differential number of interactions or interaction strength in the cell-cell communication network between two datasets;\n#' 2) the number of interactions or interaction strength in a single dataset;\n#' 3) the inferred cell-cell communication network in a single dataset, defined by `signaling`. Please see @Details below for detailed explanations of this heatmap plot.\n#'\n#' When show differential number of interactions or interaction strength in the cell-cell communication network between two datasets, the width of edges represent the relative number of interactions or interaction strength.\n#' Red (or blue) colored edges represent increased (or decreased) signaling in the second dataset compared to the first one.\n#'\n#' The top colored bar plot represents the sum of absolute values displayed in each column of the heatmap. The right colored bar plot represents the sum of absolute values in each row.\n#'\n#'\n#' @param object A merged CellChat object or a single CellChat object\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param signaling a character vector giving the name of signaling networks in a single CellChat object\n#' @param slot.name the slot name of object. Set is to be \"netP\" if input signaling is a pathway name; Set is to be \"net\" if input signaling is a ligand-receptor pair\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap A vector of two colors corresponding to max/min values, or a color name in brewer.pal only when the data in the heatmap do not contain negative values.\n#' By default, color.heatmap = c('#2166ac','#b2182b') when taking a merged CellChat object as input; color.heatmap = \"Reds\" when taking a single CellChat object as input.\n#' @param title.name the name of the title\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param row.show,col.show a vector giving the index or the name of row or columns to show in the heatmap\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation anno_barplot rowAnnotation\n#' @return an object of ComplexHeatmap\n#' @export\nnetVisual_heatmap <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\"), signaling = NULL, slot.name = c(\"netP\", \"net\"), color.use = NULL, color.heatmap = NULL,\n title.name = NULL, width = NULL, height = NULL, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE,\n sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, row.show = NULL, col.show = NULL){\n if (!is.null(measure)) {\n measure <- match.arg(measure)\n }\n slot.name <- match.arg(slot.name)\n if (class(object@net[[1]]) == \"list\") {\n message(\"Do heatmap based on a merged object \\n\")\n if (is.null(color.heatmap)) {\n color.heatmap <- c('#2166ac','#b2182b')\n }\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n legend.name = \"Relative values\"\n } else {\n message(\"Do heatmap based on a single object \\n\")\n if (is.null(color.heatmap)) {\n color.heatmap <- \"Reds\"\n }\n if (!is.null(signaling)) {\n prob <- slot(object, slot.name)$prob\n if (slot.name == \"net\") {\n prob[object@net$pval > thresh] <- 0\n }\n net.diff <- prob[,,signaling]\n if (is.null(title.name)) {\n title.name = paste0(signaling, \" signaling network\")\n }\n legend.name <- \"Communication Prob.\"\n } else if (!is.null(measure)) {\n net.diff <- object@net[[measure]]\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Interaction strength\"\n }\n }\n legend.name <- title.name\n }\n }\n\n net <- net.diff\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- rownames(net.diff)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (is.null(color.use)) {\n color.use <- scPalette(ncol(net))\n }\n names(color.use) <- colnames(net)\n color.use.row <- color.use\n color.use.col <- color.use\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n #idx <- intersect(idx1, idx2)\n # if (length(idx) > 0) {\n # net <- net[-idx, ]\n # net <- net[, -idx]\n # }\n if (length(idx1) > 0) {\n net <- net[-idx1, ]\n color.use.row <- color.use.row[-idx1]\n }\n if (length(idx2) > 0) {\n net <- net[, -idx2]\n color.use.col <- color.use.col[-idx2]\n }\n }\n\n mat <- net\n if (!is.null(row.show)) {\n mat <- mat[row.show, , drop=FALSE]\n color.use.row <- color.use.row[row.show]\n }\n if (!is.null(col.show)) {\n mat <- mat[ ,col.show, drop=FALSE]\n color.use.col <- color.use.col[col.show]\n }\n\n\n if (min(mat) < 0) {\n color.heatmap.use = colorRamp3(c(min(mat), 0, max(mat)), c(color.heatmap[1], \"#f7f7f7\", color.heatmap[2]))\n colorbar.break <- c(round(min(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",min(mat, na.rm = T)))+1), 0, round(max(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",max(mat, na.rm = T)))+1))\n # color.heatmap.use = colorRamp3(c(seq(min(mat), -(max(mat)-min(max(mat)))/9, length.out = 4), 0, seq((max(mat)-min(max(mat)))/9, max(mat), length.out = 4)), RColorBrewer::brewer.pal(n = 9, name = color.heatmap))\n } else {\n if (length(color.heatmap) == 3) {\n color.heatmap.use = colorRamp3(c(0, min(mat), max(mat)), color.heatmap)\n } else if (length(color.heatmap) == 2) {\n color.heatmap.use = colorRamp3(c(min(mat), max(mat)), color.heatmap)\n } else if (length(color.heatmap) == 1) {\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n }\n colorbar.break <- c(round(min(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",min(mat, na.rm = T)))+1), round(max(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",max(mat, na.rm = T)))+1))\n }\n # col_fun(as.vector(mat))\n\n df.col<- data.frame(group = colnames(mat)); rownames(df.col) <- colnames(mat)\n df.row<- data.frame(group = rownames(mat)); rownames(df.row) <- rownames(mat)\n col_annotation <- HeatmapAnnotation(df = df.col, col = list(group = color.use.col),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n row_annotation <- HeatmapAnnotation(df = df.row, col = list(group = color.use.row), which = \"row\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ha1 = rowAnnotation(Strength = anno_barplot(rowSums(abs(mat)), border = FALSE,gp = gpar(fill = color.use.row, col=color.use.row)), show_annotation_name = FALSE)\n ha2 = HeatmapAnnotation(Strength = anno_barplot(colSums(abs(mat)), border = FALSE,gp = gpar(fill = color.use.col, col=color.use.col)), show_annotation_name = FALSE)\n\n if (sum(abs(mat) > 0) == 1) {\n color.heatmap.use = c(\"white\", color.heatmap.use)\n } else {\n mat[mat == 0] <- NA\n }\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = legend.name,\n bottom_annotation = col_annotation, left_annotation =row_annotation, top_annotation = ha2, right_annotation = ha1,\n cluster_rows = cluster.rows,cluster_columns = cluster.rows,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n # width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = title.name,column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 90,\n row_title = \"Sources (Sender)\",row_title_gp = gpar(fontsize = font.size.title),row_title_rot = 90,\n heatmap_legend_param = list(title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, #at = colorbar.break,\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n # draw(ht1)\n return(ht1)\n}\n\n\n#' Visualization of (differential) number of interactions\n#'\n#' @param object A merged CellChat object or a single CellChat object\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param invert.source,invert.target retain the complementary set\n#' @param signaling a character vector giving the name of signaling networks in a single CellChat object\n#' @param slot.name the slot name of object. Set is to be \"netP\" if input signaling is a pathway name; Set is to be \"net\" if input signaling is a ligand-receptor pair\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name the name of the title\n#' @param x.lab.rot do rotation for the x-ticklabels\n#' @param ... Parameters passing to `barplot_internal`\n#' @importFrom methods slot\n#' @return an object of ggplot\n#' @export\nnetVisual_barplot <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\"), sources.use = NULL, targets.use = NULL, invert.source = FALSE, invert.target = FALSE,signaling = NULL, slot.name = c(\"netP\", \"net\"), color.use = NULL,\n title.name = NULL,x.lab.rot = FALSE,...){\n if (!is.null(measure)) {\n measure <- match.arg(measure)\n }\n slot.name <- match.arg(slot.name)\n if (is.list(object@net[[1]])) {\n message(\"Show differential number of interactions based on a merged object \\n\")\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n } else {\n message(\"Show number of interactions based on a single object \\n\")\n if (!is.null(signaling)) {\n net.diff <- slot(object, slot.name)$prob[,,signaling]\n if (is.null(title.name)) {\n title.name = paste0(signaling, \" signaling network\")\n }\n } else if (!is.null(measure)) {\n net.diff <- object@net[[measure]]\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Interaction strength\"\n }\n }\n }\n }\n\n net <- net.diff\n cells.level <- rownames(net.diff)\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n if (invert.source == TRUE) {\n sources.use <- setdiff(rownames(net.diff), sources.use)\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n if (invert.target == TRUE) {\n targets.use <- setdiff(rownames(net.diff), targets.use)\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n }\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(cells.level))\n }\n names(color.use) <- cells.level\n color.use <- color.use[cells.level %in% unique(df.net$target)]\n\n gg <- barplot_internal(df.net, x = \"target\", y = \"value\", fill = \"target\", color.use = color.use, title.name = title.name,x.lab.rot = x.lab.rot,...)\n\n return(gg)\n\n}\n\n\n#' Show all the significant interactions (L-R pairs) from some cell groups to other cell groups\n#'\n#' The dot color and size represent the calculated communication probability and p-values.\n#'\n#' @param object CellChat object\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest and the order of L-R on y-axis\n#' @param sort.by.source,sort.by.target,sort.by.source.priority set the order of interacting cell pairs on x-axis; please check examples for details\n#' @param color.heatmap A character string or vector indicating the colormap option to use. It can be the avaibale color palette in viridis_pal() or brewer.pal()\n#' @param direction Sets the order of colors in the scale. If 1, the default colors are used. If -1, the order of colors is reversed.\n#' @param n.colors number of basic colors to generate from color palette\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param comparison a numerical vector giving the datasets for comparison in the merged object; e.g., comparison = c(1,2)\n#' @param group a numerical vector giving the group information of different datasets; e.g., group = c(1,2,2)\n#' @param remove.isolate whether to remove the entire empty columns, i.e., communication between certain cell groups\n#' @param max.dataset a scale, keeping the communications with highest probability in max.dataset (i.e., certrain condition)\n#' @param min.dataset a scale, keeping the communications with lowest probability in min.dataset (i.e., certrain condition)\n#' @param min.quantile,max.quantile minimum and maximum quantile cutoff values for the colorbar, may specify quantile in [0,1]\n#' @param line.on whether to add vertical line when doing comparison analysis for the merged object\n#' @param line.size size of vertical line if added\n#' @param color.text.use whether to color the xtick labels according to the dataset origin when doing comparison analysis\n#' @param color.text the colors for xtick labels according to the dataset origin when doing comparison analysis\n#' @param dot.size.min,dot.size.max Size of smallest and largest points\n#' @param title.name main title of the plot\n#' @param font.size,font.size.title font size of all the text and the title name\n#' @param show.legend whether to show legend\n#' @param grid.on,color.grid whether to add grid\n#' @param angle.x,vjust.x,hjust.x parameters for adjusting the rotation of xtick labels\n#' @param return.data whether to return the data.frame for replotting\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # show all the significant interactions (L-R pairs) from some cell groups (defined by 'sources.use') to other cell groups (defined by 'targets.use')\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), remove.isolate = FALSE)\n#'\n#' # show all the significant interactions (L-R pairs) associated with certain signaling pathways\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), signaling = c(\"CCL\",\"CXCL\"))\n#'\n#' # show all the significant interactions (L-R pairs) based on user's input (defined by `pairLR.use`; the order of L-R is also based on user's input)\n#' pairLR.use <- extractEnrichedLR(cellchat, signaling = c(\"CCL\",\"CXCL\",\"FGF\"))\n#' netVisual_bubble(cellchat, sources.use = c(3,4), targets.use = c(5:8), pairLR.use = pairLR.use, remove.isolate = TRUE)\n#'\n#' # set the order of interacting cell pairs on x-axis\n#' # (1) Default: first sort cell pairs based on the appearance of sources in levels(object@idents), and then based on the appearance of targets in levels(object@idents)\n#' # (2) sort cell pairs based on the targets.use defined by users\n#' netVisual_bubble(cellchat, targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.target = T)\n#' # (3) sort cell pairs based on the sources.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T)\n#' # (4) sort cell pairs based on the sources.use and then targets.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T, sort.by.target = T)\n#' # (5) sort cell pairs based on the targets.use and then sources.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T, sort.by.target = T, sort.by.source.priority = FALSE)\n#'\n#'# show all the increased interactions in the second dataset compared to the first dataset\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:8), remove.isolate = TRUE, max.dataset = 2)\n#'\n#'# show all the decreased interactions in the second dataset compared to the first dataset\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:8), remove.isolate = TRUE, max.dataset = 1)\n#'}\nnetVisual_bubble <- function(object, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR.use = NULL, sort.by.source = FALSE, sort.by.target = FALSE, sort.by.source.priority = TRUE, color.heatmap = c(\"Spectral\",\"viridis\"), n.colors = 10, direction = -1, thresh = 0.05,\n comparison = NULL, group = NULL, remove.isolate = FALSE, max.dataset = NULL, min.dataset = NULL,\n min.quantile = 0, max.quantile = 1, line.on = TRUE, line.size = 0.2, color.text.use = TRUE, color.text = NULL, dot.size.min = NULL, dot.size.max = NULL,\n title.name = NULL, font.size = 10, font.size.title = 10, show.legend = TRUE,\n grid.on = TRUE, color.grid = \"grey90\", angle.x = 90, vjust.x = NULL, hjust.x = NULL,\n return.data = FALSE){\n color.heatmap <- match.arg(color.heatmap)\n if (is.list(object@net[[1]])) {\n message(\"Comparing communications on a merged object \\n\")\n } else {\n message(\"Comparing communications on a single object \\n\")\n }\n if (is.null(vjust.x) | is.null(hjust.x)) {\n angle=c(0, 45, 90)\n hjust=c(0, 1, 1)\n vjust=c(0, 1, 0.5)\n vjust.x = vjust[angle == angle.x]\n hjust.x = hjust[angle == angle.x]\n }\n if (length(color.heatmap) == 1) {\n color.use <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n scales::viridis_pal(option = color.heatmap, direction = -1)(n.colors)\n })\n } else {\n color.use <- color.heatmap\n }\n if (direction == -1) {\n color.use <- rev(color.use)\n }\n\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n pairLR.use$pathway_name <- as.character(pairLR.use$pathway_name)\n } else if (\"interaction_name\" %in% colnames(pairLR.use)) {\n pairLR.use$interaction_name <- as.character(pairLR.use$interaction_name)\n }\n }\n\n if (is.null(comparison)) {\n cells.level <- levels(object@idents)\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.net$source.target <- paste(df.net$source, df.net$target, sep = \" -> \")\n source.target <- paste(rep(sources.use, each = length(targets.use)), targets.use, sep = \" -> \")\n source.target.isolate <- setdiff(source.target, unique(df.net$source.target))\n if (length(source.target.isolate) > 0) {\n df.net.isolate <- as.data.frame(matrix(NA, nrow = length(source.target.isolate), ncol = ncol(df.net)))\n colnames(df.net.isolate) <- colnames(df.net)\n df.net.isolate$source.target <- source.target.isolate\n df.net.isolate$interaction_name_2 <- df.net$interaction_name_2[1]\n df.net.isolate$pval <- 1\n a <- stringr::str_split(df.net.isolate$source.target, \" -> \", simplify = T)\n df.net.isolate$source <- as.character(a[, 1])\n df.net.isolate$target <- as.character(a[, 2])\n df.net <- rbind(df.net, df.net.isolate)\n }\n\n df.net$pval[df.net$pval > 0.05] = 1\n df.net$pval[df.net$pval > 0.01 & df.net$pval <= 0.05] = 2\n df.net$pval[df.net$pval <= 0.01] = 3\n df.net$prob[df.net$prob == 0] <- NA\n df.net$prob.original <- df.net$prob\n df.net$prob <- -1/log(df.net$prob)\n\n idx1 <- which(is.infinite(df.net$prob) | df.net$prob < 0)\n if (sum(idx1) > 0) {\n values.assign <- seq(max(df.net$prob, na.rm = T)*1.1, max(df.net$prob, na.rm = T)*1.5, length.out = length(idx1))\n position <- sort(prob.original[idx1], index.return = TRUE)$ix\n df.net$prob[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n # rownames(df.net) <- df.net$interaction_name_2\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n group.names <- paste(rep(levels(df.net$source), each = length(levels(df.net$target))), levels(df.net$target), sep = \" -> \")\n\n df.net$interaction_name_2 <- as.character(df.net$interaction_name_2)\n df.net <- with(df.net, df.net[order(interaction_name_2),])\n df.net$interaction_name_2 <- factor(df.net$interaction_name_2, levels = unique(df.net$interaction_name_2))\n cells.order <- group.names\n df.net$source.target <- factor(df.net$source.target, levels = cells.order)\n df <- df.net\n } else {\n dataset.name <- names(object@net)\n df.net.all <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.all <- data.frame()\n for (ii in 1:length(comparison)) {\n cells.level <- levels(object@idents[[comparison[ii]]])\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n\n df.net <- df.net.all[[comparison[ii]]]\n df.net$interaction_name_2 <- as.character(df.net$interaction_name_2)\n df.net$source.target <- paste(df.net$source, df.net$target, sep = \" -> \")\n source.target <- paste(rep(sources.use, each = length(targets.use)), targets.use, sep = \" -> \")\n source.target.isolate <- setdiff(source.target, unique(df.net$source.target))\n if (length(source.target.isolate) > 0) {\n df.net.isolate <- as.data.frame(matrix(NA, nrow = length(source.target.isolate), ncol = ncol(df.net)))\n colnames(df.net.isolate) <- colnames(df.net)\n df.net.isolate$source.target <- source.target.isolate\n df.net.isolate$interaction_name_2 <- df.net$interaction_name_2[1]\n df.net.isolate$pval <- 1\n a <- stringr::str_split(df.net.isolate$source.target, \" -> \", simplify = T)\n df.net.isolate$source <- as.character(a[, 1])\n df.net.isolate$target <- as.character(a[, 2])\n df.net <- rbind(df.net, df.net.isolate)\n }\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n group.names <- paste(rep(levels(df.net$source), each = length(levels(df.net$target))), levels(df.net$target), sep = \" -> \")\n group.names0 <- group.names\n group.names <- paste0(group.names0, \" (\", dataset.name[comparison[ii]], \")\")\n\n if (nrow(df.net) > 0) {\n df.net$pval[df.net$pval > 0.05] = 1\n df.net$pval[df.net$pval > 0.01 & df.net$pval <= 0.05] = 2\n df.net$pval[df.net$pval <= 0.01] = 3\n df.net$prob[df.net$prob == 0] <- NA\n df.net$prob.original <- df.net$prob\n df.net$prob <- -1/log(df.net$prob)\n } else {\n df.net <- as.data.frame(matrix(NA, nrow = length(group.names), ncol = 5))\n colnames(df.net) <- c(\"interaction_name_2\",\"source.target\",\"prob\",\"pval\",\"prob.original\")\n df.net$source.target <- group.names0\n }\n # df.net$group.names <- sub(paste0(' \\\\(',dataset.name[comparison[ii]],'\\\\)'),'',as.character(df.net$source.target))\n df.net$group.names <- as.character(df.net$source.target)\n df.net$source.target <- paste0(df.net$source.target, \" (\", dataset.name[comparison[ii]], \")\")\n df.net$dataset <- dataset.name[comparison[ii]]\n df.all <- rbind(df.all, df.net)\n }\n if (nrow(df.all) == 0) {\n stop(\"No interactions are detected. Please consider changing the cell groups for analysis. \")\n }\n\n idx1 <- which(is.infinite(df.all$prob) | df.all$prob < 0)\n if (sum(idx1) > 0) {\n values.assign <- seq(max(df.all$prob, na.rm = T)*1.1, max(df.all$prob, na.rm = T)*1.5, length.out = length(idx1))\n position <- sort(df.all$prob.original[idx1], index.return = TRUE)$ix\n df.all$prob[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n\n df.all$interaction_name_2[is.na(df.all$interaction_name_2)] <- df.all$interaction_name_2[!is.na(df.all$interaction_name_2)][1]\n\n df <- df.all\n df <- with(df, df[order(interaction_name_2),])\n df$interaction_name_2 <- factor(df$interaction_name_2, levels = unique(df$interaction_name_2))\n\n cells.order <- c()\n dataset.name.order <- c()\n for (i in 1:length(group.names0)) {\n for (j in 1:length(comparison)) {\n cells.order <- c(cells.order, paste0(group.names0[i], \" (\", dataset.name[comparison[j]], \")\"))\n dataset.name.order <- c(dataset.name.order, dataset.name[comparison[j]])\n }\n }\n df$source.target <- factor(df$source.target, levels = cells.order)\n }\n\n min.cutoff <- quantile(df$prob, min.quantile,na.rm= T)\n max.cutoff <- quantile(df$prob, max.quantile,na.rm= T)\n df$prob[df$prob < min.cutoff] <- min.cutoff\n df$prob[df$prob > max.cutoff] <- max.cutoff\n\n\n if (remove.isolate) {\n df <- df[!is.na(df$prob), ]\n line.on <- FALSE\n }\n if (!is.null(max.dataset)) {\n # line.on <- FALSE\n # df <- df[!is.na(df$prob),]\n signaling <- as.character(unique(df$interaction_name_2))\n for (i in signaling) {\n df.i <- df[df$interaction_name_2 == i, ,drop = FALSE]\n cell <- as.character(unique(df.i$group.names))\n for (j in cell) {\n df.i.j <- df.i[df.i$group.names == j, , drop = FALSE]\n values <- df.i.j$prob\n idx.max <- which(values == max(values, na.rm = T))\n idx.min <- which(values == min(values, na.rm = T))\n #idx.na <- c(which(is.na(values)), which(!(dataset.name[comparison] %in% df.i.j$dataset)))\n dataset.na <- c(df.i.j$dataset[is.na(values)], setdiff(dataset.name[comparison], df.i.j$dataset))\n if (length(idx.max) > 0) {\n if (all(!(df.i.j$dataset[idx.max] %in% dataset.name[max.dataset]))) {\n df.i.j$prob <- NA\n } else if (all((idx.max != idx.min) & !is.null(min.dataset))) {\n if (all(!(df.i.j$dataset[idx.min] %in% dataset.name[min.dataset]))) {\n df.i.j$prob <- NA\n } else if (length(dataset.na) > 0 & sum(!(dataset.name[min.dataset] %in% dataset.na)) > 0) {\n df.i.j$prob <- NA\n }\n }\n }\n df.i[df.i$group.names == j, \"prob\"] <- df.i.j$prob\n }\n df[df$interaction_name_2 == i, \"prob\"] <- df.i$prob\n }\n #df <- df[!is.na(df$prob), ]\n }\n if (remove.isolate) {\n df <- df[!is.na(df$prob), ]\n line.on <- FALSE\n }\n if (nrow(df) == 0) {\n stop(\"No interactions are detected. Please consider changing the cell groups for analysis. \")\n }\n # Re-order y-axis\n if (!is.null(pairLR.use)) {\n interaction_name_2.order <- intersect(object@DB$interaction[pairLR.use$interaction_name, ]$interaction_name_2, unique(df$interaction_name_2))\n df$interaction_name_2 <- factor(df$interaction_name_2, levels = interaction_name_2.order)\n }\n\n # Re-order x-axis\n df$source.target = droplevels(df$source.target, exclude = setdiff(levels(df$source.target),unique(df$source.target)))\n if (sort.by.target & !sort.by.source) {\n if (!is.null(targets.use)) {\n df$target <- factor(df$target, levels = intersect(targets.use, df$target))\n df <- with(df, df[order(target, source),])\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n if (sort.by.source & !sort.by.target) {\n if (!is.null(sources.use)) {\n df$source <- factor(df$source, levels = intersect(sources.use, df$source))\n df <- with(df, df[order(source, target),])\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n if (sort.by.source & sort.by.target) {\n if (!is.null(sources.use)) {\n df$source <- factor(df$source, levels = intersect(sources.use, df$source))\n if (!is.null(targets.use)) {\n df$target <- factor(df$target, levels = intersect(targets.use, df$target))\n }\n if (sort.by.source.priority) {\n df <- with(df, df[order(source, target),])\n } else {\n df <- with(df, df[order(target, source),])\n }\n\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n\n g <- ggplot(df, aes(x = source.target, y = interaction_name_2, color = prob, size = pval)) +\n geom_point(pch = 16) +\n theme_linedraw() + theme(panel.grid.major = element_blank()) +\n theme(axis.text.x = element_text(angle = angle.x, hjust= hjust.x, vjust = vjust.x),\n axis.title.x = element_blank(),\n axis.title.y = element_blank()) +\n scale_x_discrete(position = \"bottom\")\n\n values <- c(1,2,3); names(values) <- c(\"p > 0.05\", \"0.01 < p < 0.05\",\"p < 0.01\")\n if (is.null(dot.size.max)) {\n dot.size.max = max(df$pval)\n }\n if (is.null(dot.size.min)) {\n dot.size.min = min(df$pval)\n }\n g <- g + scale_radius(range = c(dot.size.min, dot.size.max), breaks = sort(unique(df$pval)),labels = names(values)[values %in% sort(unique(df$pval))], name = \"p-value\")\n #g <- g + scale_radius(range = c(1,3), breaks = values,labels = names(values), name = \"p-value\")\n if (min(df$prob, na.rm = T) != max(df$prob, na.rm = T)) {\n g <- g + scale_colour_gradientn(colors = colorRampPalette(color.use)(99), na.value = \"white\", limits=c(quantile(df$prob, 0,na.rm= T), quantile(df$prob, 1,na.rm= T)),\n breaks = c(quantile(df$prob, 0,na.rm= T), quantile(df$prob, 1,na.rm= T)), labels = c(\"min\",\"max\")) +\n guides(color = guide_colourbar(barwidth = 0.5, title = \"Commun. Prob.\"))\n } else {\n g <- g + scale_colour_gradientn(colors = colorRampPalette(color.use)(99), na.value = \"white\") +\n guides(color = guide_colourbar(barwidth = 0.5, title = \"Commun. Prob.\"))\n }\n\n g <- g + theme(text = element_text(size = font.size),plot.title = element_text(size=font.size.title)) +\n theme(legend.title = element_text(size = 8), legend.text = element_text(size = 6))\n\n if (grid.on) {\n if (length(unique(df$source.target)) > 1) {\n g <- g + geom_vline(xintercept=seq(1.5, length(unique(df$source.target))-0.5, 1),lwd=0.1,colour=color.grid)\n }\n if (length(unique(df$interaction_name_2)) > 1) {\n g <- g + geom_hline(yintercept=seq(1.5, length(unique(df$interaction_name_2))-0.5, 1),lwd=0.1,colour=color.grid)\n }\n }\n if (!is.null(title.name)) {\n g <- g + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5))\n }\n\n if (!is.null(comparison)) {\n if (line.on) {\n xintercept = seq(0.5+length(dataset.name[comparison]), length(group.names0)*length(dataset.name[comparison]), by = length(dataset.name[comparison]))\n g <- g + geom_vline(xintercept = xintercept, linetype=\"dashed\", color = \"grey60\", size = line.size)\n }\n if (color.text.use) {\n if (is.null(group)) {\n group <- 1:length(comparison)\n names(group) <- dataset.name[comparison]\n }\n if (is.null(color.text)) {\n color <- ggPalette(length(unique(group)))\n } else {\n color <- color.text\n }\n names(color) <- names(group[!duplicated(group)])\n color <- color[group]\n #names(color) <- dataset.name[comparison]\n dataset.name.order <- levels(df$source.target)\n dataset.name.order <- stringr::str_match(dataset.name.order, \"\\\\(.*\\\\)\")\n dataset.name.order <- stringr::str_sub(dataset.name.order, 2, stringr::str_length(dataset.name.order)-1)\n xtick.color <- color[dataset.name.order]\n g <- g + theme(axis.text.x = element_text(colour = xtick.color))\n }\n }\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (return.data) {\n return(list(communication = df, gg.obj = g))\n } else {\n return(g)\n }\n\n}\n\n\n\n\n#' Chord diagram for visualizing cell-cell communication for a signaling pathway\n#'\n#' Names of cell states will be displayed in this chord diagram\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the name of signaling networks\n#' @param net a weighted matrix or a data frame with three columns defining the cell-cell communication network\n#' @param slot.name the slot name of object: slot.name = \"net\" when visualizing cell-cell communication network per each ligand-receptor pair associated with a given signaling pathway;\n#' slot.name = \"netP\" when visualizing cell-cell communication network at the level of signaling pathways\n#' @param color.use colors for the cell groups\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param remove.isolate whether remove sectors without any links\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the figures\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param ... other parameters passing to chordDiagram\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_cell <- function(object, signaling = NULL, net = NULL, slot.name = \"netP\",\n color.use = NULL,group = NULL,cell.order = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n remove.isolate = FALSE, link.visible = TRUE, scale = FALSE, directional = 1,link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20, nCol = NULL,\n thresh = 0.05,...){\n\n if (!is.null(signaling)) {\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n }\n\n if (slot.name == \"netP\") {\n message(\"Plot the aggregated cell-cell communication network at the signaling pathway level\")\n net <- apply(prob, c(1,2), sum)\n if (is.null(title.name)) {\n title.name <- paste0(signaling, \" signaling pathway network\")\n }\n # par(mfrow = c(1,1), xpd=TRUE)\n # par(mar = c(5, 4, 4, 2))\n gg <- netVisual_chord_cell_internal(net, color.use = color.use, group = group, cell.order = cell.order, sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap, big.gap = big.gap,annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y, ...)\n } else if (slot.name == \"net\") {\n message(\"Plot the cell-cell communication network per each ligand-receptor pair associated with a given signaling pathway\")\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n # layout(matrix(1:length(pairLR.name.use), ncol = nCol))\n # par(xpd=TRUE)\n # par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE, mar = c(5, 4, 4, 2) +0.1)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n #par(mar = c(5, 4, 4, 2))\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n gg[[i]] <- netVisual_chord_cell_internal(net, color.use = color.use, group = group,cell.order = cell.order,sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap,big.gap = big.gap, annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y, ...)\n }\n }\n\n } else if (!is.null(net)) {\n gg <- netVisual_chord_cell_internal(net, color.use = color.use, group = group,cell.order = cell.order,sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap, big.gap = big.gap,annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y, ...)\n } else {\n stop(\"Please assign values to either `signaling` or `net`\")\n }\n\n return(gg)\n}\n\n\n#' Chord diagram for visualizing cell-cell communication from a weighted adjacency matrix or a data frame\n#'\n#' Names of cell states/groups will be displayed in this chord diagram\n#'\n#' @param net a weighted matrix or a data frame with three columns defining the cell-cell communication network\n#' @param color.use colors for the cell groups\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param remove.isolate whether remove sectors without any links\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name of the plot\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param ... other parameters passing to chordDiagram\n#' @importFrom circlize circos.clear chordDiagram circos.track circos.text get.cell.meta.data\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_cell_internal <- function(net, color.use = NULL, group = NULL, cell.order = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n remove.isolate = FALSE, link.visible = TRUE, scale = FALSE, directional = 1, link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20,...){\n if (inherits(x = net, what = c(\"matrix\", \"Matrix\"))) {\n cell.levels <- union(rownames(net), colnames(net))\n net <- reshape2::melt(net, value.name = \"prob\")\n colnames(net)[1:2] <- c(\"source\",\"target\")\n } else if (is.data.frame(net)) {\n if (all(c(\"source\",\"target\", \"prob\") %in% colnames(net)) == FALSE) {\n stop(\"The input data frame must contain three columns named as source, target, prob\")\n }\n cell.levels <- as.character(union(net$source,net$target))\n }\n if (!is.null(cell.order)) {\n cell.levels <- cell.order\n }\n net$source <- as.character(net$source)\n net$target <- as.character(net$target)\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cell.levels[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cell.levels[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n }\n # remove the interactions with zero values\n net <- subset(net, prob > 0)\n if(dim(net)[1]<=0){message(\"No interaction between those cells\")}\n # create a fake data if keeping the cell types (i.e., sectors) without any interactions\n if (!remove.isolate) {\n cells.removed <- setdiff(cell.levels, as.character(union(net$source,net$target)))\n if (length(cells.removed) > 0) {\n net.fake <- data.frame(cells.removed, cells.removed, 1e-10*sample(length(cells.removed), length(cells.removed)))\n colnames(net.fake) <- colnames(net)\n net <- rbind(net, net.fake)\n link.visible <- net[, 1:2]\n link.visible$plot <- FALSE\n if(nrow(net) > nrow(net.fake)){\n link.visible$plot[1:(nrow(net) - nrow(net.fake))] <- TRUE\n }\n # directional <- net[, 1:2]\n # directional$plot <- 0\n # directional$plot[1:(nrow(net) - nrow(net.fake))] <- 1\n # link.arr.type = \"big.arrow\"\n # message(\"Set scale = TRUE when remove.isolate = FALSE\")\n scale = TRUE\n }\n }\n\n df <- net\n cells.use <- union(df$source,df$target)\n\n # define grid order\n order.sector <- cell.levels[cell.levels %in% cells.use]\n\n # define grid color\n if (is.null(color.use)){\n color.use = scPalette(length(cell.levels))\n names(color.use) <- cell.levels\n } else if (is.null(names(color.use))) {\n names(color.use) <- cell.levels\n }\n grid.col <- color.use[order.sector]\n names(grid.col) <- order.sector\n\n # set grouping information\n if (!is.null(group)) {\n group <- group[names(group) %in% order.sector]\n }\n\n # define edge color\n edge.color <- color.use[as.character(df$source)]\n\n if (directional == 0 | directional == 2) {\n link.arr.type = \"triangle\"\n } else {\n link.arr.type = \"big.arrow\"\n }\n\n circos.clear()\n chordDiagram(df,\n order = order.sector,\n col = edge.color,\n grid.col = grid.col,\n transparency = transparency,\n link.border = link.border,\n directional = directional,\n direction.type = c(\"diffHeight\",\"arrows\"),\n link.arr.type = link.arr.type, # link.border = \"white\",\n annotationTrack = \"grid\",\n annotationTrackHeight = annotationTrackHeight,\n preAllocateTracks = list(track.height = max(strwidth(order.sector))),\n small.gap = small.gap,\n big.gap = big.gap,\n link.visible = link.visible,\n scale = scale,\n group = group,\n link.target.prop = link.target.prop,\n reduce = reduce,\n ...)\n circos.track(track.index = 1, panel.fun = function(x, y) {\n xlim = get.cell.meta.data(\"xlim\")\n xplot = get.cell.meta.data(\"xplot\")\n ylim = get.cell.meta.data(\"ylim\")\n sector.name = get.cell.meta.data(\"sector.index\")\n circos.text(mean(xlim), ylim[1], sector.name, facing = \"clockwise\", niceFacing = TRUE, adj = c(0, 0.5),cex = lab.cex)\n }, bg.border = NA)\n\n # https://jokergoo.github.io/circlize_book/book/legends.html\n if (show.legend) {\n lgd <- ComplexHeatmap::Legend(at = names(grid.col), type = \"grid\", legend_gp = grid::gpar(fill = grid.col), title = \"Cell State\")\n ComplexHeatmap::draw(lgd, x = unit(1, \"npc\")-unit(legend.pos.x, \"mm\"), y = unit(legend.pos.y, \"mm\"), just = c(\"right\", \"bottom\"))\n }\n\n if(!is.null(title.name)){\n # title(title.name, cex = 1)\n text(-0, 1.02, title.name, cex=1)\n }\n circos.clear()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Chord diagram for visualizing cell-cell communication for a set of ligands/receptors or signaling pathways\n#'\n#' Names of ligands/receptors or signaling pathways will be displayed in this chord diagram\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object: slot.name = \"net\" when visualizing links at the level of ligands/receptors; slot.name = \"netP\" when visualizing links at the level of signaling pathways\n#' @param signaling a character vector giving the name of signaling networks\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param net A data frame consisting of the interactions of interest.\n#' net should have at least three columns: \"source\",\"target\" and \"interaction_name\" when visualizing links at the level of ligands/receptors;\n#' \"source\",\"target\" and \"pathway_name\" when visualizing links at the level of signaling pathway; \"interaction_name\" and \"pathway_name\" must be the matched names in CellChatDB$interaction.\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param color.use colors for the cell groups\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name of the plot\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param ... other parameters to chordDiagram\n#' @importFrom circlize circos.clear chordDiagram circos.track circos.text get.cell.meta.data\n#' @importFrom dplyr select %>% group_by summarize\n#' @importFrom grDevices recordPlot\n#' @importFrom stringr str_split\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_gene <- function(object, slot.name = \"net\", color.use = NULL,\n signaling = NULL, pairLR.use = NULL, net = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n link.visible = TRUE, scale = FALSE, directional = 1, link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, legend.pos.x = 20, legend.pos.y = 20, show.legend = TRUE,\n thresh = 0.05,\n ...){\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use) | sum(c(\"interaction_name\",\"pathway_name\") %in% colnames(pairLR.use) == 0)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n message(\"slot.name is set to be 'netP' when pairLR.use contains signaling pathways\")\n slot.name = \"netP\"\n }\n }\n\n if (!is.null(pairLR.use) & !is.null(signaling)) {\n stop(\"Please do not assign values to 'signaling' when using 'pairLR.use'\")\n }\n\n if (is.null(net)) {\n prob <- slot(object, \"net\")$prob\n pval <- slot(object, \"net\")$pval\n prob[pval > thresh] <- 0\n net <- reshape2::melt(prob, value.name = \"prob\")\n colnames(net)[1:3] <- c(\"source\",\"target\",\"interaction_name\")\n cols.default <- c(\"interaction_name_2\", \"pathway_name\", \"ligand\", \"receptor\" ,\"annotation\",\"evidence\")\n cols.common <- intersect(cols.default,colnames(object@LR$LRsig))\n pairLR = dplyr::select(object@LR$LRsig, cols.common)\n idx <- match(net$interaction_name, rownames(pairLR))\n temp <- pairLR[idx,]\n net <- cbind(net, temp)\n }\n\n if (!is.null(signaling)) {\n pairLR.use <- data.frame()\n for (i in 1:length(signaling)) {\n pairLR.use.i <- searchPair(signaling = signaling[i], pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.use <- rbind(pairLR.use, pairLR.use.i)\n }\n }\n\n if (!is.null(pairLR.use)){\n if (\"interaction_name\" %in% colnames(pairLR.use)) {\n net <- subset(net,interaction_name %in% pairLR.use$interaction_name)\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n net <- subset(net, pathway_name %in% as.character(pairLR.use$pathway_name))\n }\n }\n\n if (slot.name == \"netP\") {\n net <- dplyr::select(net, c(\"source\",\"target\",\"pathway_name\",\"prob\"))\n net$source_target <- paste(net$source, net$target, sep = \"sourceTotarget\")\n net <- net %>% dplyr::group_by(source_target, pathway_name) %>% dplyr::summarize(prob = sum(prob))\n a <- stringr::str_split(net$source_target, \"sourceTotarget\", simplify = T)\n net$source <- as.character(a[, 1])\n net$target <- as.character(a[, 2])\n net$ligand <- net$pathway_name\n net$receptor <- \" \"\n }\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- levels(object@idents)[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n } else {\n sources.use <- levels(object@idents)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- levels(object@idents)[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n } else {\n targets.use <- levels(object@idents)\n }\n # remove the interactions with zero values\n df <- subset(net, prob > 0)\n\n if (nrow(df) == 0) {\n stop(\"No signaling links are inferred! \")\n }\n\n if (length(unique(net$ligand)) == 1) {\n message(\"You may try the function `netVisual_chord_cell` for visualizing individual signaling pathway\")\n }\n\n df$id <- 1:nrow(df)\n # deal with duplicated sector names\n ligand.uni <- unique(df$ligand)\n for (i in 1:length(ligand.uni)) {\n df.i <- df[df$ligand == ligand.uni[i], ]\n source.uni <- unique(df.i$source)\n for (j in 1:length(source.uni)) {\n df.i.j <- df.i[df.i$source == source.uni[j], ]\n df.i.j$ligand <- paste0(df.i.j$ligand, paste(rep(' ',j-1),collapse = ''))\n df$ligand[df$id %in% df.i.j$id] <- df.i.j$ligand\n }\n }\n receptor.uni <- unique(df$receptor)\n for (i in 1:length(receptor.uni)) {\n df.i <- df[df$receptor == receptor.uni[i], ]\n target.uni <- unique(df.i$target)\n for (j in 1:length(target.uni)) {\n df.i.j <- df.i[df.i$target == target.uni[j], ]\n df.i.j$receptor <- paste0(df.i.j$receptor, paste(rep(' ',j-1),collapse = ''))\n df$receptor[df$id %in% df.i.j$id] <- df.i.j$receptor\n }\n }\n\n cell.order.sources <- levels(object@idents)[levels(object@idents) %in% sources.use]\n cell.order.targets <- levels(object@idents)[levels(object@idents) %in% targets.use]\n\n df$source <- factor(df$source, levels = cell.order.sources)\n df$target <- factor(df$target, levels = cell.order.targets)\n # df.ordered.source <- df[with(df, order(source, target, -prob)), ]\n # df.ordered.target <- df[with(df, order(target, source, -prob)), ]\n df.ordered.source <- df[with(df, order(source, -prob)), ]\n df.ordered.target <- df[with(df, order(target, -prob)), ]\n\n order.source <- unique(df.ordered.source[ ,c('ligand','source')])\n order.target <- unique(df.ordered.target[ ,c('receptor','target')])\n\n # define sector order\n order.sector <- c(order.source$ligand, order.target$receptor)\n\n # define cell type color\n if (is.null(color.use)){\n color.use = scPalette(nlevels(object@idents))\n names(color.use) <- levels(object@idents)\n color.use <- color.use[levels(object@idents) %in% as.character(union(df$source,df$target))]\n } else if (is.null(names(color.use))) {\n names(color.use) <- levels(object@idents)\n color.use <- color.use[levels(object@idents) %in% as.character(union(df$source,df$target))]\n }\n\n # define edge color\n edge.color <- color.use[as.character(df.ordered.source$source)]\n names(edge.color) <- as.character(df.ordered.source$source)\n\n # define grid colors\n grid.col.ligand <- color.use[as.character(order.source$source)]\n names(grid.col.ligand) <- as.character(order.source$source)\n grid.col.receptor <- color.use[as.character(order.target$target)]\n names(grid.col.receptor) <- as.character(order.target$target)\n grid.col <- c(as.character(grid.col.ligand), as.character(grid.col.receptor))\n names(grid.col) <- order.sector\n\n df.plot <- df.ordered.source[ ,c('ligand','receptor','prob')]\n\n if (directional == 2) {\n link.arr.type = \"triangle\"\n } else {\n link.arr.type = \"big.arrow\"\n }\n circos.clear()\n chordDiagram(df.plot,\n order = order.sector,\n col = edge.color,\n grid.col = grid.col,\n transparency = transparency,\n link.border = link.border,\n directional = directional,\n direction.type = c(\"diffHeight\",\"arrows\"),\n link.arr.type = link.arr.type,\n annotationTrack = \"grid\",\n annotationTrackHeight = annotationTrackHeight,\n preAllocateTracks = list(track.height = max(strwidth(order.sector))),\n small.gap = small.gap,\n big.gap = big.gap,\n link.visible = link.visible,\n scale = scale,\n link.target.prop = link.target.prop,\n reduce = reduce,\n ...)\n\n circos.track(track.index = 1, panel.fun = function(x, y) {\n xlim = get.cell.meta.data(\"xlim\")\n xplot = get.cell.meta.data(\"xplot\")\n ylim = get.cell.meta.data(\"ylim\")\n sector.name = get.cell.meta.data(\"sector.index\")\n circos.text(mean(xlim), ylim[1], sector.name, facing = \"clockwise\", niceFacing = TRUE, adj = c(0, 0.5),cex = lab.cex)\n }, bg.border = NA)\n\n # https://jokergoo.github.io/circlize_book/book/legends.html\n if (show.legend) {\n lgd <- ComplexHeatmap::Legend(at = names(color.use), type = \"grid\", legend_gp = grid::gpar(fill = color.use), title = \"Cell State\")\n ComplexHeatmap::draw(lgd, x = unit(1, \"npc\")-unit(legend.pos.x, \"mm\"), y = unit(legend.pos.y, \"mm\"), just = c(\"right\", \"bottom\"))\n }\n\n circos.clear()\n if(!is.null(title.name)){\n text(-0, 1.02, title.name, cex=1)\n }\n gg <- recordPlot()\n return(gg)\n}\n\n\n\n\n#' River plot showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways\n#'\n#' River (alluvial) plot shows the correspondence between the inferred latent patterns and cell groups as well as ligand-receptor pairs or signaling pathways.\n#'\n#' The thickness of the flow indicates the contribution of the cell group or signaling pathway to each latent pattern. The height of each pattern is proportional to the number of its associated cell groups or signaling pathways.\n#'\n#' Outgoing patterns reveal how the sender cells coordinate with each other as well as how they coordinate with certain signaling pathways to drive communication.\n#'\n#' Incoming patterns show how the target cells coordinate with each other as well as how they coordinate with certain signaling pathways to respond to incoming signaling.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object: “netP” or “net”. Use “netP” to analyze cell-cell communication at the level of signaling pathways, and “net” to analyze cell-cell communication at the level of ligand-receptor pairs.\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param cutoff the threshold for filtering out weak links\n#' @param sources.use a vector giving the index or the name of source cell groups of interest\n#' @param targets.use a vector giving the index or the name of target cell groups of interest\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.use.pattern the character vector defining the color of each pattern\n#' @param color.use.signaling the character vector defining the color of each signaling\n#' @param do.order whether reorder the cell groups or signaling according to their similarity\n#' @param main.title the title of plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom methods slot\n#' @importFrom stats cutree dist hclust\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @import ggalluvial\n# #' @importFrom ggalluvial geom_stratum geom_flow to_lodes_form\n#' @importFrom ggplot2 geom_text scale_x_discrete scale_fill_manual theme ggtitle\n#' @importFrom cowplot plot_grid ggdraw draw_label\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_river <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = 0.5,\n sources.use = NULL, targets.use = NULL, signaling = NULL,\n color.use = NULL, color.use.pattern = NULL, color.use.signaling = \"grey50\",\n do.order = FALSE, main.title = NULL,\n font.size = 2.5, font.size.title = 12){\n message(\"Please make sure you have load `library(ggalluvial)` when running this function\")\n requireNamespace(\"ggalluvial\")\n # suppressMessages(require(ggalluvial))\n res.pattern <- methods::slot(object, slot.name)$pattern[[pattern]]\n data1 = res.pattern$pattern$cell\n data2 = res.pattern$pattern$signaling\n if (is.null(color.use.pattern)) {\n nPatterns <- length(unique(data1$Pattern))\n if (pattern == \"outgoing\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(1,nPatterns*2, by = 2)]\n } else if (pattern == \"incoming\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(2,nPatterns*2, by = 2)]\n }\n }\n if (is.null(main.title)) {\n if (pattern == \"outgoing\") {\n main.title = \"Outgoing communication patterns of secreting cells\"\n } else if (pattern == \"incoming\") {\n main.title = \"Incoming communication patterns of target cells\"\n }\n }\n\n if (is.null(data2)) {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n if (is.null(color.use)) {\n color.use <- scPalette(nCellGroup)\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n gg <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10))+\n ggtitle(main.title)\n\n } else {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n cells.level = levels(object@idents)\n if (is.null(color.use)) {\n color.use <- scPalette(length(cells.level))[cells.level %in% unique(plot.data$CellGroup)]\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n if (!is.null(sources.use)) {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% sources.use)\n }\n if (!is.null(targets.use)) {\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% targets.use)\n }\n ## connect cell groups with patterns\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n StatStratum <- ggalluvial::StatStratum\n gg1 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10)) +\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n ## connect patterns with signaling\n data2$Contribution[data2$Contribution < cutoff] <- 0\n plot.data <- data2\n nPatterns<-length(unique(plot.data$Pattern))\n nSignaling<-length(unique(plot.data$Signaling))\n if (length(color.use.signaling) == 1) {\n color.use.all <- c(color.use.pattern, rep(color.use.signaling, nSignaling))\n } else {\n color.use.all <- c(color.use.pattern, color.use.signaling)\n }\n\n if (!is.null(signaling)) {\n plot.data <- plot.data[plot.data$Signaling %in% signaling, ]\n }\n\n plot.data.long <- ggalluvial::to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"Signaling\"]], plot.data[[\"Pattern\"]]), sum)\n mat[is.na(mat)] <- 0; mat <- mat[-which(rowSums(mat) == 0), ]\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(colnames(mat),names(cluster)[order.name]))\n }\n\n gg2 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"Pattern\", \"Signaling\")),y= Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"forward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) + # 2.5\n scale_x_discrete(limits = c(), labels=c(\"Patterns\", \"Signaling\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size= 10))+\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n ## connect cell groups with signaling\n # data1 = data1[data1$Contribution > 0,]\n # data2 = data2[data2$Contribution > 0,]\n\n # data3 = merge(data1, data2, by.x=\"Pattern\", by.y=\"Pattern\")\n # data3$Contribution <- data3$Contribution.x * data3$Contribution.y\n # data3 <- data3[,colnames(data3) %in% c(\"CellGroup\",\"Signaling\",\"Contribution\")]\n\n # plot.data <- data3\n # nSignaling<-length(unique(plot.data$Signaling))\n # nCellGroup<-length(unique(plot.data$CellGroup))\n #\n # if (length(color.use.signaling) == 1) {\n # color.use.signaling <- rep(color.use.signaling, nSignaling)\n # }\n #\n #\n # ## connect cell groups with patterns\n # plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n # if (do.order) {\n # mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Signaling\"]]), sum)\n # d <- dist(as.matrix(mat))\n # hc <- hclust(d, \"ave\")\n # k <- length(unique(grep(\"Signaling\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n # cluster <- hc %>% cutree(k)\n # order.name <- order(cluster)\n # plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n # color.use <- color.use[order.name]\n # }\n # color.use.all <- c(color.use, color.use.signaling)\n\n # gg3 <- ggplot(plot.data.long, aes(x = factor(x, levels = c(\"CellGroup\", \"Signaling\")),y=Contribution,\n # stratum = stratum, alluvium = connection,\n # fill = stratum, label = stratum)) +\n # geom_flow(width = 1/3,aes.flow = \"forward\") +\n # geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n # geom_text(stat = \"stratum\", size = 2.5) +\n # scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Signaling\")) +\n # scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n # theme_bw()+\n # theme(legend.position = \"none\",\n # axis.title = element_blank(),\n # axis.text.y= element_blank(),\n # panel.grid.major = element_blank(),\n # panel.grid.minor = element_blank(),\n # panel.border = element_blank(),\n # axis.ticks = element_blank(),axis.text=element_text(size=10)) +\n # theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n\n gg <- cowplot::plot_grid(gg1, gg2,align = \"h\", nrow = 1)\n title <- cowplot::ggdraw() + cowplot::draw_label(main.title,size = font.size.title)\n gg <- cowplot::plot_grid(title, gg, ncol=1, rel_heights=c(0.1, 1))\n }\n return(gg)\n}\n\n#' Dot plots showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways\n#'\n#' Using a contribution score of each cell group to each signaling pathway computed by multiplying W by H obtained from `identifyCommunicationPatterns`, we constructed a dot plot in which the dot size is proportion to the contribution score to show association between cell group and their enriched signaling pathways.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param cutoff the threshold for filtering out weak links. Default is 1/R where R is the number of latent patterns. We set the elements in W and H to be zero if they are less than `cutoff`.\n#' @param color.use the character vector defining the color of each cell group\n#' @param pathway.show the character vector defining the signaling to show\n#' @param group.show the character vector defining the cell group to show\n#' @param shape the shape of the symbol: 21 for circle and 22 for square\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param main.title the title of plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom methods slot\n#' @import ggplot2\n#' @importFrom dplyr group_by top_n\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_dot <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = NULL, color.use = NULL,\n pathway.show = NULL, group.show = NULL,\n shape = 21, dot.size = c(1, 3), dot.alpha = 1, main.title = NULL,\n font.size = 10, font.size.title = 12){\n pattern <- match.arg(pattern)\n patternSignaling <- methods::slot(object, slot.name)$pattern[[pattern]]\n data1 = patternSignaling$pattern$cell\n data2 = patternSignaling$pattern$signaling\n data = patternSignaling$data\n if (is.null(main.title)) {\n if (pattern == \"outgoing\") {\n main.title = \"Outgoing communication patterns of secreting cells\"\n } else if (pattern == \"incoming\") {\n main.title = \"Incoming communication patterns of target cells\"\n }\n }\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(data1$CellGroup))\n }\n if (is.null(cutoff)) {\n cutoff <- 1/length(unique(data1$Pattern))\n }\n options(warn = -1)\n data1$Contribution[data1$Contribution < cutoff] <- 0\n data2$Contribution[data2$Contribution < cutoff] <- 0\n data3 = merge(data1, data2, by.x=\"Pattern\", by.y=\"Pattern\")\n data3$Contribution <- data3$Contribution.x * data3$Contribution.y\n data3 <- data3[,colnames(data3) %in% c(\"CellGroup\",\"Signaling\",\"Contribution\")]\n if (!is.null(pathway.show)) {\n data3 <- data3[data3$Signaling %in% pathway.show, ]\n pathway.add <- pathway.show[which(pathway.show %in% data3$Signaling == 0)]\n if (length(pathway.add) > 1) {\n data.add <- expand.grid(CellGroup = levels(data1$CellGroup), Signaling = pathway.add)\n data.add$Contribution <- 0\n data3 <- rbind(data3, data.add)\n }\n data3$Signaling <- factor(data3$Signaling, levels = pathway.show)\n }\n if (!is.null(group.show)) {\n data3$CellGroup <- as.character(data3$CellGroup)\n data3 <- data3[data3$CellGroup %in% group.show, ]\n data3$CellGroup <- factor(data3$CellGroup, levels = group.show)\n }\n\n data <- as.data.frame(as.table(data));\n data <- data[data[,3] != 0, ]\n data12 <- paste0(data[,1],data[,2])\n data312 <- paste0(data3[,1],data3[,2])\n idx1 <- which(match(data312, data12, nomatch = 0) ==0)\n data3$Contribution[idx1] <- 0\n data3$id <- data312\n data3 <- data3 %>% group_by(id) %>% top_n(1, Contribution)\n\n data3$Contribution[which(data3$Contribution == 0)] <- NA\n\n df <- data3\n gg <- ggplot(data = df, aes(x = Signaling, y = CellGroup)) +\n geom_point(aes(size = Contribution, fill = CellGroup, colour = CellGroup), shape = shape) +\n scale_size_continuous(range = dot.size) +\n theme_linedraw() +\n scale_x_discrete(position = \"bottom\") +\n ggtitle(main.title) +\n theme(plot.title = element_text(hjust = 0.5)) +\n theme(text = element_text(size = font.size),plot.title = element_text(size=font.size.title, face=\"plain\"),\n axis.text.x = element_text(angle = 45, hjust=1),\n axis.text.y = element_text(angle = 0, hjust=1),\n axis.title.x = element_blank(),\n axis.title.y = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25)) +\n theme(panel.grid.major = element_line(colour=\"grey90\", size = (0.1)))\n gg <- gg + scale_y_discrete(limits = rev(levels(data3$CellGroup)))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE, na.value = \"white\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, na.value = \"white\")\n gg <- gg + guides(colour=\"none\") + guides(fill=\"none\")\n gg <- gg + theme(legend.title = element_text(size = 10), legend.text = element_text(size = 8))\n gg\n return(gg)\n}\n\n\n#' 2D visualization of the learned manifold of signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param pathway.labeled a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param pathway.remove.show whether show the removed signaling names\n#' @param color.use defining the color for each cell group\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embedding <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), color.use = NULL, pathway.labeled = NULL, top.label = 1, pathway.remove = NULL, pathway.remove.show = TRUE, dot.size = c(2, 6), label.size = 2, dot.alpha = 0.5,\n xlabel = \"Dim 1\", ylabel = \"Dim 2\", title = NULL,\n font.size = 10, font.size.title = 12, do.label = T, show.legend = T, show.axes = T) {\n type <- match.arg(type)\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n Groups <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n prob <- methods::slot(object, slot.name)$prob\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n }\n\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(dimnames(prob)[[3]] %in% pathway.remove)\n prob <- prob[ , , -pathway.remove.idx]\n }\n\n prob_sum <- apply(prob, 3, sum)\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum), labels = as.character(unlist(dimnames(prob)[3])), Groups = as.factor(Groups))\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(Groups)))\n }\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.,fill = Groups, colour = Groups), shape = 21) +\n CellChat_theme_opts() +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\"))+\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE)\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n if (do.label) {\n if (is.null(pathway.labeled)) {\n if (top.label < 1) {\n if (length(comparison) == 2) {\n g.t <- rankSimilarity(object, slot.name = slot.name, type = type, comparison1 = comparison)\n pathway.labeled <- as.character(g.t$data$name[(nrow(g.t$data)-ceiling(top.label * nrow(g.t$data))+1):nrow(g.t$data) ])\n data.label <- df[df$labels %in% pathway.labeled, , drop = FALSE]\n }\n } else {\n data.label <- df\n }\n\n } else {\n data.label <- df[df$labels %in% pathway.labeled, , drop = FALSE]\n }\n gg <- gg + ggrepel::geom_text_repel(data = data.label, mapping = aes(label = labels, colour = Groups), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n\n # gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = Groups), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (length(pathway.remove) > 0 & pathway.remove.show) {\n gg <- gg + annotate(geom = 'text', label = paste(\"Isolate pathways: \", paste(pathway.remove, collapse = ', ')), x = -Inf, y = Inf, hjust = 0, vjust = 1, size = label.size,fontface=\"italic\")\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n gg\n}\n\n\n#' Zoom into the 2D visualization of the learned manifold learning of the signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param color.use defining the color for each cell group\n#' @param nCol the number of columns of the plot\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom cowplot plot_grid\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingZoomIn <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), color.use = NULL, pathway.remove = NULL, nCol = 1, dot.size = c(2, 6), label.size = 2.8, dot.alpha = 0.5,\n xlabel = NULL, ylabel = NULL, do.label = T, show.legend = F, show.axes = T) {\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n prob <- methods::slot(object, slot.name)$prob\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n }\n\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(dimnames(prob)[[3]] %in% pathway.remove)\n prob <- prob[ , , -pathway.remove.idx]\n }\n\n prob_sum <- apply(prob, 3, sum)\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum), labels = as.character(unlist(dimnames(prob)[3])), clusters = as.factor(clusters))\n\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n\n # zoom into each cluster and do labels\n ggAll <- vector(\"list\", length(unique(clusters)))\n for (i in 1:length(unique(clusters))) {\n clusterID = i\n title <- paste0(\"Group \", clusterID)\n df2 <- df[df$clusters %in% clusterID,]\n gg <- ggplot(data = df2, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.), shape = 21, colour = alpha(color.use[clusterID], alpha = 1), fill = alpha(color.use[clusterID], alpha = dot.alpha)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size=12))+\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels), colour = color.use[clusterID], size = label.size, segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n ggAll[[i]] <- gg\n }\n gg.combined <- cowplot::plot_grid(plotlist = ggAll, ncol = nCol)\n\n gg.combined\n\n}\n\n\n\n#' 2D visualization of the joint manifold learning of signaling networks from two datasets\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object\n#' @param pathway.labeled a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param pathway.remove.show whether show the removed signaling names\n#' @param color.use defining the color for each cell group\n#' @param point.shape a numeric vector giving the point shapes. By default point.shape <- c(21, 0, 24, 23, 25, 10, 12), see available shapes at http://www.sthda.com/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingPairwise <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, color.use = NULL, point.shape = NULL, pathway.labeled = NULL, top.label = 1, pathway.remove = NULL, pathway.remove.show = TRUE, dot.size = c(2, 6), label.size = 2.5, dot.alpha = 0.5,\n xlabel = \"Dim 1\", ylabel = \"Dim 2\", title = NULL,do.label = T, show.legend = T, show.axes = T) {\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"2D visualization of signaling networks from datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n object.names <- setdiff(names(methods::slot(object, slot.name)), \"similarity\")[comparison]\n prob <- list()\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n prob[[i]] = object.net$prob\n }\n\n if (is.null(point.shape)) {\n point.shape <- c(21, 0, 24, 23, 25, 10, 12)\n }\n\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove <- sub(\"--.*\", \"\", pathway.remove)\n }\n\n if (length(pathway.remove) > 0) {\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n pathway.remove.idx <- which(paste0(dimnames(probi)[[3]],\"--\",object.names[i]) %in% pathway.remove)\n # pathway.remove.idx <- which(dimnames(probi)[[3]] %in% pathway.remove)\n if (length(pathway.remove.idx) > 0) {\n probi <- probi[ , , -pathway.remove.idx]\n }\n prob[[i]] <- probi\n }\n }\n prob_sum.each <- list()\n signalingAll <- c()\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n prob_sum.each[[i]] <- apply(probi, 3, sum)\n signalingAll <- c(signalingAll, paste0(names(prob_sum.each[[i]]),\"--\",object.names[i]))\n }\n prob_sum <- unlist(prob_sum.each)\n names(prob_sum) <- signalingAll\n\n group <- sub(\".*--\", \"\", names(prob_sum))\n labels = sub(\"--.*\", \"\", names(prob_sum))\n\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum),\n labels = as.character(labels), clusters = as.factor(clusters), group = factor(group, levels = unique(group)))\n # color dots (light inside color and dark border) based on clustering and no labels\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.,fill = clusters, colour = clusters, shape = group)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) +\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) #+ scale_alpha(group, range = c(0.1, 1))\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n gg <- gg + scale_shape_manual(values = point.shape[1:length(prob)])\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = clusters, alpha=group), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n }\n\n if (length(pathway.remove) > 0 & pathway.remove.show) {\n gg <- gg + annotate(geom = 'text', label = paste(\"Isolate pathways: \", paste(pathway.remove, collapse = ', ')), x = -Inf, y = Inf, hjust = 0, vjust = 1, size = label.size,fontface=\"italic\")\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n gg\n}\n\n\n\n#' Zoom into the 2D visualization of the joint manifold learning of signaling networks from two datasets\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param color.use defining the color for each cell group\n#' @param nCol number of columns in the plot\n#' @param point.shape a numeric vector giving the point shapes. By default point.shape <- c(21, 0, 24, 23, 25, 10, 12), see available shapes at http://www.sthda.com/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingPairwiseZoomIn <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, color.use = NULL, nCol = 1, point.shape = NULL, pathway.remove = NULL, dot.size = c(2, 6), label.size = 2.8, dot.alpha = 0.5,\n xlabel = NULL, ylabel = NULL, do.label = T, show.legend = F, show.axes = T) {\n\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"2D visualization of signaling networks from datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n object.names <- setdiff(names(methods::slot(object, slot.name)), \"similarity\")[comparison]\n prob <- list()\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n prob[[i]] = object.net$prob\n }\n\n if (is.null(point.shape)) {\n point.shape <- c(21, 0, 24, 23, 25, 10, 12)\n }\n\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove <- sub(\"--.*\", \"\", pathway.remove)\n }\n\n if (length(pathway.remove) > 0) {\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n pathway.remove.idx <- which(paste0(dimnames(probi)[[3]],\"--\",object.names[i]) %in% pathway.remove)\n # pathway.remove.idx <- which(dimnames(probi)[[3]] %in% pathway.remove)\n if (length(pathway.remove.idx) > 0) {\n probi <- probi[ , , -pathway.remove.idx]\n }\n prob[[i]] <- probi\n }\n }\n\n prob_sum.each <- list()\n signalingAll <- c()\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n prob_sum.each[[i]] <- apply(probi, 3, sum)\n signalingAll <- c(signalingAll, paste0(names(prob_sum.each[[i]]),\"--\",object.names[i]))\n }\n prob_sum <- unlist(prob_sum.each)\n names(prob_sum) <- signalingAll\n\n group <- sub(\".*--\", \"\", names(prob_sum))\n labels = sub(\"--.*\", \"\", names(prob_sum))\n\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum),\n labels = as.character(labels), clusters = as.factor(clusters), group = factor(group, levels = unique(group)))\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n\n # zoom into each cluster and do labels\n ggAll <- vector(\"list\", length(unique(clusters)))\n for (i in 1:length(unique(clusters))) {\n clusterID = i\n title <- paste0(\"Cluster \", clusterID)\n df2 <- df[df$clusters %in% clusterID,]\n gg <- ggplot(data = df2, aes(x, y)) +\n geom_point(aes(size = Commun.Prob., shape = group),fill = alpha(color.use[clusterID], alpha = dot.alpha), colour = alpha(color.use[clusterID], alpha = 1)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) +\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n idx <- match(unique(df2$group), levels(df$group), nomatch = 0)\n gg <- gg + scale_shape_manual(values= point.shape[idx])\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels), colour = color.use[clusterID], size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n ggAll[[i]] <- gg\n }\n gg.combined <- cowplot::plot_grid(plotlist = ggAll, ncol = nCol)\n\n gg.combined\n\n}\n\n\n#' A Seurat wrapper function for plotting gene expression using violin plot, dot plot or bar plot\n#'\n#' This function create a Seurat object from an input CellChat object, and then plot gene expression distribution using a modified violin plot or dot plot based on Seurat's function or a bar plot.\n#' Please check \\code{\\link{StackedVlnPlot}},\\code{\\link{dotPlot}} and \\code{\\link{barPlot}}for detailed description of the arguments.\n#'\n#' USER can extract the signaling genes related to the inferred L-R pairs or signaling pathway using \\code{\\link{extractEnrichedLR}}, and then plot gene expression using Seurat package.\n#'\n#' @param object CellChat object\n#' @param features Features to plot gene expression\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param type violin plot or dot plot\n#' @param color.use defining the color for each cell group\n#' @param group.by Name of one metadata columns to group (color) cells. Default is the defined cell groups in CellChat object\n#' @param ... other arguments passing to either VlnPlot or DotPlot from Seurat package\n#' @return\n#' @export\n#'\n#' @examples\n\nplotGeneExpression <- function(object, features = NULL, signaling = NULL, enriched.only = TRUE, type = c(\"violin\", \"dot\",\"bar\"), color.use = NULL, group.by = NULL, ...) {\n type <- match.arg(type)\n meta <- object@meta\n if (is.list(object@idents)) {\n meta$group.cellchat <- object@idents$joint\n } else {\n meta$group.cellchat <- object@idents\n }\n if (!identical(rownames(meta), colnames(object@data.signaling))) {\n cat(\"The cell barcodes in 'meta' is \", head(rownames(meta)),'\\n')\n warning(\"The cell barcodes in 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of 'mata'!\")\n rownames(meta) <- colnames(object@data.signaling)\n }\n\n w10x <- Seurat::CreateSeuratObject(counts = object@data.signaling, meta.data = meta)\n if (is.null(group.by)) {\n group.by <- \"group.cellchat\"\n }\n Seurat::Idents(w10x) <- group.by\n if (!is.null(features) & !is.null(signaling)) {\n warning(\"`features` will be used when inputing both `features` and `signaling`!\")\n }\n if (!is.null(features)) {\n feature.use <- features\n } else if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, enriched.only = enriched.only)\n feature.use <- res$geneLR\n }\n if (type == \"violin\") {\n gg <- StackedVlnPlot(w10x, features = feature.use, color.use = color.use, ...)\n } else if (type == \"dot\") {\n gg <- dotPlot(w10x, features = feature.use, color.use = color.use, ...)\n } else if (type == \"bar\") {\n gg <- barPlot(w10x, features = feature.use, color.use = color.use, ...)\n }\n return(gg)\n}\n\n\n#' Dot plot\n#'\n#'The size of the dot encodes the percentage of cells within a class, while the color encodes the AverageExpression level across all cells within a class\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param rotation whether rotate the plot\n#' @param colormap RColorbrewer palette to use (check available palette using RColorBrewer::display.brewer.all()). default will use customed color palette\n#' @param color.direction Sets the order of colours in the scale. If 1, the default, colours are as output by RColorBrewer::brewer.pal(). If -1, the order of colours is reversed.\n#' @param color.use defining the color for each condition/dataset\n#' @param idents Which classes to include in the plot (default is all)\n#' @param group.by Name of one or more metadata columns to group (color) cells by\n#' (for example, orig.ident); pass 'ident' to group by identity class\n#' @param split.by Name of a metadata column to split plot by;\n#' @param legend.width legend width\n#' @param scale whther show x-axis text\n#' @param col.min Minimum scaled average expression threshold (everything smaller will be set to this)\n#' @param col.max Maximum scaled average expression threshold (everything larger will be set to this)\n#' @param dot.scale Scale the size of the points, similar to cex\n#' @param assay Name of assay to use, defaults to the active assay\n#' @param angle.x angle for x-axis text rotation\n#' @param hjust.x adjust x axis text\n#' @param angle.y angle for y-axis text rotation\n#' @param hjust.y adjust y axis text\n#' @param show.legend whether show the legend\n#' @param ... Extra parameters passed to DotPlot from Seurat package\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\ndotPlot <- function(object, features, rotation = TRUE, colormap = \"OrRd\", color.direction = 1, color.use = c(\"#F8766D\",\"#00BFC4\"), scale = TRUE, col.min = -2.5, col.max = 2.5, dot.scale = 6, assay = \"RNA\",\n idents = NULL, group.by = NULL, split.by = NULL, legend.width = 0.5,\n angle.x = 45, hjust.x = 1, angle.y = 0, hjust.y = 0.5, show.legend = TRUE, ...) {\n\n gg <- Seurat::DotPlot(object, features = features, assay = assay, cols = color.use,\n scale = scale, col.min = col.min, col.max = col.max, dot.scale = dot.scale,\n idents = idents, group.by = group.by, split.by = split.by,...)\n gg <- gg + theme(axis.title.x=element_blank(), axis.title.y=element_blank()) +\n theme(axis.text.x = element_text(size = 10), axis.text.y = element_text(size = 10), axis.line = element_line(colour = 'black')) +\n theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))+\n theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x), axis.text.y = element_text(angle = angle.y, hjust = hjust.y))\n\n gg <- gg + theme(legend.title = element_text(size = 10), legend.text = element_text(size = 8))\n if (is.null(split.by)) {\n gg <- gg + guides(color = guide_colorbar(barwidth = legend.width, title = \"Scaled expression\"),size = guide_legend(title = 'Percent expressed'))\n }\n\n if (rotation) {\n gg <- gg + coord_flip()\n }\n if (!is.null(colormap)) {\n if (is.null(split.by)) {\n gg <- gg + scale_color_distiller(palette = colormap, direction = color.direction, guide = guide_colorbar(title = \"Scaled Expression\", ticks = T, label = T, barwidth = legend.width), na.value = \"lightgrey\")\n }\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n return(gg)\n}\n\n\n\n#' Stacked Violin plot\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param color.use defining the color for each cell group\n#' @param colors.ggplot whether use ggplot color scheme; default: colors.ggplot = FALSE\n#' @param split.by Name of a metadata column to split plot by;\n#' @param idents Which classes to include in the plot (default is all)\n#' @param show.text.y whther show y-axis text\n#' @param line.size line width in the violin plot\n#' @param pt.size size of the dots\n#' @param plot.margin adjust the white space between each plot\n#' @param angle.x angle for x-axis text rotation\n#' @param vjust.x adjust x axis text\n#' @param hjust.x adjust x axis text\n#' @param ... Extra parameters passed to VlnPlot from Seurat package\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\n#' @importFrom patchwork wrap_plots\n# #' @importFrom Seurat VlnPlot\nStackedVlnPlot<- function(object, features, idents = NULL, split.by = NULL,\n color.use = NULL, colors.ggplot = FALSE,\n angle.x = 90, vjust.x = NULL, hjust.x = NULL, show.text.y = TRUE, line.size = NULL,\n pt.size = 0,\n plot.margin = margin(0, 0, 0, 0, \"cm\"),\n ...) {\n options(warn=-1)\n if (is.null(color.use)) {\n numCluster <- length(levels(Seurat::Idents(object)))\n if (colors.ggplot) {\n color.use <- NULL\n } else {\n color.use <- scPalette(numCluster)\n }\n }\n if (is.null(vjust.x) | is.null(hjust.x)) {\n angle=c(0, 45, 90)\n hjust=c(0, 1, 1)\n vjust=c(0, 1, 0.5)\n vjust.x = vjust[angle == angle.x]\n hjust.x = hjust[angle == angle.x]\n }\n\n plot_list<- purrr::map(features, function(x) modify_vlnplot(object = object, features = x, idents = idents, split.by = split.by, cols = color.use, pt.size = pt.size,\n show.text.y = show.text.y, line.size = line.size, ...))\n\n # Add back x-axis title to bottom plot. patchwork is going to support this?\n plot_list[[length(plot_list)]]<- plot_list[[length(plot_list)]] +\n theme(axis.text.x=element_text(), axis.ticks.x = element_line()) +\n theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x, vjust = vjust.x)) +\n theme(axis.text.x = element_text(size = 10))\n\n p<- patchwork::wrap_plots(plotlist = plot_list, ncol = 1)\n return(p)\n}\n\n#' modified vlnplot\n#' @param object Seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param split.by Name of a metadata column to split plot by;\n#' @param idents Which classes to include in the plot (default is all)\n#' @param cols defining the color for each cell group\n#' @param show.text.y whther show y-axis text\n#' @param line.size line width in the violin plot\n#' @param pt.size size of the dots\n#' @param plot.margin adjust the white space between each plot\n#' @param ... pass any arguments to VlnPlot in Seurat\n#' @import ggplot2\n# #' @importFrom Seurat VlnPlot\n#'\nmodify_vlnplot<- function(object,\n features,\n idents = NULL,\n split.by = NULL,\n cols = NULL,\n show.text.y = TRUE,\n line.size = NULL,\n pt.size = 0,\n plot.margin = margin(0, 0, 0, 0, \"cm\"),\n ...) {\n options(warn=-1)\n p<- Seurat::VlnPlot(object, features = features, cols = cols, pt.size = pt.size, idents = idents, split.by = split.by, ... ) +\n xlab(\"\") + ylab(features) + ggtitle(\"\")\n p <- p + theme(text = element_text(size = 10)) + theme(axis.line = element_line(size=line.size)) +\n theme(axis.text.x = element_text(size = 10), axis.text.y = element_text(size = 8), axis.line.x = element_line(colour = 'black', size=line.size),axis.line.y = element_line(colour = 'black', size= line.size))\n # theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))\n p <- p + theme(legend.position = \"none\",\n plot.title= element_blank(),\n axis.title.x = element_blank(),\n axis.text.x = element_blank(),\n axis.ticks.x = element_blank(),\n axis.title.y = element_text(size = rel(1), angle = 0),\n axis.text.y = element_text(size = rel(1)),\n plot.margin = plot.margin ) +\n theme(axis.text.y = element_text(size = 8))\n\n p <- p + scale_y_continuous(labels = function(x) {\n idx0 = which(x == 0)\n if (length(idx0) > 0) {\n if (idx0 > 1) {\n c(rep(x = \"\", times = idx0-1), \"0\",rep(x = \"\", times = length(x) -2-idx0), x[length(x) - 1], \"\")\n } else {\n c(\"0\", rep(x = \"\", times = length(x)-3), x[length(x) - 1], \"\")\n }\n } else {\n c(as.character(min(x)), rep(x = \"\", times = length(x)-3), x[length(x) - 1], \"\")\n }\n })\n # #c(rep(x = \"\", times = length(x)-2), x[length(x) - 1], \"\"))\n\n p <- p + theme(element_line(size=line.size))\n\n if (!show.text.y) {\n p <- p + theme(axis.ticks.y=element_blank(), axis.text.y=element_blank())\n }\n return(p)\n}\n\n#' extract the max value of the y axis\n#' @param p ggplot object\n#' @importFrom ggplot2 ggplot_build\nextract_max<- function(p){\n ymax<- max(ggplot_build(p)$layout$panel_scales_y[[1]]$range$range)\n return(signif(ymax,2))\n}\n\n\n#' Bar plot for average gene expression\n#'\n#' Please check \\code{\\link{barplot_internal}}for detailed description of the arguments.\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param color.use defining the color for each condition/dataset\n#' @param group.by Name of one or more metadata columns to group (color) cells by\n#' (for example, orig.ident); pass 'ident' to group by identity class\n#' @param method methods for computing the average gene expression per cell group. By default = \"truncatedMean\", where a value should be assigned to 'trim;\n#' @param trim the fraction (0 to 0.5) of observations to be trimmed from each end of x before the mean is computed.\n#' @param split.by Name of a metadata column to split plot by;\n#' @param assay Name of assay to use, defaults to the active assay\n#' @param x.lab.rot whether do rotation for the x.tick.label\n#' @param ncol number of columns to show in the plot\n#' @param ... Extra parameters passed to barplot_internal\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\nbarPlot <- function(object, features, group.by = NULL, split.by = NULL, color.use = NULL, method = c(\"truncatedMean\", \"triMean\",\"median\"),trim = 0.1, assay = \"RNA\",\n x.lab.rot = FALSE, ncol = 1, ...) {\n method <- match.arg(method)\n if (is.null(group.by)) {\n labels = Seurat::Idents(object)\n } else {\n labels = object@meta.data[,group.by]\n }\n FunMean <- switch(method,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n triMean = triMean,\n median = function(x) median(x, na.rm = TRUE))\n if (packageVersion(\"Seurat\") < \"5.0.0\") {\n data.all <- object[[assay]]@data\n } else {\n data.all <- object[[assay]]$data\n }\n if (!is.null(split.by)) {\n group = object@meta.data[,split.by]\n group.levels <- levels(group)\n df <- data.frame()\n for (i in 1:length(group.levels)) {\n data = data.all[, group == group.levels[i], drop = FALSE]\n labels.use <- labels[group == group.levels[i]]\n dataavg <- aggregate(t(data[features, ]), list(labels.use) , FUN = FunMean)\n dataavg <- t(dataavg[,-1])\n colnames(dataavg) <- levels(labels.use)\n dataavg <- as.data.frame(dataavg)\n dataavg$gene = rownames(dataavg)\n df1 = reshape2::melt(dataavg, id.vars = c(\"gene\"))\n colnames(df1) <- c(\"gene\",\"labels\",\"value\")\n df1$condition = group.levels[i]\n df = rbind(df, df1)\n }\n df$labels <- factor(df$labels, levels = levels(labels))\n df$condition <- factor(df$condition, levels = group.levels)\n\n } else {\n data = data.all\n dataavg <- aggregate(t(data[features, ]), list(labels) , FUN = FunMean)\n dataavg <- t(dataavg[,-1])\n colnames(dataavg) <- levels(labels)\n dataavg$gene = rownames(dataavg)\n df1 = reshape2::melt(dataavg, id.vars = c(\"gene\"))\n colnames(df1) <- c(\"gene\",\"labels\",\"value\")\n df1$condition = df1[,\"labels\"]\n df = df1\n }\n gg <- list()\n for (i in 1:length(features)) {\n if (i < length(features)) {\n df.use = subset(df, gene == features[i])\n gg[[i]] <- barplot_internal(df.use, x = \"labels\", y = \"value\", fill = \"condition\",color.use = color.use,ylabel = features[i],remove.xtick = TRUE,x.lab.rot = x.lab.rot,...)\n }else {\n gg[[i]] <- barplot_internal(df.use, x = \"labels\", y = \"value\", fill = \"condition\",color.use = color.use,ylabel = features[i],remove.xtick = FALSE,x.lab.rot = x.lab.rot,...)\n }\n }\n\n p<- patchwork::wrap_plots(plotlist = gg, ncol = ncol)+ patchwork::plot_layout(guides = \"collect\")\n return(p)\n\n}\n\n#' Bar plot for dataframe\n#'\n#' @param df a dataframe\n#' @param x Name of one column to show on the x-axis\n#' @param y Name of one column to show on the y-axis\n#' @param fill Name of one column to compare the values\n#' @param color.use defining the color of bar plot;\n#' @param percent.y whether showing y-values as percentage\n#' @param width bar width\n#' @param legend.title Name of legend\n#' @param xlabel Name of x label\n#' @param ylabel Name of y label\n#' @param remove.xtick whether remove x tick\n#' @param title.name Name of the main title\n#' @param stat.add whether adding statistical test\n#' @param stat.method,label.x parameters for ggpubr::stat_compare_means\n#' @param show.legend Whether show the legend\n#' @param x.lab.rot Whether rorate the xtick labels\n#' @param size.text font size\n\n#' @import ggplot2\n#' @importFrom ggpubr stat_compare_means\n#'\n#' @return ggplot2 object\n#' @export\nbarplot_internal <- function(df, x = \"cellType\", y = \"value\", fill = \"condition\", legend.title = NULL, width=0.6, title.name = NULL,\n xlabel = NULL, ylabel = NULL, color.use = NULL,remove.xtick = FALSE,\n stat.add = FALSE, stat.method = \"wilcox.test\", percent.y = FALSE, label.x = 1.5,\n show.legend = TRUE, x.lab.rot = FALSE, size.text = 10) {\n\n gg <- ggplot(df, aes_string(x=x, y=y, fill = fill, color = fill)) + geom_bar(stat=\"identity\", width=width, position=position_dodge()) +\n theme_classic() + scale_x_discrete(limits = (levels(df$x))) + theme(axis.text.x = element_text(angle = 45, hjust = 1,size=10))\n\n gg <- gg + ylab(ylabel) + xlab(xlabel) + theme_classic() +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = size.text), axis.text = element_text(colour=\"black\"))\n if (!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values = alpha(color.use, alpha = 1), drop = FALSE)\n gg <- gg + scale_color_manual(values = alpha(color.use, alpha = 1), drop = FALSE) + guides(colour = FALSE)\n }\n if (stat.add) {\n gg <- gg + ggpubr::stat_compare_means(mapping = aes_string(group = fill), method = stat.method, label.x = label.x,\n label = \"p.format\", size = 3)\n }\n # if (show.mean) {\n # gg <- gg + stat_summary(fun.y=mean, geom=\"point\", shape=20, size=10, color=\"red\", fill=\"red\")\n # }\n if (remove.xtick) {\n gg <- gg + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.title.x=element_blank())\n }\n if (percent.y) {\n gg <- gg + scale_y_continuous(labels = scales::percent_format(accuracy = 1))\n }\n if (is.null(legend.title)) {\n gg <- gg + theme(legend.title = element_blank())\n } else {\n gg <- gg + guides(fill=guide_legend(legend.title))\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n if (x.lab.rot) {\n gg <- gg + theme(axis.text.x = element_text(angle = 45, hjust = 1, size=size.text))\n }\n gg\n return(gg)\n}\n\n\n########################################\n# spatial plot #\n########################################\n#' Visualize spatial cell groups\n#'\n#' This function takes a CellChat object as input, and then plot cell groups of interest.\n#'\n#' @param object cellchat object\n#' @param color.use defining the color for each cell group\n#' @param group.by Name of one metadata columns to group (color) cells. Default is the defined cell groups in CellChat object\n#' @param sample.use the sample name used for visualization, which should be the element in `object@meta$samples`.\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups\n#' @param idents.use a vector giving the index or the name of cell groups of interest\n#' @param alpha the transparency of individual spot\n#' @param shape.by the shape of individual spot\n#' @param title.name title name\n#' @param point.size the size of spots\n#' @param legend.size the size of legend\n#' @param legend.text.size the text size on the legend\n#' @param legend.position legend position\n#' @param ncol number of columns of the legend text\n#' @param byrow arrange the legend text byrow or not\n#' @return\n#' @export\n#'\n#' @examples\nspatialDimPlot <- function(object, color.use = NULL, group.by = NULL, sample.use = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL,\n alpha = 1, shape.by = 16, title.name = NULL, point.size = 2.4,\n legend.size = 5, legend.text.size = 8, legend.position = \"right\", ncol = 1, byrow = FALSE){\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[,group.by]\n labels <- factor(labels)\n }\n cells.level <- levels(labels)\n\n coordinates <- object@images$coordinates\n samples <- object@meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n\n if (is.null(sources.use) & is.null(targets.use)){\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n } else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use, \"Others\"))\n\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use, targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n\n gg <- ggplot(data = coordinates,aes(x=x_cent,y=y_cent,colour = labels))+\n geom_point(alpha = alpha, size = point.size, shape=shape.by) +\n scale_color_manual(values = color.use, na.value = \"grey90\") + theme(legend.position = legend.position) +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size)) + # , legend.key.size = unit(0.4, \"inches\")\n guides(color = guide_legend(override.aes = list(size=legend.size), ncol = ncol, byrow = byrow)) +\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n coord_fixed() + theme(aspect.ratio = 1)+ theme(legend.key = element_blank())\n gg <- gg + scale_y_reverse()\n\n if (!is.null(title.name)){\n gg <- gg + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))\n }\n return(gg)\n\n}\n\n\n#' A spatial feature plots\n#'\n#' This function takes a CellChat object as input, and then plot gene expression distribution over spots/cells on the image.\n#'\n#' @param object cellchat object\n#' @param features a char vector containing features to visualize. `features` can be genes or column names of `object@meta`.\n#' @param signaling signalling names to visualize\n#' @param pairLR.use a data frame consisting of one column named \"interaction_name\", defining the L-R pairs of interest\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param do.group set `do.group = TRUE` when only showing enriched signaling based on cell group-level communication; set `do.group = FALSE` when only showing enriched signaling based on individual cell-level communication\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param color.heatmap A character string or vector indicating the colormap option to use. It can be the avaibale color palette in brewer.pal() or viridis_pal() (e.g., \"Spectral\",\"viridis\")\n#' @param n.colors,direction n.colors: number of basic colors to generate from color palette; direction: Sets the order of colors in the scale. If 1, the default colors are used. If -1, the order of colors is reversed.\n#' @param do.binary,cutoff whether binarizing the expression using a given cutoff\n#' @param color.use defining the color for cells/spots expressing ligand only, expressing receptor only, expressing both ligand & receptor and cells/spots without expression of given ligands and receptors\n#' @param alpha the transparency of individual spot\n#' @param point.size the size of cell slot\n#' @param shape.by the shape of individual spot\n#' @param legend.size the size of legend\n#' @param legend.text.size the text size on the legend\n#' @param ncol number of columns if plotting multiple plots\n#' @param show.legend whether show each figure legend\n#' @param show.legend.combined whether show the figure legend for the last plot\n#' @return\n#' @export\n#'\n#' @examples\n\nspatialFeaturePlot <- function(object, features = NULL, signaling = NULL, pairLR.use = NULL, sample.use = NULL, enriched.only = TRUE,thresh = 0.05, do.group = TRUE,\n color.heatmap = \"Spectral\", n.colors = 8, direction = -1,\n do.binary = FALSE, cutoff = NULL, color.use = NULL, alpha = 1,\n point.size = 0.8, legend.size = 3, legend.text.size = 8, shape.by = 16, ncol = NULL,\n show.legend = TRUE, show.legend.combined = FALSE){\n data <- object@data\n meta <- object@meta\n coords <- object@images$coordinates\n samples <- meta$samples\n if (ncol(coords) == 2) {\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coords = coords\n coords[,1] = temp_coords[,2]\n coords[,2] = temp_coords[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n scales::viridis_pal(option = color.heatmap, direction = -1)(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n } else {\n colormap <- color.heatmap\n }\n\n if (is.null(features) & is.null(signaling) & is.null(pairLR.use)){\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)){\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)){\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)){\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n\n df <- data.frame(x = coords[, 1], y = coords[, 2])\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, enriched.only = enriched.only, thresh = thresh)\n feature.use <- res$geneLR\n } else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n } else {\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(paste0('There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.'))\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\",\"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex, object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex, object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n } else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) > 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n } else if (length(intersect(feature.use, colnames(meta))) > 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[ ,feature.use, drop = FALSE])\n } else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \",cutoff,\"to the values...\", '\\n')\n data.use[data.use <= cutoff] <- 0\n }\n\n\n if (is.null(ncol)) {\n if (length(feature.use) > 9) {\n ncol <- 4\n } else {\n ncol <- min(length(feature.use), 4)\n }\n }\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i, ]\n g <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = feature.data), alpha = alpha, size=point.size, shape=shape.by) +\n scale_colour_gradientn(colours = colormap, guide = guide_colorbar(title = NULL, ticks = T, label = T, barwidth = 0.5), na.value = \"grey90\") +\n theme(legend.position = \"right\") +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size), legend.key.size = unit(0.15, \"inches\")) + # , legend.key.size = unit(0.4, \"inches\")\n ggtitle(feature.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))+\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n theme(legend.key = element_blank())\n g <- g + coord_fixed() + theme(aspect.ratio = 1) + scale_y_reverse()\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (show.legend.combined & i == numFeature) {\n g <- g + theme(legend.position = \"right\", legend.key.height = grid::unit(0.15, \"in\"), legend.key.width = grid::unit(0.5, \"in\"), legend.title = element_blank(),legend.key = element_blank())\n }\n gg[[i]] <- g\n }\n if (ncol > 1) {\n gg <- patchwork::wrap_plots(gg, ncol = ncol)\n } else {\n gg <- gg[[1]]\n }\n\n } else {\n\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, enriched.only = enriched.only, thresh = thresh)\n # gene.pair = searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n # LR.pair <- gene.pair[res$interaction_name, c(\"ligand\",\"receptor\")]\n LR.pair <- object@LR$LRsig[res$interaction_name, c(\"ligand\",\"receptor\")]\n } else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n } else {\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(paste0('There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.'))\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\",\"receptor\")]\n } else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n # compute the expression of ligand or receptor\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL; rownames(dataR) <- geneR;\n # data.use <- matrix(0, nrow = nrow(dataL)*2, ncol = ncol(dataL))\n # data.use[seq_len(nrow(data.use)) %% 2 == 1, ] <- dataL\n # data.use[seq_len(nrow(data.use)) %% 2 == 0, ] <- dataR\n # rownames(data.use)[seq_len(nrow(data.use)) %% 2 == 1] <- geneL\n # rownames(data.use)[seq_len(nrow(data.use)) %% 2 == 0] <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n if (is.null(ncol)) {\n if (length(feature.use) > 9) {\n ncol <- 4\n } else {\n ncol <- min(length(feature.use), 4)\n }\n }\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \" )\n }\n gg <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i, ] > cutoff\n idx2 = dataR[i, ] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\",ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i],geneR[i],\"Both\",\"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i],geneR[i],\"Both\",\"None\")\n\n if (length(setdiff(levels(group), unique(group))) > 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group), unique(group)))\n }\n\n df$feature.data <- group\n g <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = feature.data), alpha = alpha, size=point.size, shape=shape.by) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size), legend.key.size = unit(0.15, \"inches\")) + # , legend.key.size = unit(0.4, \"inches\")\n guides(color = guide_legend(override.aes = list(size=legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))+\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n theme(legend.key = element_blank())\n g <- g + coord_fixed() + theme(aspect.ratio = 1) + scale_y_reverse()\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (show.legend.combined & i == numFeature) {\n g <- g + theme(legend.position = \"right\", legend.key.height = grid::unit(0.15, \"in\"), legend.key.width = grid::unit(0.5, \"in\"), legend.title = element_blank(),legend.key = element_blank())\n }\n gg[[i]] <- g\n }\n if (ncol > 1) {\n gg <- patchwork::wrap_plots(gg, ncol = ncol)\n } else {\n gg <- gg[[1]]\n }\n\n }\n return(gg)\n}\n"], ["/CellChat/R/analysis.R", "\n#' Compute and visualize the contribution of each ligand-receptor pair in the overall signaling pathways\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param width the width of individual bar\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param return.data whether return the data.frame consisting of the predicted L-R pairs and their contribution\n#' @param x.rotation rotation of x-label\n#' @param title the title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom dplyr select\n#' @importFrom ggplot2 ggplot geom_bar aes coord_flip scale_x_discrete element_text theme ggtitle\n#' @importFrom cowplot ggdraw draw_label plot_grid\n#'\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_contribution <- function(object, signaling, signaling.name = NULL, sources.use = NULL, targets.use = NULL,\n width = 0.1, vertex.receiver = NULL, thresh = 0.05, return.data = FALSE,\n x.rotation = 0, title = \"Contribution of each L-R pair\",\n font.size = 10, font.size.title = 10) {\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pair.name.use = select(object@DB$interaction[rownames(pairLR),],\"interaction_name_2\")\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n\n prob <- prob[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n dimnames(prob)[3] <- pairLR.name.use\n }\n prob <-(prob-min(prob))/(max(prob)-min(prob))\n\n if (is.null(vertex.receiver)) {\n pSum <- apply(prob, 3, sum)\n pSum.max <- sum(prob)\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n y.lim <- max(pSum)\n\n pair.name <- unlist(dimnames(prob)[3])\n pair.name <- factor(pair.name, levels = unique(pair.name))\n if (!is.null(pairLR.name.use)) {\n pair.name <- pair.name.use[as.character(pair.name),1]\n pair.name <- factor(pair.name, levels = unique(pair.name))\n }\n mat <- pSum\n df1 <- data.frame(name = pair.name, contribution = mat)\n if(nrow(df1) < 10) {\n df2 <- data.frame(name = as.character(1:(10-nrow(df1))), contribution = rep(0, 10-nrow(df1)))\n df <- rbind(df1, df2)\n } else {\n df <- df1\n }\n df <- df[order(df$contribution, decreasing = TRUE), ]\n # df$name <- factor(df$name, levels = unique(df$name))\n df$name <- factor(df$name,levels=df$name[order(df$contribution, decreasing = TRUE)])\n df1$name <- factor(df1$name,levels=df1$name[order(df1$contribution, decreasing = TRUE)])\n gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\", width = 0.7) +\n theme_classic() + theme(axis.text.y = element_text(angle = x.rotation, hjust = 1,size=font.size, colour = 'black'), axis.text=element_text(size=font.size),\n axis.title.y = element_text(size= font.size), axis.text.x = element_blank(), axis.ticks = element_blank()) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim) + coord_flip() + theme(legend.position=\"none\") +\n scale_x_discrete(limits = rev(levels(df$name)), labels = c(rep(\"\", max(0, 10-nlevels(df1$name))),rev(levels(df1$name))))\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5, size = font.size.title))\n }\n gg\n\n } else {\n pair.name <- factor(unlist(dimnames(prob)[3]), levels = unique(unlist(dimnames(prob)[3])))\n # show all the communications\n pSum <- apply(prob, 3, sum)\n pSum.max <- sum(prob)\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n y.lim <- max(pSum)\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\",width = 0.2) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8),\n axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"All\")+ theme(plot.title = element_text(hjust = 0.5))#+\n\n # show the communications in Hierarchy1\n if (dim(prob)[3] > 1) {\n pSum <- apply(prob[,vertex.receiver,], 3, sum)\n } else {\n pSum <- sum(prob[,vertex.receiver,])\n }\n\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg1 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\",width = 0.2) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"Hierarchy1\") + theme(plot.title = element_text(hjust = 0.5))#+\n #scale_x_discrete(limits = c(0,1))\n\n # show the communications in Hierarchy2\n\n if (dim(prob)[3] > 1) {\n pSum <- apply(prob[,setdiff(1:dim(prob)[1],vertex.receiver),], 3, sum)\n } else {\n pSum <- sum(prob[,setdiff(1:dim(prob)[1],vertex.receiver),])\n }\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg2 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\", width=0.9) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"Hierarchy2\")+ theme(plot.title = element_text(hjust = 0.5))#+\n #scale_x_discrete(limits = c(0,1))\n title <- cowplot::ggdraw() + cowplot::draw_label(paste0(\"Contribution of each signaling in \", signaling.name, \" pathway\"), fontface='bold', size = 10)\n gg.combined <- cowplot::plot_grid(gg, gg1, gg2, nrow = 1)\n gg.combined <- cowplot::plot_grid(title, gg.combined, ncol = 1, rel_heights=c(0.1, 1))\n gg <- gg.combined\n gg\n }\n if (return.data) {\n df <- subset(df, contribution > 0)\n return(list(LR.contribution = df, gg.obj = gg))\n } else {\n return(gg)\n }\n}\n\n\n#' Compute the network centrality scores allowing identification of dominant senders, receivers, mediators and influencers in all inferred communication networks\n#'\n#' NB: This function was previously named as `netAnalysis_signalingRole`. The previous function `netVisual_signalingRole` is now named as `netAnalysis_signalingRole_network`.\n#'\n#' @param object CellChat object; If object = NULL, USER must provide `net`\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks. Setting slot.name = \"netP\" to compute the network centrality scores at the level of signaling pathways, and setting slot.name = \"net\" to compute the network centrality scores at the level of ligand-receptor pairs\n#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net\n#' @param net.name a character vector giving the name of signaling networks\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom future nbrOfWorkers\n#' @importFrom methods slot\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#'\n#' @return\n#' @export\n#'\nnetAnalysis_computeCentrality <- function(object = NULL, slot.name = \"netP\", net = NULL, net.name = NULL, thresh = 0.05) {\n if (is.null(net)) {\n prob <- methods::slot(object, slot.name)$prob\n pval <- methods::slot(object, slot.name)$pval\n pval[prob == 0] <- 1\n prob[pval >= thresh] <- 0\n net = prob\n }\n if (is.null(net.name)) {\n net.name <- dimnames(net)[[3]]\n }\n if (length(dim(net)) == 3) {\n nrun <- dim(net)[3]\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n centr.all = my.sapply(\n X = 1:nrun,\n FUN = function(x) {\n net0 <- net[ , , x]\n return(computeCentralityLocal(net0))\n },\n simplify = FALSE\n )\n } else {\n centr.all <- as.list(computeCentralityLocal(net))\n }\n names(centr.all) <- net.name\n if (is.null(object)) {\n return(centr.all)\n } else {\n slot(object, slot.name)$centr <- centr.all\n return(object)\n }\n}\n\n\n\n#' Compute Centrality measures for a signaling network\n#'\n#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net\n#' @importFrom igraph graph_from_adjacency_matrix strength hub_score authority_score eigen_centrality page_rank betweenness E\n#' @importFrom sna flowbet infocent\n#'\n#' @return\ncomputeCentralityLocal <- function(net) {\n centr <- vector(\"list\")\n G <- igraph::graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n centr$outdeg_unweighted <- rowSums(net > 0)\n centr$indeg_unweighted <- colSums(net > 0)\n centr$outdeg <- igraph::strength(G, mode=\"out\")\n centr$indeg <- igraph::strength(G, mode=\"in\")\n centr$hub <- igraph::hub_score(G)$vector\n centr$authority <- igraph::authority_score(G)$vector # A node has high authority when it is linked by many other nodes that are linking many other nodes.\n centr$eigen <- igraph::eigen_centrality(G)$vector # A measure of influence in the network that takes into account second-order connections\n centr$page_rank <- igraph::page_rank(G)$vector\n igraph::E(G)$weight <- 1/igraph::E(G)$weight\n centr$betweenness <- igraph::betweenness(G)\n #centr$flowbet <- try(sna::flowbet(net)) # a measure of its role as a gatekeeper for the flow of communication between any two cells; the total maximum flow (aggregated across all pairs of third parties) mediated by v.\n #centr$info <- try(sna::infocent(net)) # actors with higher information centrality are predicted to have greater control over the flow of information within a network; highly information-central individuals tend to have a large number of short paths to many others within the social structure.\n centr$flowbet <- tryCatch({\n sna::flowbet(net)\n }, error = function(e) {\n as.vector(matrix(0, nrow = nrow(net), ncol = 1))\n })\n centr$info <- tryCatch({\n sna::infocent(net, diag = T, rescale = T, cmode = \"lower\")\n # sna::infocent(net, diag = T, rescale = T, cmode = \"weak\")\n }, error = function(e) {\n as.vector(matrix(0, nrow = nrow(net), ncol = 1))\n })\n return(centr)\n}\n\n\n#' Select the number of the patterns for running `identifyCommunicationPatterns`\n#'\n#' We infer the number of patterns based on two metrics that have been implemented in the NMF R package, including Cophenetic and Silhouette. Both metrics measure the stability for a particular number of patterns based on a hierarchical clustering of the consensus matrix. For a range of the number of patterns, a suitable number of patterns is the one at which Cophenetic and Silhouette values begin to drop suddenly.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param k.range a range of the number of patterns\n#' @param title.name title of plot\n#' @param do.facet whether use facet plot showing the two measures\n#' @param nrun number of runs when performing NMF\n#' @param seed.use seed when performing NMF\n#' @importFrom methods slot\n# #' @importFrom NMF nmfEstimateRank\n#' @import NMF\n# #' @importFrom ggplot2 scale_color_brewer\n#' @import ggplot2\n#' @return a ggplot object\n#' @export\n#'\n#' @examples\nselectK <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), title.name = NULL, do.facet = TRUE, k.range = seq(2,10), nrun = 30, seed.use = 10) {\n pattern <- match.arg(pattern)\n prob <- methods::slot(object, slot.name)$prob\n if (pattern == \"outgoing\") {\n data_sender <- apply(prob, c(1,3), sum)\n data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_sender)\n } else if (pattern == \"incoming\") {\n data_receiver <- apply(prob, c(2,3), sum)\n data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_receiver)\n }\n options(warn = -1)\n data <- data0\n data <- data[rowSums(data)!=0,]\n\n if (is.null(title.name)) {\n title.name <- paste0(pattern, \" signaling \\n\")\n # title.name <- paste0(pattern, \" signaling \\n (nrun = \", nrun, \", seed = \", seed.use, \")\")\n }\n\n res <- NMF::nmfEstimateRank(data, range = k.range, method = 'lee', nrun=nrun, seed = seed.use)\n df1 <- data.frame(k = res$measures$rank, score = res$measures$cophenetic, Measure = \"Cophenetic\")\n df2 <- data.frame(k = res$measures$rank, score = res$measures$silhouette.consensus, Measure = \"Silhouette\")\n # df3 <- data.frame(k = res$measures$rank, score = res$measures$dispersion, Measure = \"Dispersion\")\n df <- rbind(df1, df2)\n #df <- rbind(df1, df2, df3)\n gg <- ggplot(df, aes(x = k, y = score, group = Measure, color = Measure)) + geom_line(size=1) +\n geom_point() +\n theme_classic() + labs(x = 'Number of patterns', y='Measure score') +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(legend.position = \"right\") + theme(text = element_text(size = 10)) + scale_x_discrete(limits = (unique(df$k))) +\n scale_color_brewer(palette=\"Set2\") + guides(color=guide_legend(\"Measure type\"))\n if (do.facet) {\n gg <- gg + facet_wrap(~ Measure, scales='free')\n }\n gg\n return(gg)\n}\n\n\n\n#' Identification of major signals for specific cell groups and general communication patterns\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param k the number of patterns\n#' @param k.range a range of the number of patterns\n#' @param heatmap.show whether showing heatmap\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param title.legend the title of legend in heatmap\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @importFrom methods slot\n#' @importFrom NMF nmfEstimateRank nmf\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation draw\n#' @importFrom stats setNames\n#' @importFrom grid grid.grabExpr grid.newpage pushViewport grid.draw unit gpar viewport popViewport\n#'\n#' @return\n#' @export\n#'\n#' @examples\n\nidentifyCommunicationPatterns <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), k = NULL, k.range = seq(2,10), heatmap.show = TRUE,\n color.use = NULL, color.heatmap = \"Spectral\", title.legend = \"Contributions\",\n width = 4, height = 6, font.size = 8) {\n pattern <- match.arg(pattern)\n prob <- methods::slot(object, slot.name)$prob\n if (pattern == \"outgoing\") {\n data_sender <- apply(prob, c(1,3), sum)\n data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_sender)\n } else if (pattern == \"incoming\") {\n data_receiver <- apply(prob, c(2,3), sum)\n data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_receiver)\n }\n options(warn = -1)\n data <- data0\n data <- data[rowSums(data)!=0,]\n if (is.null(k)) {\n stop(\"Please run the function `selectK` for selecting a suitable k!\")\n }\n\n outs_NMF <- NMF::nmf(data, rank = k, method = 'lee', seed = 'nndsvd')\n W <- scaleMat(outs_NMF@fit@W, 'r1')\n H <- scaleMat(outs_NMF@fit@H, 'c1')\n colnames(W) <- paste0(\"Pattern \", seq(1,ncol(W))); rownames(H) <- paste0(\"Pattern \", seq(1,nrow(H)));\n if (heatmap.show) {\n net <- W\n if (is.null(color.use)) {\n color.use <- scPalette(length(rownames(net)))\n }\n color.heatmap = grDevices::colorRampPalette(rev(RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(255)\n\n df<- data.frame(group = rownames(net)); rownames(df) <- rownames(net)\n cell.cols.assigned <- setNames(color.use, unique(as.character(df$group)))\n row_annotation <- HeatmapAnnotation(df = df, col = list(group = cell.cols.assigned),which = \"row\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ht1 = Heatmap(net, col = color.heatmap, na_col = \"white\", name = \"Contribution\",\n left_annotation = row_annotation,\n cluster_rows = T,cluster_columns = F,clustering_method_rows = \"average\",\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n show_heatmap_legend = F,\n column_title = \"Cell patterns\",column_title_gp = gpar(fontsize = 10)\n )\n\n\n net <- t(H)\n\n ht2 = Heatmap(net, col = color.heatmap, na_col = \"white\", name = \"Contribution\",\n cluster_rows = T,cluster_columns = F,clustering_method_rows = \"average\",\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = \"Communication patterns\",column_title_gp = gpar(fontsize = 10),\n heatmap_legend_param = list(title = title.legend, title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = c(round(min(net, na.rm = T), digits = 1), round(max(net, na.rm = T), digits = 1)),\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 6),grid_width = unit(2, \"mm\"))\n )\n\n gb_ht1 = grid.grabExpr(draw(ht1))\n gb_ht2 = grid.grabExpr(draw(ht2))\n #grid.newpage()\n pushViewport(viewport(x = 0.1, y = 0.1, width = 0.2, height = 0.5, just = c(\"left\", \"bottom\")))\n grid.draw(gb_ht1)\n popViewport()\n\n pushViewport(viewport(x = 0.6, y = 0.1, width = 0.2, height = 0.5, just = c(\"left\", \"bottom\")))\n grid.draw(gb_ht2)\n popViewport()\n\n }\n\n data_W <- as.data.frame(as.table(W)); colnames(data_W) <- c(\"CellGroup\",\"Pattern\",\"Contribution\")\n data_H <- as.data.frame(as.table(H)); colnames(data_H) <- c(\"Pattern\",\"Signaling\",\"Contribution\")\n\n res.pattern = list(\"cell\" = data_W, \"signaling\" = data_H)\n methods::slot(object, slot.name)$pattern[[pattern]] <- list(data = data0, pattern = res.pattern)\n return(object)\n}\n\n\n#' Compute signaling network similarity for any pair of signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param k the number of nearest neighbors\n#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity\n#' @importFrom methods slot\n\n#'\n#' @return\n#' @export\n#'\n#' @examples\ncomputeNetSimilarity <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), k = NULL, thresh = NULL) {\n type <- match.arg(type)\n prob = methods::slot(object, slot.name)$prob\n if (is.null(k)) {\n if (dim(prob)[3] <= 25) {\n k <- ceiling(sqrt(dim(prob)[3]))\n } else {\n k <- ceiling(sqrt(dim(prob)[3])) + 1\n }\n\n }\n if (!is.null(thresh)) {\n prob[prob < quantile(c(prob[prob != 0]), thresh)] <- 0\n }\n if (type == \"functional\") {\n # compute the functional similarity\n D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])\n S2 <- D_signalings; S3 <- D_signalings;\n for (i in 1:(dim(prob)[3]-1)) {\n for (j in (i+1):dim(prob)[3]) {\n Gi <- (prob[ , ,i] > 0)*1\n Gj <- (prob[ , ,j] > 0)*1\n S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)\n }\n }\n # define the similarity matrix\n S3[is.na(S3)] <- 0; S3 <- S3 + t(S3); diag(S3) <- 1\n # S_signalings <- S1 *S2\n S_signalings <- S3\n } else if (type == \"structural\") {\n # compute the structure distance\n D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])\n for (i in 1:(dim(prob)[3]-1)) {\n for (j in (i+1):dim(prob)[3]) {\n Gi <- (prob[ , ,i] > 0)*1\n Gj <- (prob[ , ,j] > 0)*1\n D_signalings[i,j] <- computeNetD_structure(Gi,Gj)\n }\n }\n # define the structure similarity matrix\n D_signalings[is.infinite(D_signalings)] <- 0\n D_signalings[is.na(D_signalings)] <- 0\n D_signalings <- D_signalings + t(D_signalings)\n S_signalings <- 1-D_signalings\n }\n\n # smooth the similarity matrix using SNN\n SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)\n Similarity <- as.matrix(S_signalings*SNN)\n rownames(Similarity) <- dimnames(prob)[[3]]\n colnames(Similarity) <- dimnames(prob)[[3]]\n\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {\n methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity\n return(object)\n}\n\n\n\n#' Compute signaling network similarity for any pair of datasets\n#'\n#' @param object A merged CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison\n#' @param k the number of nearest neighbors\n#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity\n#' @importFrom methods slot\n#'\n#' @return\n#' @export\n#'\ncomputeNetSimilarityPairwise <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, k = NULL, thresh = NULL) {\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Compute signaling network similarity for datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n net <- list()\n signalingAll <- c()\n object.net.nameAll <- c()\n # 1:length(setdiff(names(methods::slot(object, slot.name)), \"similarity\"))\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n object.net.name <- names(methods::slot(object, slot.name))[comparison[i]]\n object.net.nameAll <- c(object.net.nameAll, object.net.name)\n net[[i]] = object.net$prob\n signalingAll <- c(signalingAll, paste0(dimnames(net[[i]])[[3]], \"--\", object.net.name))\n # signalingAll <- c(signalingAll, dimnames(net[[i]])[[3]])\n }\n names(net) <- object.net.nameAll\n net.dim <- sapply(net, dim)[3,]\n nnet <- sum(net.dim)\n position <- cumsum(net.dim); position <- c(0,position)\n\n if (is.null(k)) {\n if (nnet <= 25) {\n k <- ceiling(sqrt(nnet))\n } else {\n k <- ceiling(sqrt(nnet)) + 1\n }\n\n }\n if (!is.null(thresh)) {\n for (i in 1:length(net)) {\n neti <- net[[i]]\n neti[neti < quantile(c(neti[neti != 0]), thresh)] <- 0\n net[[i]] <- neti\n }\n }\n if (type == \"functional\") {\n # compute the functional similarity\n S3 <- matrix(0, nrow = nnet, ncol = nnet)\n for (i in 1:nnet) {\n for (j in 1:nnet) {\n idx.i <- which(position - i >= 0)[1]\n idx.j <- which(position - j >= 0)[1]\n net.i <- net[[idx.i-1]]\n net.j <- net[[idx.j-1]]\n Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1\n Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1\n S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)\n }\n }\n\n # define the similarity matrix\n S3[is.na(S3)] <- 0; diag(S3) <- 1\n S_signalings <- S3\n } else if (type == \"structural\") {\n # compute the structure distance\n D_signalings <- matrix(0, nrow = nnet, ncol = nnet)\n for (i in 1:nnet) {\n for (j in 1:nnet) {\n idx.i <- which(position - i >= 0)[1]\n idx.j <- which(position - j >= 0)[1]\n net.i <- net[[idx.i-1]]\n net.j <- net[[idx.j-1]]\n Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1\n Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1\n D_signalings[i,j] <- computeNetD_structure(Gi,Gj)\n }\n }\n # define the structure similarity matrix\n D_signalings[is.infinite(D_signalings)] <- 0\n D_signalings[is.na(D_signalings)] <- 0\n S_signalings <- 1-D_signalings\n }\n # smooth the similarity matrix using SNN\n SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)\n Similarity <- as.matrix(S_signalings*SNN)\n rownames(Similarity) <- signalingAll\n colnames(Similarity) <- rownames(Similarity)\n\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {\n methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL\n }\n # methods::slot(object, slot.name)$similarity[[type]]$matrix <- Similarity\n methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity\n return(object)\n}\n\n\n#' Manifold learning of the signaling networks based on their similarity\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object\n#' @param pathway.remove a range of the number of patterns\n#' @param umap.method UMAP implementation to run.\n#'\n#' Can be umap-learn: Run the python umap-learn package; uwot: Runs umap via the uwot R package; If umap.method = \"uwot\", please make sure you have installed the 'uwot' (https://github.com/jlmelville/uwot)\n#'\n#' @param n_neighbors the number of nearest neighbors in running umap\n#' @param min_dist This controls how tightly the embedding is allowed compress points together.\n#' Larger values ensure embedded points are moreevenly distributed, while smaller values allow the\n#' algorithm to optimise more accurately with regard to local structure. Sensible values are in the range 0.001 to 0.5.\n#' @param ... Parameters passing to umap\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetEmbedding <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, pathway.remove = NULL,\n umap.method = c(\"umap-learn\", \"uwot\"), n_neighbors = NULL,min_dist = 0.3,...) {\n umap.method <- match.arg(umap.method)\n if (object@options$mode == \"single\") {\n comparison <- \"single\"\n cat(\"Manifold learning of the signaling networks for a single dataset\", '\\n')\n } else if (object@options$mode == \"merged\") {\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Manifold learning of the signaling networks for datasets\", as.character(comparison), '\\n')\n }\n comparison.name <- paste(comparison, collapse = \"-\")\n Similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n if (is.null(pathway.remove)) {\n pathway.remove <- rownames(Similarity)[which(colSums(Similarity) == 1)]\n }\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(rownames(Similarity) %in% pathway.remove)\n Similarity <- Similarity[-pathway.remove.idx, -pathway.remove.idx]\n }\n if (is.null(n_neighbors)) {\n n_neighbors <- ceiling(sqrt(dim(Similarity)[1])) + 1\n }\n options(warn = -1)\n # dimension reduction\n if (umap.method == \"umap-learn\") {\n Y <- runUMAP(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)\n } else if (umap.method == \"uwot\") {\n Y <- uwot::umap(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)\n colnames(Y) <- paste0('UMAP', 1:ncol(Y))\n rownames(Y) <- colnames(Similarity)\n }\n\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$dr)) {\n methods::slot(object, slot.name)$similarity[[type]]$dr <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]] <- Y\n return(object)\n}\n\n\n#' Classification learning of the signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object\n#' @param k the number of signaling groups when running kmeans\n#' @param methods the methods for clustering: \"kmeans\" or \"spectral\"\n#' @param do.plot whether showing the eigenspectrum for inferring number of clusters; Default will save the plot\n#' @param fig.id add a unique figure id when saving the plot\n#' @param do.parallel whether doing parallel when inferring the number of signaling groups when running kmeans\n#' @param nCores number of workers when doing parallel\n#' @param k.eigen the number of eigenvalues used when doing spectral clustering\n#' @importFrom methods slot\n#' @importFrom future nbrOfWorkers plan\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @return\n#' @export\n#'\n#' @examples\nnetClustering <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, k = NULL, methods = \"kmeans\", do.plot = TRUE, fig.id = NULL, do.parallel = TRUE, nCores = 4, k.eigen = NULL) {\n type <- match.arg(type)\n if (object@options$mode == \"single\") {\n comparison <- \"single\"\n cat(\"Classification learning of the signaling networks for a single dataset\", '\\n')\n } else if (object@options$mode == \"merged\") {\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Classification learning of the signaling networks for datasets\", as.character(comparison), '\\n')\n }\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n data.use <- Y\n if (methods == \"kmeans\") {\n if (!is.null(k)) {\n clusters = kmeans(data.use,k,nstart=10)$cluster\n } else {\n N <- nrow(data.use)\n kRange <- seq(2,min(N-1, 10),by = 1)\n if (do.parallel) {\n future::plan(\"multisession\", workers = nCores)\n options(future.globals.maxSize = 1000 * 1024^2)\n }\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n results = my.sapply(\n X = 1:length(kRange),\n FUN = function(x) {\n idents <- kmeans(data.use,kRange[x],nstart=10)$cluster\n clusIndex <- idents\n #adjMat0 <- as.numeric(outer(clusIndex, clusIndex, FUN = \"==\")) - outer(1:N, 1:N, \"==\")\n adjMat0 <- Matrix::Matrix(as.numeric(outer(clusIndex, clusIndex, FUN = \"==\")), nrow = N, ncol = N)\n return(list(adjMat = adjMat0, ncluster = length(unique(idents))))\n },\n simplify = FALSE\n )\n adjMat <- lapply(results, \"[[\", 1)\n CM <- Reduce('+', adjMat)/length(kRange)\n res <- computeEigengap(as.matrix(CM))\n numCluster <- res$upper_bound\n clusters = kmeans(data.use,numCluster,nstart=10)$cluster\n if (do.plot) {\n gg <- res$gg.obj\n ggsave(filename= paste0(\"estimationNumCluster_\",fig.id,\"_\",type,\"_dataset_\",comparison.name,\".pdf\"), plot=gg, width = 3.5, height = 3, units = 'in', dpi = 300)\n }\n }\n\n } else if (methods == \"spectral\") {\n A <- as.matrix(data.use)\n D <- apply(A, 1, sum)\n L <- diag(D)-A # unnormalized version\n L <- diag(D^-0.5)%*%L%*% diag(D^-0.5) # normalized version\n evL <- eigen(L,symmetric=TRUE) # evL$values is decreasing sorted when symmetric=TRUE\n # pick the first k first k eigenvectors (corresponding k smallest) as data points in spectral space\n plot(rev(evL$values)[1:30])\n Z <- evL$vectors[,(ncol(evL$vectors)-k.eigen+1):ncol(evL$vectors)]\n clusters = kmeans(Z,k,nstart=20)$cluster\n }\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$group)) {\n methods::slot(object, slot.name)$similarity[[type]]$group <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]] <- clusters\n return(object)\n}\n\n\n#' Build SNN matrix\n# #' Adapted from swne (https://github.com/yanwu2014/swne)\n#' @param data.use Features x samples matrix to use to build the SNN\n#' @param k Defines k for the k-nearest neighbor algorithm\n#' @param k.scale Granularity option for k.param\n#' @param prune.SNN Sets the cutoff for acceptable Jaccard distances when\n#' computing the neighborhood overlap for the SNN construction.\n#'\n#' @return Returns similarity matrix in sparse matrix format\n#'\n#' @importFrom FNN get.knn\n#' @importFrom Matrix sparseMatrix\n#' @export\n#'\nbuildSNN <- function(data.use, k = 10, k.scale = 10, prune.SNN = 1/15) {\n n.cells <- ncol(data.use)\n if (n.cells < k) {\n stop(\"k cannot be greater than the number of samples\")\n }\n\n ## find the k-nearest neighbors for each single cell\n my.knn <- FNN::get.knn(t(as.matrix(data.use)), k = min(k.scale * k, n.cells - 1))\n nn.ranked <- cbind(1:n.cells, my.knn$nn.index[, 1:(k - 1)])\n nn.large <- my.knn$nn.index\n\n w <- ComputeSNN(nn.ranked, prune.SNN)\n colnames(w) <- rownames(w) <- colnames(data.use)\n\n Matrix::diag(w) <- 1\n return(w)\n}\n\n\n\n#' Compute the eigengap of a given matrix for inferring the number of clusters\n#'\n#' @param CM consensus matrix\n#' @param tau truncated consensus matrix\n#' @param tol tolerance\n#' @return\n#' @import ggplot2\n#' @export\ncomputeEigengap <- function(CM, tau = NULL, tol = 0.01){\n # compute the drop tolerance, enforcing parsimony of components\n K.init <- computeLaplacian(CM, tol = tol)$n_zeros\n if (is.null(tau)) {\n if (K.init <= 5) {\n tau = 0.3\n } else if (K.init <= 10){\n tau = 0.4\n } else {\n tau = 0.5\n }\n }\n\n # truncate the ensemble consensus matrix\n CM[CM <= tau] <- 0;\n # normalize and make symmetric\n CM <- (CM + t(CM))/2\n eigs <- computeLaplacian(CM, tol = tol)\n\n # compute the largest eigengap\n gaps <- diff(eigs$val)\n upper_bound <- which(gaps == max(gaps))\n\n # compute the number of zero eigenvalues\n lower_bound <- eigs$n_zeros\n\n df <- data.frame(nCluster = 1:min(c(30,length(eigs$val))), eigenVal = eigs$val[1:min(c(30,length(eigs$val)))])\n g <- ggplot(df, aes(x = nCluster, y = eigenVal)) + geom_point(size = 1) +\n geom_point(aes(x= upper_bound, y= eigs$val[upper_bound]), colour=\"red\", size = 3, pch = 1) + theme(legend.position=\"none\")\n title.name <- paste0('Inferred number of clusters: ', upper_bound,'; Min number: ', lower_bound)\n g <- g + labs(title = title.name) + theme_bw() + scale_x_continuous(breaks=seq(0,30,5)) +\n theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = 10)) + labs(x = 'Number of clusters', y = 'Eigenvalue of graph Laplacian')+\n theme(axis.text.x = element_text(size = 8), axis.text.y = element_text(size = 8))\n # ggsave(filename= paste0(\"estimationNumCluster_eigenspectrum\",sample.int(100,1),\".pdf\"), plot=g, width = 3.5, height = 3, units = 'in', dpi = 300)\n return(list(upper_bound = upper_bound,\n lower_bound = lower_bound,\n eigs = eigs,\n gg.obj = g))\n\n}\n\n\n#' Compute eigenvalues of associated Laplacian matrix of a given matrix\n#'\n#' @param CM consensus matrix\n#' @param tol tolerance\n#' @return\n#' @importFrom RSpectra eigs_sym\n#' @importFrom Matrix colSums\n#' @export\ncomputeLaplacian <- function(CM, tol = 0.01) {\n # Normalized Laplacian:\n Dsq <- sqrt(Matrix::colSums(CM))\n L <- -Matrix::t(CM / Dsq) / Dsq\n Matrix::diag(L) <- 1 + Matrix::diag(L)\n\n numEigs <- min(100,nrow(CM))\n res <- RSpectra::eigs_sym(L, k = numEigs, which = \"SM\", opt = list(tol = 1e-4))\n eigs <- abs(Re(res$values))\n n_zeros <- sum(eigs <= tol)\n return(list(val = sort(eigs), n_zeros = n_zeros))\n}\n\n\n#' Rank the similarity of the shared signaling pathways based on their joint manifold learning\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison1 a numerical vector giving the datasets for comparison. This should be the same as `comparison` in `computeNetSimilarityPairwise`\n#' @param comparison2 a numerical vector with two elements giving the datasets for comparison.\n#'\n#' If there are more than 2 datasets defined in `comparison1`, `comparison2` can be defined to indicate which two datasets used for computing the distance.\n#' e.g., comparison2 = c(1,3) indicates the first and third datasets defined in `comparison1` will be used for comparison.\n#' @param x.rotation rotation of x-labels\n#' @param title main title of the plot\n#' @param bar.w the width of bar plot\n#' @param color.use defining the color\n#' @param font.size font size\n#' @import ggplot2\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nrankSimilarity <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison1 = NULL, comparison2 = c(1,2),\n x.rotation = 90, title = NULL, color.use = NULL, bar.w = NULL, font.size = 8) {\n type <- match.arg(type)\n\n if (is.null(comparison1)) {\n comparison1 <- 1:length(unique(object@meta$datasets))\n }\n comparison.name <- paste(comparison1, collapse = \"-\")\n cat(\"Compute the distance of signaling networks between datasets\", as.character(comparison1[comparison2]), '\\n')\n comparison2.name <- names(methods::slot(object, slot.name))[comparison1[comparison2]]\n # net <- list()\n # for (i in 1:length(comparison2)) {\n # net[[i]] = methods::slot(object, slot.name)[[comparison1[comparison2[i]]]]$prob\n # }\n\n #net.dim <- sapply(net, dim)[3,]\n #position <- cumsum(net.dim); position <- c(0,position)\n # if (is.null(pathway.remove)) {\n # similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n # pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove.idx <- which(rownames(similarity) %in% pathway.remove)\n # }\n\n # if (length(pathway.remove.idx) > 0) {\n # for (i in 1:length(pathway.remove.idx)) {\n # idx <- which(position - pathway.remove.idx[i] > 0)\n # if (!is.null(idx)) {\n # position[idx[1]] <- position[idx[1]] - 1\n # if (idx[1] == 2) {\n # position[3] <- position[3] - 1\n # }\n # }\n # }\n # }\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n group <- sub(\".*--\", \"\", rownames(Y))\n data1 <- Y[group %in% comparison2.name[1], ]\n data2 <- Y[group %in% comparison2.name[2], ]\n rownames(data1) <- sub(\"--.*\", \"\", rownames(data1))\n rownames(data2) <- sub(\"--.*\", \"\", rownames(data2))\n\n pathway.show = as.character(intersect(rownames(data1), rownames(data2)))\n data1 <- data1[pathway.show, ]\n data2 <- data2[pathway.show, ]\n euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))\n dist <- NULL\n for(i in 1:nrow(data1)) dist[i] <- euc.dist(data1[i,],data2[i,])\n df <- data.frame(name = pathway.show, dist = dist, row.names = pathway.show)\n df <- df[order(df$dist), , drop = F]\n df$name <- factor(df$name, levels = as.character(df$name))\n\n gg <- ggplot(df, aes(x=name, y=dist)) + geom_bar(stat=\"identity\",width = bar.w) +\n theme_classic() + theme(text=element_text(size=font.size),axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_text(size=font.size)) +\n xlab(\"\") + ylab(\"Pathway distance\") + coord_flip()#+\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n if (!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = 1), drop = FALSE, na.value = \"white\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, na.value = \"white\")\n }\n return(gg)\n}\n\n\n\n\n\n\n\n#' Rank signaling networks based on the information flow or the number of interactions\n#'\n#' This function can also be used to rank signaling from certain cell groups to other cell groups\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param measure \"weight\" or \"count\". \"weight\": comparing the total interaction weights (strength); \"count\": comparing the number of interactions;\n#' @param mode \"single\",\"comparison\"\n#' @param comparison a numerical vector giving the datasets for comparison; a single value means ranking for only one dataset and two values means ranking comparison for two datasets\n#' @param color.use defining the color for each cell group\n#' @param stacked whether plot the stacked bar plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a vector giving the signaling pathway to show\n#' @param pairLR a vector giving the names of L-R pairs to show (e.g, pairLR = c(\"IL1A_IL1R1_IL1RAP\",\"IL1B_IL1R1_IL1RAP\"))\n#' @param signaling.type a char giving the types of signaling from the three categories c(\"Secreted Signaling\", \"ECM-Receptor\", \"Cell-Cell Contact\")\n#' @param do.stat whether do a Wilcoxon test to determine whether there is significant difference between two datasets. Default = FALSE\n#' @param paired.test a logical indicating whether you want a paired test. Paired test is applicable to compare two datasets with the same cellular compositions.\n#' @param cutoff.pvalue the cutoff of pvalue when doing Wilcoxon test; Default = 0.05\n#' @param tol a tolerance when considering the relative contribution being equal between two datasets. contribution.relative between 1-tol and 1+tol will be considered as equal contribution\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @param do.flip whether flip the x-y axis\n#' @param x.angle,y.angle,x.hjust,y.hjust parameters for rotating and spacing axis labels\n#' @param axis.gap whetehr making gaps in y-axes\n#' @param ylim,segments,tick_width,rel_heights parameters in the function gg.gap when making gaps in y-axes\n#' e.g., ylim = c(0, 35), segments = list(c(11, 14),c(16, 28)), tick_width = c(5,2,5), rel_heights = c(0.8,0,0.1,0,0.1)\n#' https://tobiasbusch.xyz/an-r-package-for-everything-ep2-gaps\n#' @param show.raw whether show the raw information flow. Default = FALSE, showing the scaled information flow to provide compariable data scale; When stacked = TRUE, use raw information flow by default.\n#' @param return.data whether return the data.frame consisting of the calculated information flow of each signaling pathway or L-R pair\n#' @param x.rotation rotation of x-labels\n#' @param title main title of the plot\n#' @param bar.w the width of bar plot\n#' @param font.size font size\n\n#' @import ggplot2\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nrankNet <- function(object, slot.name = \"netP\", measure = c(\"weight\",\"count\"), mode = c(\"comparison\", \"single\"), comparison = c(1,2), color.use = NULL, stacked = FALSE, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR = NULL, signaling.type = NULL, do.stat = FALSE, paired.test = TRUE, cutoff.pvalue = 0.05, tol = 0.05, thresh = 0.05, show.raw = FALSE, return.data = FALSE, x.rotation = 90, title = NULL, bar.w = 0.75, font.size = 8,\n do.flip = TRUE, x.angle = NULL, y.angle = 0, x.hjust = 1,y.hjust = 1,\n axis.gap = FALSE, ylim = NULL, segments = NULL, tick_width = NULL, rel_heights = c(0.9,0,0.1)) {\n measure <- match.arg(measure)\n mode <- match.arg(mode)\n options(warn = -1)\n object.names <- names(methods::slot(object, slot.name))\n if (measure == \"weight\") {\n ylabel = \"Information flow\"\n } else if (measure == \"count\") {\n ylabel = \"Number of interactions\"\n }\n if (mode == \"single\") {\n object1 <- methods::slot(object, slot.name)\n prob = object1$prob\n prob[object1$pval > thresh] <- 0\n if (measure == \"count\") {\n prob <- 1*(prob > 0)\n }\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n if (sum(prob) == 0) {\n stop(\"No inferred communications for the input!\")\n }\n\n pSum <- apply(prob, 3, sum)\n pSum.original <- pSum\n if (measure == \"weight\") {\n pSum <- -1/log(pSum)\n pSum[is.na(pSum)] <- 0\n idx1 <- which(is.infinite(pSum) | pSum < 0)\n values.assign <- seq(max(pSum)*1.1, max(pSum)*1.5, length.out = length(idx1))\n position <- sort(pSum.original[idx1], index.return = TRUE)$ix\n pSum[idx1] <- values.assign[match(1:length(idx1), position)]\n } else if (measure == \"count\") {\n pSum <- pSum.original\n }\n\n pair.name <- names(pSum)\n\n df<- data.frame(name = pair.name, contribution = pSum.original, contribution.scaled = pSum, group = object.names[comparison[1]])\n idx <- with(df, order(df$contribution))\n df <- df[idx, ]\n df$name <- factor(df$name, levels = as.character(df$name))\n for (i in 1:length(pair.name)) {\n df.t <- df[df$name == pair.name[i], \"contribution\"]\n if (sum(df.t) == 0) {\n df <- df[-which(df$name == pair.name[i]), ]\n }\n }\n\n if (!is.null(signaling.type)) {\n LR <- subset(object@DB$interaction, annotation %in% signaling.type)\n if (slot.name == \"netP\") {\n signaling <- unique(LR$pathway_name)\n } else if (slot.name == \"net\") {\n pairLR <- LR$interaction_name\n }\n }\n\n if ((slot.name == \"netP\") && (!is.null(signaling))) {\n df <- subset(df, name %in% signaling)\n } else if ((slot.name == \"netP\") &&(!is.null(pairLR))) {\n stop(\"You need to set `slot.name == 'net'` if showing specific L-R pairs \")\n }\n if ((slot.name == \"net\") && (!is.null(pairLR))) {\n df <- subset(df, name %in% pairLR)\n } else if ((slot.name == \"net\") && (!is.null(signaling))) {\n stop(\"You need to set `slot.name == 'netP'` if showing specific signaling pathways \")\n }\n\n gg <- ggplot(df, aes(x=name, y=contribution.scaled)) + geom_bar(stat=\"identity\",width = bar.w) +\n theme_classic() + theme(axis.text=element_text(size=font.size),axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(ylabel) + coord_flip()#+\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n\n } else if (mode == \"comparison\") {\n prob.list <- list()\n pSum <- list()\n pSum.original <- list()\n pair.name <- list()\n idx <- list()\n pSum.original.all <- c()\n object.names.comparison <- c()\n for (i in 1:length(comparison)) {\n object.list <- methods::slot(object, slot.name)[[comparison[i]]]\n prob <- object.list$prob\n prob[object.list$pval > thresh] <- 0\n if (measure == \"count\") {\n prob <- 1*(prob > 0)\n }\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n if (sum(prob) == 0) {\n stop(\"No inferred communications for the input!\")\n }\n prob.list[[i]] <- prob\n pSum.original[[i]] <- apply(prob, 3, sum)\n if (measure == \"weight\") {\n pSum[[i]] <- -1/log(pSum.original[[i]])\n pSum[[i]][is.na(pSum[[i]])] <- 0\n idx[[i]] <- which(is.infinite(pSum[[i]]) | pSum[[i]] < 0)\n pSum.original.all <- c(pSum.original.all, pSum.original[[i]][idx[[i]]])\n } else if (measure == \"count\") {\n pSum[[i]] <- pSum.original[[i]] # the prob is already binarized in line 1136\n }\n pair.name[[i]] <- names(pSum.original[[i]])\n object.names.comparison <- c(object.names.comparison, object.names[comparison[i]])\n }\n if (measure == \"weight\") {\n values.assign <- seq(max(unlist(pSum))*1.1, max(unlist(pSum))*1.5, length.out = length(unlist(idx)))\n position <- sort(pSum.original.all, index.return = TRUE)$ix\n for (i in 1:length(comparison)) {\n if (i == 1) {\n pSum[[i]][idx[[i]]] <- values.assign[match(1:length(idx[[i]]), position)]\n } else {\n pSum[[i]][idx[[i]]] <- values.assign[match(length(unlist(idx[1:i-1]))+1:length(unlist(idx[1:i])), position)]\n }\n }\n }\n\n\n\n pair.name.all <- as.character(unique(unlist(pair.name)))\n df <- list()\n for (i in 1:length(comparison)) {\n df[[i]] <- data.frame(name = pair.name.all, contribution = 0, contribution.scaled = 0, group = object.names[comparison[i]], row.names = pair.name.all)\n df[[i]][pair.name[[i]],3] <- pSum[[i]]\n df[[i]][pair.name[[i]],2] <- pSum.original[[i]]\n }\n\n\n # contribution.relative <- as.numeric(format(df[[length(comparison)]]$contribution/abs(df[[1]]$contribution), digits=1))\n # # contribution.relative <- as.numeric(format(df[[length(comparison)]]$contribution.scaled/abs(df[[1]]$contribution.scaled), digits=1))\n # contribution.relative2 <- as.numeric(format(df[[length(comparison)-1]]$contribution/abs(df[[1]]$contribution), digits=1))\n # contribution.relative[is.na(contribution.relative)] <- 0\n # for (i in 1:length(comparison)) {\n # df[[i]]$contribution.relative <- contribution.relative\n # df[[i]]$contribution.relative2 <- contribution.relative2\n # }\n # df[[1]]$contribution.data2 <- df[[length(comparison)]]$contribution\n # idx <- with(df[[1]], order(-contribution.relative, -contribution.relative2, contribution, -contribution.data2))\n #\n contribution.relative <- list()\n for (i in 1:(length(comparison)-1)) {\n contribution.relative[[i]] <- as.numeric(format(df[[length(comparison)-i+1]]$contribution/df[[1]]$contribution, digits=1))\n contribution.relative[[i]][is.na(contribution.relative[[i]])] <- 0\n }\n names(contribution.relative) <- paste0(\"contribution.relative.\", 1:length(contribution.relative))\n for (i in 1:length(comparison)) {\n for (j in 1:length(contribution.relative)) {\n df[[i]][[names(contribution.relative)[j]]] <- contribution.relative[[j]]\n }\n }\n df[[1]]$contribution.data2 <- df[[length(comparison)]]$contribution\n if (length(comparison) == 2) {\n idx <- with(df[[1]], order(-contribution.relative.1, contribution, -contribution.data2))\n } else if (length(comparison) == 3) {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2,contribution, -contribution.data2))\n } else if (length(comparison) == 4) {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2, -contribution.relative.3, contribution, -contribution.data2))\n } else {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2, -contribution.relative.3, -contribution.relative.4, contribution, -contribution.data2))\n }\n\n\n\n for (i in 1:length(comparison)) {\n df[[i]] <- df[[i]][idx, ]\n df[[i]]$name <- factor(df[[i]]$name, levels = as.character(df[[i]]$name))\n }\n df[[1]]$contribution.data2 <- NULL\n\n df <- do.call(rbind, df)\n df$group <- factor(df$group, levels = object.names.comparison)\n\n if (is.null(color.use)) {\n color.use = ggPalette(length(comparison))\n }\n\n # https://stackoverflow.com/questions/49448497/coord-flip-changes-ordering-of-bars-within-groups-in-grouped-bar-plot\n df$group <- factor(df$group, levels = rev(levels(df$group)))\n color.use <- rev(color.use)\n\n # perform statistical analysis\n # if (do.stat) {\n # pvalues <- c()\n # for (i in 1:length(pair.name.all)) {\n # df.prob <- data.frame()\n # for (j in 1:length(comparison)) {\n # if (pair.name.all[i] %in% pair.name[[j]]) {\n # df.prob <- rbind(df.prob, data.frame(prob = as.vector(prob.list[[j]][ , , pair.name.all[i]]), group = comparison[j]))\n # } else {\n # df.prob <- rbind(df.prob, data.frame(prob = as.vector(matrix(0, nrow = nrow(prob.list[[j]]), ncol = nrow(prob.list[[j]]))), group = comparison[j]))\n # }\n #\n # }\n # df.prob$group <- factor(df.prob$group, levels = comparison)\n # if (length(comparison) == 2) {\n # pvalues[i] <- wilcox.test(prob ~ group, data = df.prob)$p.value\n # } else {\n # pvalues[i] <- kruskal.test(prob ~ group, data = df.prob)$p.value\n # }\n # }\n # df$pvalues <- pvalues\n # }\n if (do.stat & length(comparison) == 2) {\n for (i in 1:length(pair.name.all)) {\n if (nrow(prob.list[[j]]) != nrow(prob.list[[1]])) {\n if (paired.test) {\n stop(\"Paired test is not applicable to datasets with different cellular compositions! Please set `do.stat = FALSE` or `paired.test = FALSE`! \\n\")\n }\n }\n prob.values <- matrix(0, nrow = nrow(prob.list[[1]]) * nrow(prob.list[[1]]), ncol = length(comparison))\n for (j in 1:length(comparison)) {\n if (pair.name.all[i] %in% pair.name[[j]]) {\n prob.values[, j] <- as.vector(prob.list[[j]][ , , pair.name.all[i]])\n } else {\n prob.values[, j] <- NA\n }\n }\n prob.values <- prob.values[rowSums(prob.values, na.rm = TRUE) != 0, , drop = FALSE]\n if (nrow(prob.values) >3 & sum(is.na(prob.values)) == 0) {\n pvalues <- wilcox.test(prob.values[ ,1], prob.values[ ,2], paired = paired.test)$p.value\n } else {\n pvalues <- 0\n }\n pvalues[is.na(pvalues)] <- 0\n df$pvalues[df$name == pair.name.all[i]] <- pvalues\n }\n }\n\n\n if (length(comparison) == 2) {\n if (do.stat) {\n colors.text <- ifelse((df$contribution.relative < 1-tol) & (df$pvalues < cutoff.pvalue), color.use[2], ifelse((df$contribution.relative > 1+tol) & df$pvalues < cutoff.pvalue, color.use[1], \"black\"))\n } else {\n colors.text <- ifelse(df$contribution.relative < 1-tol, color.use[2], ifelse(df$contribution.relative > 1+tol, color.use[1], \"black\"))\n }\n } else {\n message(\"The text on the y-axis will not be colored for the number of compared datasets larger than 3!\")\n colors.text = NULL\n }\n\n for (i in 1:length(pair.name.all)) {\n df.t <- df[df$name == pair.name.all[i], \"contribution\"]\n if (sum(df.t) == 0) {\n df <- df[-which(df$name == pair.name.all[i]), ]\n }\n }\n\n if ((slot.name == \"netP\") && (!is.null(signaling))) {\n df <- subset(df, name %in% signaling)\n } else if ((slot.name == \"netP\") &&(!is.null(pairLR))) {\n stop(\"You need to set `slot.name == 'net'` if showing specific L-R pairs \")\n }\n if ((slot.name == \"net\") && (!is.null(pairLR))) {\n df <- subset(df, name %in% pairLR)\n } else if ((slot.name == \"net\") && (!is.null(signaling))) {\n stop(\"You need to set `slot.name == 'netP'` if showing specific signaling pathways \")\n }\n\n if (stacked) {\n gg <- ggplot(df, aes(x=name, y=contribution, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position =\"fill\") # +\n # xlab(\"\") + ylab(\"Relative information flow\") #+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n # scale_y_discrete(breaks=c(\"0\",\"0.5\",\"1\")) +\n if (measure == \"weight\") {\n gg <- gg + xlab(\"\") + ylab(\"Relative information flow\")\n } else if (measure == \"count\") {\n gg <- gg + xlab(\"\") + ylab(\"Relative number of interactions\")\n }\n\n gg <- gg + geom_hline(yintercept = 0.5, linetype=\"dashed\", color = \"grey50\", size=0.5)\n } else {\n if (show.raw) {\n gg <- ggplot(df, aes(x=name, y=contribution, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position = position_dodge(0.8)) +\n xlab(\"\") + ylab(ylabel) #+ coord_flip()#+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n } else {\n gg <- ggplot(df, aes(x=name, y=contribution.scaled, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position = position_dodge(0.8)) +\n xlab(\"\") + ylab(ylabel) #+ coord_flip()#+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n }\n\n if (axis.gap) {\n gg <- gg + theme_bw() + theme(panel.grid = element_blank())\n gg.gap::gg.gap(gg,\n ylim = ylim,\n segments = segments,\n tick_width = tick_width,\n rel_heights = rel_heights)\n }\n }\n gg <- gg + CellChat_theme_opts() + theme_classic()\n if (do.flip) {\n gg <- gg + coord_flip() + theme(axis.text.y = element_text(colour = colors.text))\n if (is.null(x.angle)) {\n x.angle = 0\n }\n\n } else {\n if (is.null(x.angle)) {\n x.angle = 45\n }\n gg <- gg + scale_x_discrete(limits = rev) + theme(axis.text.x = element_text(colour = rev(colors.text)))\n\n }\n\n gg <- gg + theme(axis.text=element_text(size=font.size), axis.title.y = element_text(size=font.size))\n gg <- gg + scale_fill_manual(name = \"\", values = color.use)\n gg <- gg + guides(fill = guide_legend(reverse = TRUE))\n gg <- gg + theme(axis.text.x = element_text(angle = x.angle, hjust=x.hjust),\n axis.text.y = element_text(angle = y.angle, hjust=y.hjust))\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n }\n\n if (return.data) {\n df$contribution <- abs(df$contribution)\n df$contribution.scaled <- abs(df$contribution.scaled)\n return(list(signaling.contribution = df, gg.obj = gg))\n } else {\n return(gg)\n }\n}\n\n\n#' Comparing the number of inferred communication links between different datasets\n#'\n#' @param object A merged CellChat object\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param color.use defining the color for each group of datasets\n#' @param group a vector giving the groups of different datasets to define colors of the bar plot. Default: only one group and a single color\n#' @param group.levels the factor level in the defined group\n#' @param group.facet Name of one metadata column defining faceting groups\n#' @param group.facet.levels the factor level in the defined group.facet\n#' @param n.row Number of rows in facet_grid()\n#' @param color.alpha transparency\n#' @param legend.title legend title\n#' @param width bar width\n#' @param title.name main title of the plot\n#' @param digits integer indicating the number of decimal places (round) to be used when `measure` is `weight`.\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param remove.xtick whether remove xtick\n#' @param size.text font size of the text\n#' @param show.legend whether show the legend\n#' @param x.lab.rot,angle.x,vjust.x,hjust.x adjusting parameters if rotating xtick.labels when x.lab.rot = TRUE\n#' @import ggplot2\n#' @return A ggplot object\n#' @export\n#'\ncompareInteractions <- function(object, measure = c(\"count\", \"weight\"), color.use = NULL, group = NULL, group.levels = NULL, group.facet = NULL, group.facet.levels = NULL, n.row = 1, color.alpha = 1, legend.title = NULL, width=0.6, title.name = NULL, digits = 3,\n xlabel = NULL, ylabel = NULL, remove.xtick = FALSE,\n show.legend = TRUE, x.lab.rot = FALSE, angle.x = 45, vjust.x = NULL, hjust.x = 1, size.text = 10) {\n measure <- match.arg(measure)\n if (measure == \"count\") {\n df <- as.data.frame(sapply(object@net, function(x) sum(x$count)))\n if (is.null(ylabel)) {\n ylabel = \"Number of inferred interactions\"\n }\n } else if (measure == \"weight\") {\n df <- as.data.frame(sapply(object@net, function(x) sum(x$weight)))\n df[,1] <- round(df[,1],digits)\n if (is.null(ylabel)) {\n ylabel = \"Interaction strength\"\n }\n }\n colnames(df) <- \"count\"\n\n df$dataset <- names(object@net)\n if (is.null(group)) {\n group <- 1\n }\n df$group <- group\n df$dataset <- factor(df$dataset, levels = names(object@net))\n if (is.null(group.levels)) {\n df$group <- factor(df$group)\n } else {\n df$group <- factor(df$group, levels = group.levels)\n }\n\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(group)))\n }\n # theme_classic() #+ scale_x_discrete(limits = (levels(df$x)))\n if (!is.null(group.facet)) {\n if (all(group.facet %in% colnames(df))) {\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n gg <- gg + facet_wrap(group.facet, nrow = n.row)\n } else {\n df$group.facet <- group.facet\n if (is.null(group.facet.levels)) {\n df$group.facet <- factor(df$group.facet)\n } else {\n df$group.facet <- factor(df$group.facet, levels = group.facet.levels)\n }\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n gg <- gg + facet_wrap(~group.facet, nrow = n.row)\n }\n } else {\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n }\n gg <- gg + geom_text(aes(label=count), vjust=-0.3, size=3, position = position_dodge(0.9))\n gg <- gg + ylab(ylabel) + xlab(xlabel) + theme_classic() +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = size.text), axis.text = element_text(colour=\"black\"))\n gg <- gg + scale_fill_manual(values = alpha(color.use, alpha = color.alpha), drop = FALSE)\n # gg <- gg + scale_color_manual(values = alpha(color.use, alpha = 1), drop = FALSE) + guides(colour = FALSE)\n if (remove.xtick) {\n gg <- gg + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank())\n }\n if (is.null(legend.title)) {\n gg <- gg + theme(legend.title = element_blank())\n } else {\n gg <- gg + guides(fill=guide_legend(legend.title))\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n if (x.lab.rot) {\n gg <- gg + theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x, vjust = vjust.x, size=size.text))\n }\n gg\n return(gg)\n}\n\n\n#' Rank ligand-receptor interactions for any pair of two cell groups\n#'\n#' @param object CellChat object\n#' @param LR.use ligand-receptor interactions used in inferring communication network\n#' @return\n#' @export\n#'\nrankNetPairwise <- function(object, LR.use = NULL) {\n if (is.null(LR.use)) {\n pairLR.use <- object@LR$LRsig\n } else {\n pairLR.use <- LR.use\n }\n net <- object@net\n prob <- net$prob\n pval <- net$pval\n numCluster <- dim(prob)[1]\n pairwiseLR <- list()\n for (i in 1:numCluster) {\n temp <- list()\n for (j in 1:numCluster) {\n pvalij <- pval[i,j,]; pvalij <- as.vector(pvalij)\n probij <- prob[i,j,]; probij <- as.vector(probij)\n index <- 1:length(pvalij)\n data <- data.frame(pathway_index = index, interaction_name = pairLR.use$interaction_name, interaction_name_2 = pairLR.use$interaction_name_2, pathway_name = pairLR.use$pathway_name, ligand = pairLR.use$ligand, receptor = pairLR.use$receptor,\n prob = probij, pval = pvalij, row.names = rownames(pairLR.use))\n temp[[j]] <- data[with(data, order(pval, -prob)), ]\n }\n names(temp) <- colnames(prob)\n pairwiseLR[[i]] <- temp\n }\n names(pairwiseLR) <- rownames(prob)\n object@net$pairwiseRank <- pairwiseLR\n return(object)\n}\n\n\n#' compute the Shannon entropy\n#'\n#' @param a a numeric vector\n#' @return\nentropia<-function(a){\n a<-a[which(a>0)]\n return(-sum(a*log(a)))\n}\n\n\n#' compute the node distance matrix\n#'\n#' @param g a graph objecct\n#' @return\nnode_distance<-function(g){\n n<-length(V(g))\n if(n==1){\n retorno=1\n }\n\n if(n>1){\n a<-Matrix::Matrix(0,nrow=n,ncol=n,sparse=TRUE)\n m<-igraph::shortest.paths(g,algorithm=c(\"unweighted\"))\n m[which(m==\"Inf\")]<-n\n quem<-setdiff(intersect(m,m),0)\n for(j in (1:length(quem))){\n\n l<-which(m==quem[j])/n\n\n linhas<-floor(l)+1\n\n posicoesm1<-which(l==floor(l))\n\n if(length(posicoesm1)>0){\n linhas[posicoesm1]<-linhas[posicoesm1]-1\n }\n a[1:n,quem[j]]<-hist(linhas,plot=FALSE,breaks=(0:n))$counts\n\n }\n retorno=(a/(n-1))\n }\n return(retorno)\n}\n\n\n#' compute nnd\n#'\n#' @param g a graph objecct\n#' @return\nnnd<-function(g){\n\n N<-length(V(g))\n\n nd<-node_distance(g)\n\n pdfm<-Matrix::colMeans(nd)\n\n norm<-log(max(c(2,length(which(pdfm[1:(N-1)]>0))+1)))\n\n return(c(pdfm,max(c(0,entropia(pdfm)-entropia(as.matrix(nd))/N))/norm))\n}\n\n#' compute alpha centrality\n#'\n#' @param g a graph objecct\n#' @importFrom igraph degree alpha.centrality\n#' @return\nalpha_centrality<-function(g){\n\n N<-length(igraph::V(g))\n\n r<-sort(igraph::alpha.centrality(g,exo=igraph::degree(g)/(N-1),alpha=1/N))/((N^2))\n\n return(c(r,max(c(0,1-sum(r)))))\n\n}\n\n#' Compute the structural distance between two signaling networks\n#'\n#' @param g a graph object of one signaling network\n#' @param h a graph object of another signaling network\n#' @param w1 parameter\n#' @param w2 parameter\n#' @param w3 parameter\n#' @importFrom igraph graph_from_adjacency_matrix V graph.complementer\n#' @return\n#' @export\n#'\n#' @examples\ncomputeNetD_structure <- function(g, h, w1 = 0.45, w2 = 0.45, w3 = 0.1){\n\n first<-0\n\n second<-0\n\n third<-0\n\n # g<-read.graph(g,format=c(\"edgelist\"),directed=FALSE)\n #\n # h<-read.graph(h,format=c(\"edgelist\"),directed=FALSE)\n\n g <- graph_from_adjacency_matrix(g,mode=\"directed\")\n h <- graph_from_adjacency_matrix(h,mode=\"directed\")\n\n N<-length(V(g))\n\n M<-length(V(h))\n\n PM<-matrix(0,ncol=max(c(M,N)))\n\n if(w1+w2>0){\n\n pg = nnd(g)\n\n PM[1:(N-1)]=pg[1:(N-1)]\n\n PM[length(PM)]<-pg[N]\n\n ph=nnd(h)\n\n PM[1:(M-1)]=PM[1:(M-1)]+ph[1:(M-1)]\n\n PM[length(PM)]<-PM[length(PM)]+ph[M]\n\n PM<-PM/2\n\n first<-sqrt(max(c((entropia(PM)-(entropia(pg[1:N])+entropia(ph[1:M]))/2)/log(2),0)))\n\n second<-abs(sqrt(pg[N+1])-sqrt(ph[M+1]))\n\n\n }\n\n if(w3>0){\n\n pg<-alpha_centrality(g)\n\n ph<-alpha_centrality(h)\n\n m<-max(c(length(pg),length(ph)))\n\n Pg<-matrix(0,ncol=m)\n\n Ph<-matrix(0,ncol=m)\n\n Pg[(m-length(pg)+1):m]<-pg\n\n Ph[(m-length(ph)+1):m]<-ph\n\n third<-third+sqrt((entropia((Pg+Ph)/2)-(entropia(pg)+entropia(ph))/2)/log(2))/2\n\n g<-graph.complementer(g)\n\n h<-graph.complementer(h)\n\n\n pg<-alpha_centrality(g)\n\n ph<-alpha_centrality(h)\n\n m<-max(c(length(pg),length(ph)))\n\n Pg<-matrix(0,ncol=m)\n\n Ph<-matrix(0,ncol=m)\n\n Pg[(m-length(pg)+1):m]<-pg\n\n Ph[(m-length(ph)+1):m]<-ph\n\n third<-third+sqrt((entropia((Pg+Ph)/2)-(entropia(pg)+entropia(ph))/2)/log(2))/2\n }\n return(w1*first+w2*second+w3*third)\n}\n\n\n#' Identify all the significant interactions (L-R pairs) and related signaling genes for a given signaling pathway\n#'\n#' @param object CellChat object\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param geneLR.return whether return the related signaling genes of enriched L-R pairs\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param geneInfo a dataframe with gene official symbol (there should be one column named `Symbol`)\n#' @param complex_input signaling complex information from CellChatDB\n#' @importFrom dplyr select\n#'\n#' @return The returned value depends on the input argument:\n#'\n#' When `geneLR.return = FALSE`, it returns a data frame containing the significant interactions (L-R pairs)\n#'\n#' When `geneLR.return = TRUE`, it returns a list, the first element is a data frame containing the significant interactions (L-R pairs), and the second is a vector containing the related signaling genes of enriched L-R pairs, which can be used for examining the gene expression pattern using the function \\code{\\link{plotGeneExpression}}\n#'\n#' @export\n#'\nextractEnrichedLR <- function(object, signaling, geneLR.return = FALSE, enriched.only = TRUE, thresh = 0.05, geneInfo = NULL, complex_input = NULL) {\n DB <- object@DB\n if (is.null(geneInfo)) {\n geneInfo = DB$geneInfo\n } else {\n DB$geneInfo = geneInfo\n }\n if (is.null(complex_input)) {\n complex_input = DB$complex\n } else {\n DB$complex = complex_input\n }\n pairLR.all <- c()\n geneLR.all <- c()\n net0 <- slot(object, \"net\")\n for (ii in 1:length(signaling)) {\n signaling.i <- signaling[ii]\n if (object@options$mode == \"single\") {\n net <- net0\n LR <- object@LR\n res <- extractEnrichedLR_internal(net, LR, DB, signaling = signaling.i, enriched.only = enriched.only, thresh = thresh)\n } else {\n geneLR.t <- c()\n pairLR.t <- c()\n for (i in 1:length(net0)) {\n net <- net0[[i]]\n LR <- object@LR[[i]]\n res.t <- extractEnrichedLR_internal(net, LR, DB, signaling = signaling.i, enriched.only = enriched.only, thresh = thresh)\n geneLR.t <- BiocGenerics::union(geneLR.t, as.character(res.t[[1]]))\n pairLR.t <- BiocGenerics::union(pairLR.t, as.character(res.t[[2]]))\n }\n res <- list(geneLR.t, pairLR.t)\n }\n geneLR.all <- c(geneLR.all, as.character(res[[1]]))\n pairLR.all <- c(pairLR.all, as.character(res[[2]]))\n }\n pairLR.all <- data.frame(interaction_name = pairLR.all, stringsAsFactors = FALSE)\n\n if (geneLR.return) {\n return(list(pairLR = pairLR.all, geneLR = geneLR.all))\n } else {\n return(pairLR.all)\n }\n}\n\n#' Identify all the significant interactions (L-R pairs) and related signaling genes for a given signaling pathway\n#'\n#' @param net,LR,DB object@net object@LR object@DB\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom dplyr select\n#'\n#' @return a list: list(geneLR, pairLR.name.use)\nextractEnrichedLR_internal <- function(net, LR, DB, signaling, enriched.only = TRUE, thresh = 0.05){\n pairLR <- searchPair(signaling = signaling, pairLR.use = LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.name.use = dplyr::select(DB$interaction[rownames(pairLR),],\"interaction_name\")\n if (enriched.only) {\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n if (length(pairLR.name.use) == 0) {\n message(paste0('There is no significant communication of ', signaling))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n }\n geneL <- unique(pairLR$ligand)\n geneR <- unique(pairLR$receptor)\n geneL <- extractGeneSubset(geneL, DB$complex, DB$geneInfo)\n geneR <- extractGeneSubset(geneR, DB$complex, DB$geneInfo)\n geneLR <- c(geneL, geneR)\n return(list(geneLR, pairLR.name.use))\n}\n\n\n#' Compute the maximum value of certain measures in the inferred cell-cell communication networks\n#'\n#' To better control the node size and edge weights of the inferred networks across different datasets,\n#' we compute the maximum number of cells per cell group and the maximum number of interactions (or interaction weights) across all datasets\n#'\n#' @param object.list List of CellChat objects\n#' @param slot.name the slot name of object that is used to compute the maximum value.\n#'\n#' When slot.name = \"idents\", 'attribute' should be \"idents\", which will compute the maximum number of cells per cell group across all datasets\n#'\n#' When slot.name = \"net\", 'attribute' can be either \"count\" or \"weight\", which will compute he maximum number of interactions (or interaction weights) across all datasets\n#'\n#' When slot.name = \"net\" or \"netP\", 'attribute' can be a single pathway name or a ligand-receptor pair name\n#'\n#' @param attribute the attribute to compute the maximum values. `attribute` should have the same length as `slot.name`.\n#'\n#' `attribute` can only be \"count\", \"weight\",\"count.merged\",\"weight.merged\" or a single pathway name or a ligand-receptor pair name\n#'\n#' @return A numeric vector\n#' @export\n#'\ngetMaxWeight <- function(object.list, slot.name = c(\"idents\", \"net\"), attribute = c(\"idents\", \"count\")) {\n weight <- c()\n for (i in 1:length(slot.name)) {\n if (slot.name[i] == \"idents\") {\n weight.all <- sapply(object.list, function (x) {max(as.numeric(table(slot(x, slot.name[i]))))})\n } else if ((slot.name[i] == \"net\") & (attribute[i] %in% c(\"count\", \"weight\",\"count.merged\",\"weight.merged\"))) {\n weight.all <- sapply(object.list, function (x) {max(slot(x, slot.name[i])[[attribute[i]]])})\n } else if (attribute[i] %in% c(object.list[[1]]@DB$interaction$pathway_name, object.list[[1]]@DB$interaction$interaction_name)) {\n weight.all <- sapply(object.list, function (x) {max(slot(x, slot.name[i])$prob[,,attribute[i]])})\n }\n weight[i] <- max(weight.all)\n }\n names(weight) <- attribute\n weight.max <- weight\n return(weight.max)\n}\n\n\n#' Compute the number of interactions/interaction strength between cell types based on their associated cell subpopulations\n#'\n#' @param object CellChat object\n#' @param group.merged a factor defining the group for merging different clusters/subpopulations\n#'\n#' @return An updated slot `net` by adding three elements:\n#'\n#' `count.merged`: the number of interactions between cell types (i.e., merged cell groups)\n#'\n#' `weight.merged`: interaction strength between cell types (i.e., merged cell groups)\n#'\n#' `group.merged` the defined group for merging different clusters/subpopulations\n#'\n#' @export\n#'\nmergeInteractions <- function(object, group.merged) {\n if (!is.factor(group.merged)) {\n group.merged <- factor(group.merged)\n }\n count <- object@net$count\n count.merged <- matrix(0, nrow = nlevels(group.merged), ncol = nlevels(group.merged))\n rownames(count.merged) <- levels(group.merged); colnames(count.merged) <- levels(group.merged);\n weight <- object@net$weight\n weight.merged <- count.merged\n dimnames(weight.merged) <- dimnames(count.merged)\n for (i in levels(group.merged)) {\n for (j in levels(group.merged)) {\n count.merged[i, j] <- sum(count[group.merged == i, group.merged == j])\n weight.merged[i, j] <- sum(weight[group.merged == i, group.merged == j])\n }\n }\n object@net$count.merged <- count.merged\n object@net$weight.merged <- weight.merged\n object@net$group.merged <- group.merged\n return(object)\n}\n\n\n#' Subset the inferred cell-cell communications of interest\n#'\n#' NB: If all arguments are NULL, it returns a data frame consisting of all the inferred cell-cell communications\n#'\n#' @param object CellChat object\n#' @param net Alternative input is a data frame with at least with three columns defining the cell-cell communication network (\"source\",\"target\",\"interaction_name\")\n#' @param slot.name the slot name of object: slot.name = \"net\" when extracting the inferred communications at the level of ligands/receptors; slot.name = \"netP\" when extracting the inferred communications at the level of signaling pathways\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param datasets select the inferred cell-cell communications from a particular `datasets` when inputing a data frame `net`\n#' @param ligand.pvalues,ligand.logFC,ligand.pct.1,ligand.pct.2 set threshold for ligand genes\n#'\n#' ligand.pvalues: threshold for pvalues in the differential expression gene analysis (DEG)\n#'\n#' ligand.logFC: threshold for logFoldChange in the DEG analysis; When ligand.logFC > 0, keep upgulated genes; otherwise, kepp downregulated genes\n#'\n#' ligand.pct.1: threshold for the percent of expressed genes in the defined 'positive' cell group. keep genes with percent greater than ligand.pct.1\n#'\n#' ligand.pct.2: threshold for the percent of expressed genes in the cells except for the defined 'positive' cell group\n#'\n#' @param receptor.pvalues,receptor.logFC,receptor.pct.1,receptor.pct.2 set threshold for receptor genes\n#' @importFrom dplyr select group_by summarize groups\n#' @importFrom stringr str_split\n#' @importFrom BiocGenerics as.data.frame\n#' @importFrom reshape2 melt\n#' @importFrom magrittr %>%\n#'\n#' @return If input object is created from a single dataset, a data frame of the inferred cell-cell communications of interest, consisting of source, target, interaction_name, pathway_name, prob and other information\n#'\n#' If input object is a merged object from multiple datasets, it will return a list and each element is a data frame for one dataset\n#'\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # access all the inferred cell-cell communications\n#' df.net <- subsetCommunication(cellchat)\n#'\n#' # access all the inferred cell-cell communications at the level of signaling pathways\n#' df.net <- subsetCommunication(cellchat, slot.name = \"netP\")\n#'\n#' # Subset to certain cells with sources.use and targets.use\n#' df.net <- subsetCommunication(cellchat, sources.use = c(1,2), targets.use = c(4,5))\n#'\n#' # Subset to certain signaling, e.g., WNT and TGFb\n#' df.net <- subsetCommunication(cellchat, signaling = c(\"WNT\", \"TGFb\"))\n#'}\n#'\nsubsetCommunication <- function(object = NULL, net = NULL, slot.name = \"net\",\n sources.use = NULL, targets.use = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n thresh = 0.05,\n datasets = NULL, ligand.pvalues = NULL, ligand.logFC = NULL, ligand.pct.1 = NULL, ligand.pct.2 = NULL,\n receptor.pvalues = NULL, receptor.logFC = NULL, receptor.pct.1 = NULL, receptor.pct.2 = NULL) {\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n message(\"slot.name is set to be 'netP' when pairLR.use contains signaling pathways\")\n slot.name = \"netP\"\n }\n }\n\n if (!is.null(pairLR.use) & !is.null(signaling)) {\n stop(\"Please do not assign values to 'signaling' when using 'pairLR.use'\")\n }\n\n if (object@options$mode == \"single\") {\n if (is.null(net)) {\n net <- slot(object, \"net\")\n }\n LR <- object@LR$LRsig\n cells.level <- levels(object@idents)\n df.net <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n } else if (object@options$mode == \"merged\") {\n if (is.null(net)) {\n net0 <- slot(object, \"net\")\n df.net <- vector(\"list\", length(net0))\n names(df.net) <- names(net0)\n for (i in 1:length(net0)) {\n net <- net0[[i]]\n LR <- object@LR[[i]]$LRsig\n cells.level <- levels(object@idents[[i]])\n\n df.net[[i]] <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n }\n } else {\n LR <- data.frame()\n for (i in 1:length(object@LR)) {\n LR <- rbind(LR, object@LR[[i]]$LRsig)\n }\n LR <- unique(LR)\n cells.level <- levels(object@idents$joint)\n df.net <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n }\n\n }\n\n return(df.net)\n\n}\n\n#' Subset the inferred cell-cell communications of interest\n#'\n#' NB: If all arguments are NULL, it returns a data frame consisting of all the inferred cell-cell communications\n#'\n#' @param net,LR,cells.level net is object@net or a data frame; LR: object@LR$LRsig; cells.level: levels(object@idents)\n#' @param slot.name the slot name of object: slot.name = \"net\" when extracting the inferred communications at the level of ligands/receptors; slot.name = \"netP\" when extracting the inferred communications at the level of signaling pathways\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param datasets select the inferred cell-cell communications from a particular `datasets` when inputing a data frame `net`\n#' @param ligand.pvalues,ligand.logFC,ligand.pct.1,ligand.pct.2 set threshold for ligand genes\n#'\n#' ligand.pvalues: threshold for pvalues in the differential expression gene analysis (DEG)\n#'\n#' ligand.logFC: threshold for logFoldChange in the DEG analysis; When ligand.logFC > 0, keep upgulated genes; otherwise, kepp downregulated genes\n#'\n#' ligand.pct.1: threshold for the percent of expressed genes in the defined 'positive' cell group. keep genes with percent greater than ligand.pct.1\n#'\n#' ligand.pct.2: threshold for the percent of expressed genes in the cells except for the defined 'positive' cell group\n#'\n#' @param receptor.pvalues,receptor.logFC,receptor.pct.1,receptor.pct.2 set threshold for receptor genes\n#' @importFrom dplyr select group_by summarize groups\n#' @importFrom stringr str_split\n#' @importFrom BiocGenerics as.data.frame\n#' @importFrom reshape2 melt\n#' @importFrom magrittr %>%\n#'\n#' @return A data frame of the inferred cell-cell communications of interest, consisting of source, target, interaction_name, pathway_name, prob and other information\n\nsubsetCommunication_internal <- function(net, LR, cells.level, slot.name = \"net\",\n sources.use = NULL, targets.use = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n thresh = 0.05,\n datasets = NULL, ligand.pvalues = NULL, ligand.logFC = NULL, ligand.pct.1 = NULL, ligand.pct.2 = NULL,\n receptor.pvalues = NULL, receptor.logFC = NULL, receptor.pct.1 = NULL, receptor.pct.2 = NULL) {\n if (!is.data.frame(net)) {\n prob <- net$prob\n pval <- net$pval\n prob[pval >= thresh] <- 0\n net <- reshape2::melt(prob, value.name = \"prob\")\n colnames(net)[1:3] <- c(\"source\",\"target\",\"interaction_name\")\n net.pval <- reshape2::melt(pval, value.name = \"pval\")\n net$pval <- net.pval$pval\n # remove the interactions with zero values\n net <- subset(net, prob > 0)\n }\n if (!(\"ligand\" %in% colnames(net))) {\n col.use <- intersect(c(\"interaction_name_2\", \"pathway_name\", \"ligand\", \"receptor\" ,\"annotation\",\"evidence\"), colnames(LR))\n pairLR <- dplyr::select(LR, col.use)\n idx <- match(net$interaction_name, rownames(pairLR))\n net <- cbind(net, pairLR[idx,])\n }\n\n if (!is.null(signaling)) {\n pairLR.use <- data.frame()\n for (i in 1:length(signaling)) {\n pairLR.use.i <- searchPair(signaling = signaling[i], pairLR.use = LR, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.use <- rbind(pairLR.use, pairLR.use.i)\n }\n }\n\n if (!is.null(pairLR.use)){\n net <- tryCatch({\n subset(net,interaction_name %in% pairLR.use$interaction_name)\n }, error = function(e) {\n subset(net, pathway_name %in% pairLR.use$pathway_name)\n })\n }\n\n if (!is.null(datasets)) {\n if (!(\"datasets\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before selecting 'datasets'\")\n }\n net <- net[net$datasets %in% datasets, , drop = FALSE]\n }\n if (!is.null(ligand.pvalues)){\n if (!(\"ligand.pvalues\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pvalues'\")\n }\n net <- net[net$ligand.pvalues <= ligand.pvalues, , drop = FALSE]\n }\n if (!is.null(ligand.logFC)){\n if (!(\"ligand.logFC\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.logFC'\")\n }\n if (ligand.logFC >= 0) {\n net <- net[net$ligand.logFC >= ligand.logFC, , drop = FALSE]\n } else {\n net <- net[net$ligand.logFC <= ligand.logFC, , drop = FALSE]\n }\n }\n if (!is.null(ligand.pct.1)){\n if (!(\"ligand.pct.1\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pct.1'\")\n }\n net <- net[net$ligand.pct.1 >= ligand.pct.1, , drop = FALSE]\n }\n if (!is.null(ligand.pct.2)){\n if (!(\"ligand.pct.2\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pct.2'\")\n }\n net <- net[net$ligand.pct.2 >= ligand.pct.2, , drop = FALSE]\n }\n\n if (!is.null(receptor.pvalues)){\n if (!(\"receptor.pvalues\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pvalues'\")\n }\n net <- net[net$receptor.pvalues <= receptor.pvalues, , drop = FALSE]\n }\n if (!is.null(receptor.logFC)){\n if (!(\"receptor.logFC\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.logFC'\")\n }\n if (receptor.logFC >= 0) {\n net <- net[net$receptor.logFC >= receptor.logFC, , drop = FALSE]\n } else {\n net <- net[net$receptor.logFC <= receptor.logFC, , drop = FALSE]\n }\n }\n if (!is.null(receptor.pct.1)){\n if (!(\"receptor.pct.1\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pct.1'\")\n }\n net <- net[net$receptor.pct.1 >= receptor.pct.1, , drop = FALSE]\n }\n if (!is.null(receptor.pct.2)){\n if (!(\"receptor.pct.2\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pct.2'\")\n }\n net <- net[net$receptor.pct.2 >= receptor.pct.2, , drop = FALSE]\n }\n\n net <- net[rowSums(is.na(net)) != ncol(net), , drop = FALSE]\n\n if (nrow(net) == 0) {\n stop(\"No significant signaling interactions are inferred based on the input!\")\n }\n\n\n if (slot.name == \"netP\") {\n col.use <- intersect(c(\"source\",\"target\",\"pathway_name\",\"prob\", \"pval\",\"annotation\"), colnames(net))\n net <- dplyr::select(net, col.use)\n net$source_target <- paste(net$source, net$target, sep = \"sourceTotarget\")\n # net$source_target_pathway <- paste(paste(net$source, net$target, sep = \"_\"), net$pathway_name, sep = \"_\")\n net.pval <- net %>% group_by(source_target, pathway_name) %>% summarize(pval = mean(pval), .groups = 'drop')\n net <- net %>% group_by(source_target, pathway_name) %>% summarize(prob = sum(prob), .groups = 'drop')\n a <- stringr::str_split(net$source_target, \"sourceTotarget\", simplify = T)\n net$source <- as.character(a[, 1])\n net$target <- as.character(a[, 2])\n net <- dplyr::select(net, -source_target)\n net$pval <- net.pval$pval\n }\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n }\n\n net <- BiocGenerics::as.data.frame(net, stringsAsFactors=FALSE)\n\n if (nrow(net) == 0) {\n warning(\"No significant signaling interactions are inferred!\")\n } else {\n rownames(net) <- 1:nrow(net)\n }\n\n if (slot.name == \"net\") {\n if ((\"ligand.logFC\" %in% colnames(net)) & (\"datasets\" %in% colnames(net))) {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\",\n \"datasets\",\"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\", \"ligand.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\", \"receptor.pvalues\"), colnames(net))\n net <- net[,col.use]\n } else if (\"ligand.logFC\" %in% colnames(net)) {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\",\n \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\", \"ligand.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\", \"receptor.pvalues\"), colnames(net))\n net <- net[,col.use]\n } else {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\"), colnames(net))\n net <- net[,col.use]\n }\n } else if (slot.name == \"netP\") {\n col.use <- intersect(c(\"source\", \"target\", \"pathway_name\", \"prob\", \"pval\"), colnames(net))\n net <- net[,col.use]\n }\n\n return(net)\n\n}\n\n\n\n\n\n\n\n\n\n\n#' Heatmap showing the centrality scores/importance of cell groups as senders, receivers, mediators and influencers in a single intercellular communication network\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the name of signaling networks\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param measure centrality measures to show\n#' @param measure.name the names of centrality measures to show\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation draw\n#' @importFrom stats setNames\n#'\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_signalingRole_network <- function(object, signaling, slot.name = \"netP\", measure = c(\"outdeg\",\"indeg\",\"flowbet\",\"info\"), measure.name = c(\"Sender\",\"Receiver\",\"Mediator\",\"Influencer\"),\n color.use = NULL, color.heatmap = \"BuGn\",\n width = 6.5, height = 1.4, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE) {\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n centr <- slot(object, slot.name)$centr[signaling]\n for(i in 1:length(centr)) {\n centr0 <- centr[[i]]\n mat <- matrix(unlist(centr0), ncol = length(centr0), byrow = FALSE)\n mat <- t(mat)\n rownames(mat) <- names(centr0); colnames(mat) <- names(centr0$outdeg)\n if (!is.null(measure)) {\n mat <- mat[measure,,drop = FALSE]\n if (!is.null(measure.name)) {\n if (length(measure.name) != length(measure)) {\n stop(\"The length of `measure.name` is not the same as that of `measure`! Please modify it! \\n\")\n }\n rownames(mat) <- measure.name\n }\n }\n mat <- sweep(mat, 1L, apply(mat, 1, max), '/', check.margin = FALSE)\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(colnames(mat)))\n }\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n\n df<- data.frame(group = colnames(mat)); rownames(df) <- colnames(mat)\n cell.cols.assigned <- setNames(color.use, unique(as.character(df$group)))\n col_annotation <- HeatmapAnnotation(df = df, col = list(group = cell.cols.assigned),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = \"Importance\",\n bottom_annotation = col_annotation,\n cluster_rows = cluster.rows,cluster_columns = cluster.cols,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = paste0(names(centr[i]), \" signaling pathway network\"),column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 45,\n heatmap_legend_param = list(title = \"Importance\", title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = c(round(min(mat, na.rm = T), digits = 1), round(max(mat, na.rm = T), digits = 1)),\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n draw(ht1)\n }\n}\n\n\n#' 2D visualization of dominant senders (sources) and receivers (targets)\n#'\n#' @description\n#' This scatter plot shows the dominant senders (sources) and receivers (targets) in a 2D space.\n#' x-axis and y-axis are respectively the total outgoing or incoming communication probability associated with each cell group.\n#' Dot size is proportional to the number of inferred links (both outgoing and incoming) associated with each cell group.\n#' Dot colors indicate different cell groups. Dot shapes indicate different categories of cell groups if `group`` is defined.\n#'\n#' @param object CellChat object\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param color.use defining the color for each cell group\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param group a vector to categorize the cell groups, e.g., categorize the cell groups into two major categories: immune cells and fibroblasts\n#' @param weight.MinMax the Minmum/maximum weight, which is useful to control the dot size when comparing multiple datasets\n#' @param point.shape point shape when group is not NULL\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size a range defining the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_signalingRole_scatter <- function(object, signaling = NULL, color.use = NULL, slot.name = \"netP\", group = NULL, weight.MinMax = NULL, dot.size = c(2, 6), point.shape = c(21, 22, 24, 23, 25, 8, 3), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\",xlabel = \"Outgoing interaction strength\", ylabel = \"Incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n centr <- slot(object, slot.name)$centr\n outgoing <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n incoming <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n dimnames(outgoing) <- list(levels(object@idents), names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n if (is.null(signaling)) {\n message(\"Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\")\n } else {\n message(\"Signaling role analysis on the cell-cell communication network from user's input\")\n signaling <- signaling[signaling %in% object@netP$pathways]\n if (length(signaling) == 0) {\n stop('There is no significant communication for the input signaling. All the significant signaling are shown in `object@netP$pathways`')\n }\n outgoing <- outgoing[ , signaling, drop = FALSE]\n incoming <- incoming[ , signaling, drop = FALSE]\n }\n outgoing.cells <- rowSums(outgoing)\n incoming.cells <- rowSums(incoming)\n\n num.link <- aggregateNet(object, signaling = signaling, return.object = FALSE, remove.isolate = FALSE)$count\n num.link <- rowSums(num.link) + colSums(num.link)-diag(num.link)\n df <- data.frame(x = outgoing.cells, y = incoming.cells, labels = names(incoming.cells),\n Count = num.link)\n df$labels <- factor(df$labels, levels = names(incoming.cells))\n if (!is.null(group)) {\n df$Group <- group\n }\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(object@idents))\n }\n if (!is.null(group)) {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Count, colour = labels, fill = labels, shape = Group))\n } else {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Count, colour = labels, fill = labels))\n }\n\n gg <- gg + CellChat_theme_opts() +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\"))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE) + guides(colour=\"none\")\n # gg <- gg + scale_colour_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(colour=\"none\")\n # gg <- gg + scale_shape_manual(values = point.shape[1:length(prob)])\n if (!is.null(group)) {\n gg <- gg + scale_shape_manual(values = point.shape[1:length(unique(df$Group))])\n }\n if (is.null(weight.MinMax)) {\n gg <- gg + scale_size_continuous(range = dot.size)\n } else {\n gg <- gg + scale_size_continuous(limits = weight.MinMax, range = dot.size)\n }\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = labels), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n\n#' 2D visualization of differential signaling roles (dominant senders (sources) or receivers (targets) ) of each cell group when comparing mutiple datasets\n#'\n#' @description\n#' This scatter plot shows the differential signaling roles (dominant senders (sources) or receivers (targets) in a 2D space.\n#'\n#' x-axis and y-axis are respectively the differential outgoing or incoming communication probability associated with each cell group.\n#' Dot colors indicate different cell groups. Dot shapes indicate different categories of cell groups if `group`` is defined.\n#'\n#' Positive values indicate the increase in the second dataset while negative values indicate the increase in the first dataset\n#'\n#' @param object A merged CellChat object of a list of CellChat objects\n#' @param color.use defining the color for each cell group\n#' @param comparison an index vector giving the two datasets for comparison\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param signaling.exclude signaling pathways to exclude\n#' @param idents.exclude cell groups to exclude. This is useful when zooming into the small changes\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param group a vector to categorize the cell groups, e.g., categorize the cell groups into two major categories: immune cells and fibroblasts\n#' @param point.shape point shape when group is not NULL\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., Outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., Incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_diff_signalingRole_scatter <- function(object, color.use = NULL, comparison = c(1,2), signaling = NULL, signaling.exclude = NULL, idents.exclude = NULL, slot.name = \"netP\", group = NULL, dot.size = 2.5, point.shape = c(21, 22, 24, 23, 25, 8, 3), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\", xlabel = \"Outgoing interaction strength\", ylabel = \"Incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (is.list(object)) {\n object <- mergeCellChat(object, add.names = names(object))\n }\n if (!is.list(object@net[[1]])) {\n stop(\"This function cannot be applied to a single cellchat object from one dataset!\")\n }\n\n dataset.name <- names(object@net)\n message(paste0(\"Visualizing differential outgoing and incoming signaling changes from \", dataset.name[comparison[1]], \" to \", dataset.name[comparison[2]]))\n title <- paste0(\"Signaling changes \", \" (\", dataset.name[comparison[1]], \" vs. \", dataset.name[comparison[2]], \")\")\n\n cell.levels <- levels(object@idents$joint)\n if (is.null(xlabel) | is.null(ylabel)) {\n xlabel = \"Differential outgoing interaction strength\"\n ylabel = \"Differential incoming interaction strength\"\n }\n if (is.null(signaling)) {\n signaling <- union(object@netP[[comparison[1]]]$pathways, object@netP[[comparison[2]]]$pathways)\n }\n if (!is.null(signaling.exclude)) {\n signaling <- setdiff(signaling, signaling.exclude)\n }\n\n mat.all.merged <- list()\n for (ii in 1:length(comparison)) {\n if (length(slot(object, slot.name)[[comparison[ii]]]$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores for each dataset seperately! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n\n centr <- slot(object, slot.name)[[comparison[ii]]]$centr\n outgoing <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n incoming <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n dimnames(outgoing) <- list(cell.levels, names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n mat.out <- t(outgoing)\n mat.in <- t(incoming)\n\n mat.all <- array(0, dim = c(length(signaling),ncol(mat.out),2))\n mat.t <-list(mat.out, mat.in)\n for (i in 1:length(comparison)) {\n mat = mat.t[[i]]\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n mat.all[,,i] = mat\n }\n dimnames(mat.all) <- list(dimnames(mat)[[1]], dimnames(mat)[[2]], c(\"outgoing\", \"incoming\"))\n mat.all.merged[[ii]] <- mat.all\n\n }\n\n mat.diff <- mat.all.merged[[2]] - mat.all.merged[[1]]\n\n outgoing.diff <- colSums(mat.diff[ , , 1])\n incoming.diff <- colSums(mat.diff[ , , 2])\n\n\n df <- data.frame(x = outgoing.diff, y = incoming.diff, labels = names(incoming.diff))\n df$labels <- factor(df$labels, levels = names(incoming.diff))\n if (!is.null(group)) {\n df$Group <- group\n }\n if (is.null(color.use)) {\n color.use <- scPalette(length(cell.levels))\n }\n if (!is.null(idents.exclude)) {\n df <- df[!(df$labels %in% idents.exclude), ]\n color.use <- color.use[!(cell.levels %in% idents.exclude)]\n df$labels = droplevels(df$labels, exclude = setdiff(levels(df$labels),unique(df$labels)))\n }\n\n if (!is.null(group)) {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = labels, fill = labels, shape = Group), size = dot.size)\n } else {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = labels, fill = labels), size = dot.size)\n }\n\n gg <- gg + CellChat_theme_opts() + theme_linedraw() +theme(panel.grid = element_blank()) +\n geom_hline(yintercept=0,linetype=\"dashed\", color = \"grey50\", size = 0.25) + geom_vline(xintercept=0, linetype=\"dashed\", color = \"grey50\",size = 0.25) +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\", hjust = 0.5))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE) + guides(colour=\"none\")\n if (!is.null(group)) {\n gg <- gg + scale_shape_manual(values = point.shape[1:length(unique(df$Group))])\n }\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = labels), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n\n#' 2D visualization of differential outgoing and incoming signaling associated with one cell group\n#'\n#' @description\n#' Positive values indicate the increase in the second dataset while negative values indicate the increase in the first dataset\n#'\n#'\n#' @param object A merged CellChat object of a list of CellChat objects\n#' @param idents.use the cell group names of interest. Should be one of `levels(object@idents$joint)`\n#' @param color.use a vector with three elements: the first is for coloring shared pathways, the second is for specific pathways in the first dataset, and the third is for specific pathways in the second dataset\n#' @param comparison an index vector giving the two datasets for comparison\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param signaling.label a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param signaling.exclude signaling pathways to exclude when plotting\n#' @param xlims,ylims set x-Axis and y-Axis Limits for zoom into the plot. e.g., xlims = c(-0.05, 0.1), ylims = c(-0.01, 0.035)\n#' @param slot.name the slot name of object\n#' @param point.shape point shape\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., Outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., Incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @importFrom plyr mapvalues\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_signalingChanges_scatter <- function(object, idents.use, color.use = c(\"grey10\", \"#F8766D\", \"#00BFC4\"), comparison = c(1,2), signaling = NULL, signaling.label = NULL, top.label = 1, signaling.exclude = NULL, xlims = NULL, ylims = NULL,slot.name = \"netP\", dot.size = 2.5, point.shape = c(21, 22, 24, 23), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\", xlabel = \"Differential outgoing interaction strength\", ylabel = \"Differential incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (is.list(object)) {\n object <- mergeCellChat(object, add.names = names(object))\n }\n if (is.list(object@net[[1]])) {\n dataset.name <- names(object@net)\n message(paste0(\"Visualizing differential outgoing and incoming signaling changes from \", dataset.name[comparison[1]], \" to \", dataset.name[comparison[2]]))\n title <- paste0(\"Signaling changes of \", idents.use, \" (\", dataset.name[comparison[1]], \" vs. \", dataset.name[comparison[2]], \")\")\n\n cell.levels <- levels(object@idents$joint)\n if (is.null(xlabel) | is.null(ylabel)) {\n xlabel = \"Differential outgoing interaction strength\"\n ylabel = \"Differential incoming interaction strength\"\n }\n\n } else {\n message(\"Visualizing outgoing and incoming signaling on a single object \\n\")\n title <- paste0(\"Signaling patterns of \", idents.use)\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n cell.levels <- levels(object@idents)\n }\n if (!(idents.use %in% cell.levels)) {\n stop(\"Please check the input cell group names!\")\n }\n if (is.null(signaling)) {\n signaling <- union(object@netP[[comparison[1]]]$pathways, object@netP[[comparison[2]]]$pathways)\n }\n if (!is.null(signaling.exclude)) {\n signaling <- setdiff(signaling, signaling.exclude)\n }\n mat.all.merged <- list()\n for (ii in 1:length(comparison)) {\n if (length(slot(object, slot.name)[[comparison[ii]]]$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores for each dataset seperately! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n centr <- slot(object, slot.name)[[comparison[ii]]]$centr\n outgoing <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n incoming <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n dimnames(outgoing) <- list(cell.levels, names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n mat.out <- t(outgoing)\n mat.in <- t(incoming)\n\n mat.all <- array(0, dim = c(length(signaling),ncol(mat.out),2))\n mat.t <-list(mat.out, mat.in)\n for (i in 1:length(comparison)) {\n mat = mat.t[[i]]\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n mat.all[,,i] = mat\n }\n dimnames(mat.all) <- list(dimnames(mat)[[1]], dimnames(mat)[[2]], c(\"outgoing\", \"incoming\"))\n mat.all.merged[[ii]] <- mat.all\n }\n mat.all.merged.use <- list(mat.all.merged[[1]][,idents.use,], mat.all.merged[[2]][,idents.use,])\n idx.specific <- mat.all.merged.use[[1]] * mat.all.merged.use[[2]]\n mat.sum <- mat.all.merged.use[[2]] + mat.all.merged.use[[1]]\n out.specific.signaling <- rownames(idx.specific)[(mat.sum[,1] != 0) & (idx.specific[,1] == 0)]\n in.specific.signaling <- rownames(idx.specific)[(mat.sum[,2] != 0) & (idx.specific[,2] == 0)]\n\n mat.diff <- mat.all.merged.use[[2]] - mat.all.merged.use[[1]]\n idx <- rowSums(mat.diff) != 0\n mat.diff <- mat.diff[idx, ]\n out.specific.signaling <- rownames(mat.diff) %in% out.specific.signaling\n in.specific.signaling <- rownames(mat.diff) %in% in.specific.signaling\n out.in.specific.signaling <- as.logical(out.specific.signaling * in.specific.signaling)\n specificity.out.in <- matrix(0, nrow = nrow(mat.diff), ncol = 1)\n specificity.out.in[out.in.specific.signaling] <- 2 # both outgoing and incoming specific to one condition\n specificity.out.in[setdiff(which(out.specific.signaling), which(out.in.specific.signaling))] <- 1 # only outgoing specific to one condition\n specificity.out.in[setdiff(which(in.specific.signaling), which(out.in.specific.signaling))] <- -1 # only incoming specific to one condition\n\n\n df <- as.data.frame(mat.diff)\n df$specificity.out.in <- specificity.out.in\n df$specificity = 0\n df$specificity[(specificity.out.in != 0) & (rowSums(mat.diff >= 0) ==2)] = 1 # specific to dataset 2\n df$specificity[(specificity.out.in != 0) & (rowSums(mat.diff <= 0) ==2)] = -1 # specific to dataset 1\n\n # change number to char\n out.in.category <- c(\"Shared\", \"Incoming specific\", \"Outgoing specific\", \"Incoming & Outgoing specific\")\n specificity.category <- c(\"Shared\", paste0(dataset.name[comparison[1]],\" specific\"), paste0(dataset.name[comparison[2]],\" specific\"))\n df$specificity.out.in <- plyr::mapvalues(df$specificity.out.in, from = c(0,-1,1,2),to = out.in.category)\n df$specificity.out.in <- factor(df$specificity.out.in, levels = out.in.category)\n df$specificity <- plyr::mapvalues(df$specificity, from = c(0,-1,1),to = specificity.category)\n df$specificity <- factor(df$specificity, levels = specificity.category)\n\n point.shape.use <- point.shape[out.in.category %in% unique(df$specificity.out.in)]\n df$specificity.out.in = droplevels(df$specificity.out.in, exclude = setdiff(out.in.category,unique(df$specificity.out.in)))\n\n color.use <- color.use[specificity.category %in% unique(df$specificity)]\n df$specificity = droplevels(df$specificity, exclude = setdiff(specificity.category,unique(df$specificity)))\n\n df$labels <- rownames(df)\n gg <- ggplot(data = df, aes(outgoing, incoming)) +\n geom_point(aes(colour = specificity, fill = specificity, shape = specificity.out.in), size = dot.size)\n gg <- gg + theme_linedraw() +theme(panel.grid = element_blank()) +\n geom_hline(yintercept=0,linetype=\"dashed\", color = \"grey50\", size = 0.25) + geom_vline(xintercept=0, linetype=\"dashed\", color = \"grey50\",size = 0.25) +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, hjust = 0.5, face=\"plain\"))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n gg <- gg + scale_shape_manual(values = point.shape.use)\n gg <- gg + theme(legend.title = element_blank())\n if (!is.null(xlims)) {\n gg <- gg + xlim(xlims)\n }\n if (!is.null(ylims)) {\n gg <- gg + ylim(ylims)\n }\n\n if (do.label) {\n if (is.null(signaling.label)) {\n thresh <- stats::quantile(abs(as.matrix(df[,1:2])), probs = 1-top.label)\n idx = abs(df[,1]) > thresh | abs(df[,2]) > thresh\n data.label <- df[idx,]\n } else {\n data.label <- df[rownames(df) %in% signaling.label, ]\n }\n\n gg <- gg + ggrepel::geom_text_repel(data = data.label, mapping = aes(label = labels, colour = specificity), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n#' Heatmap showing the contribution of signals (signaling pathways or ligand-receptor pairs) to cell groups in terms of outgoing or incoming signaling\n#'\n#' In this heatmap, colobar represents the relative signaling strength of a signaling pathway across cell groups (NB: values are row-scaled).\n#' The top colored bar plot shows the total signaling strength of a cell group by summarizing all signaling pathways displayed in the heatmap.\n#' The right grey bar plot shows the total signaling strength of a signaling pathway by summarizing all cell groups displayed in the heatmap.\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the names of signaling networks of interest\n#' @param pattern this parameter can be set as \"outgoing\", \"incoming\" or \"all\". When pattern = \"all\", CellChat aggregates the outgoing and incoming signaling strength together;\n#' @param slot.name the slot name of object that is used to examine the signaling patterns at the level of signaling pathways (slot.name = \"netP\") or ligand-receptor pairs (slot.name = \"net\");\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param title title name\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation anno_barplot rowAnnotation\n#' @importFrom stats setNames\n#'\n#' @return\n#' @export\n#'\nnetAnalysis_signalingRole_heatmap <- function(object, signaling = NULL, pattern = c(\"outgoing\", \"incoming\",\"all\"), slot.name = \"netP\",\n color.use = NULL, color.heatmap = \"BuGn\",\n title = NULL, width = 10, height = 8, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE){\n pattern <- match.arg(pattern)\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n centr <- slot(object, slot.name)$centr\n outgoing <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n incoming <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n dimnames(outgoing) <- list(levels(object@idents), names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]]$outdeg\n incoming[,i] <- centr[[i]]$indeg\n }\n if (pattern == \"outgoing\") {\n mat <- t(outgoing)\n legend.name <- \"Outgoing\"\n } else if (pattern == \"incoming\") {\n mat <- t(incoming)\n legend.name <- \"Incoming\"\n } else if (pattern == \"all\") {\n mat <- t(outgoing+ incoming)\n legend.name <- \"Overall\"\n }\n if (is.null(title)) {\n title <- paste0(legend.name, \" signaling patterns\")\n } else {\n title <- paste0(paste0(legend.name, \" signaling patterns\"), \" - \",title)\n }\n\n if (!is.null(signaling)) {\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n }\n mat.ori <- mat\n mat <- sweep(mat, 1L, apply(mat, 1, max), '/', check.margin = FALSE)\n mat[mat == 0] <- NA\n\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(colnames(mat)))\n }\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n\n df<- data.frame(group = colnames(mat)); rownames(df) <- colnames(mat)\n names(color.use) <- colnames(mat)\n col_annotation <- HeatmapAnnotation(df = df, col = list(group = color.use),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n ha2 = HeatmapAnnotation(Strength = anno_barplot(colSums(mat.ori), border = FALSE,gp = gpar(fill = color.use, col=color.use)), show_annotation_name = FALSE)\n\n pSum <- rowSums(mat.ori)\n pSum.original <- pSum\n pSum <- -1/log(pSum)\n pSum[is.na(pSum)] <- 0\n idx1 <- which(is.infinite(pSum) | pSum < 0)\n if (length(idx1) > 0) {\n values.assign <- seq(max(pSum)*1.1, max(pSum)*1.5, length.out = length(idx1))\n position <- sort(pSum.original[idx1], index.return = TRUE)$ix\n pSum[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n\n ha1 = rowAnnotation(Strength = anno_barplot(pSum, border = FALSE), show_annotation_name = FALSE)\n\n if (min(mat, na.rm = T) == max(mat, na.rm = T)) {\n legend.break <- max(mat, na.rm = T)\n } else {\n legend.break <- c(round(min(mat, na.rm = T), digits = 1), round(max(mat, na.rm = T), digits = 1))\n }\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = \"Relative strength\",\n bottom_annotation = col_annotation, top_annotation = ha2, right_annotation = ha1,\n cluster_rows = cluster.rows,cluster_columns = cluster.rows,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = title,column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 90,\n heatmap_legend_param = list(title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = legend.break,\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n # draw(ht1)\n return(ht1)\n}\n\n\n\n#' Mapping the differential expressed genes (DEG) information onto the inferred cell-cell communications\n#'\n#' This function returns a data frame consisting of all the inferred cell-cell communications with mapped DEG information\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for extracting the DEG in `object@var.features[[features.name]]`\n#' @param variable.all variable.all = TRUE will compute the c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\") for a ligand/receptor complex using the mean value of its all subunits, that is requiring all subunits of the complex are differential expressed;\n#' variable.all = FALSE will compute the minimum value of \"pvalues\" and maximum value of c(\"logFC\", \"pct.1\", \"pct.2\") among the subunits, that is only requiring that any one of the subunits of the complex is differential expressed.\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom dplyr select\n#'\n#' @return a data frame of the inferred cell-cell communications, consisting of source, target, interaction_name, pathway_name, prob and other CellChatDB information as well as DEG information\n#'\n#' @export\n#'\nnetMappingDEG <- function(object, features.name, variable.all = TRUE, thresh = 0.05) {\n features.name <- paste0(features.name, \".info\")\n if (!(features.name %in% names(object@var.features))) {\n stop(\"The input features.name does not exist in `names(object@var.features)`. Please first run `identifyOverExpressedGenes`! \")\n }\n DEG <- object@var.features[[features.name]]\n geneInfo <- object@DB$geneInfo\n complex_input <- object@DB$complex\n\n df.net <- subsetCommunication(object, thresh = thresh)\n if (!is.data.frame(df.net)) {\n net <- data.frame()\n for (ii in 1:length(df.net)) {\n df.net[[ii]]$datasets <- names(df.net)[ii]\n net <- rbind(net, df.net[[ii]])\n }\n } else {\n net <- df.net\n }\n net$source.ligand <- paste0(net$source,\".\", net$ligand)\n net$target.receptor <- paste0(net$target,\".\", net$receptor)\n\n DEG$clusters.features <- paste0(DEG$clusters,\".\", DEG$features)\n\n net <- cbind(net, data.frame(ligand.pvalues = NA, ligand.logFC = NA, ligand.pct.1 = NA, ligand.pct.2 = NA,\n receptor.pvalues = NA, receptor.logFC = NA, receptor.pct.1 = NA, receptor.pct.2 = NA))\n # compute values for ligand\n idx1.ligand <- net$ligand %in% geneInfo$Symbol\n idx2.ligand <- which((net$ligand %in% geneInfo$Symbol) == \"FALSE\")\n idx.pos <- match(net$source.ligand, DEG$clusters.features)\n idx1.source.ligand <- which(!is.na(idx.pos))\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n idx2.source.ligand <- which(idx1.ligand & !(net$source.ligand %in% DEG$clusters.features))\n net[idx1.source.ligand, c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")] <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n\n if (length(idx2.ligand) > 0) {\n net.temp.all <- data.frame()\n for (i in 1:length(idx2.ligand)) {\n complex <- net$ligand[idx2.ligand[i]]\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n\n source.ligand.complex <- paste0(net$source[idx2.ligand[i]],\".\", complexsubunitsV)\n idx.pos <- match(source.ligand.complex, DEG$clusters.features)\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n if (length(idx1.clusters.features) > 0) {\n net.temp <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\"), drop = FALSE]\n if (variable.all == TRUE) {\n net.temp <- colMeans(net.temp, na.rm = TRUE)\n } else {\n net.temp <- c(min(net.temp$pvalues), apply(net.temp[, 2:ncol(net.temp), drop = FALSE], 2, function(x) max(x, na.rm = TRUE)))\n names(net.temp)[1] <- \"pvalues\"\n }\n net.temp <- as.data.frame(t(net.temp))\n colnames(net.temp) <- c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")\n } else {\n net.temp <- data.frame(ligand.pvalues = NA, ligand.logFC = NA, ligand.pct.1 = NA, ligand.pct.2 = NA)\n }\n net.temp.all <- rbind(net.temp.all, net.temp)\n }\n net[idx2.ligand, c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")] <- net.temp.all\n }\n\n # compute values for receptor\n idx1.receptor <- net$receptor %in% geneInfo$Symbol\n idx2.receptor <- which((net$receptor %in% geneInfo$Symbol) == \"FALSE\")\n idx.pos <- match(net$target.receptor, DEG$clusters.features)\n idx1.target.receptor <- which(!is.na(idx.pos))\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n net[idx1.target.receptor, c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")] <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n\n if (length(idx2.receptor) > 0) {\n net.temp.all <- data.frame()\n for (i in 1:length(idx2.receptor)) {\n complex <- net$receptor[idx2.receptor[i]]\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n\n target.receptor.complex <- paste0(net$target[idx2.receptor[i]],\".\", complexsubunitsV)\n idx.pos <- match(target.receptor.complex, DEG$clusters.features)\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n if (length(idx1.clusters.features) > 0) {\n net.temp <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n if (variable.all == TRUE) {\n net.temp <- colMeans(net.temp, na.rm = TRUE)\n } else {\n net.temp <- c(min(net.temp$pvalues, na.rm = TRUE), apply(net.temp[, 2:ncol(net.temp), drop = FALSE], 2, function(x) max(x, na.rm = TRUE)))\n names(net.temp)[1] <- \"pvalues\"\n }\n net.temp <- as.data.frame(t(net.temp))\n colnames(net.temp) <- c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")\n } else {\n net.temp <- data.frame(receptor.pvalues = NA, receptor.logFC = NA, receptor.pct.1 = NA, receptor.pct.2 = NA)\n }\n net.temp.all <- rbind(net.temp.all, net.temp)\n }\n net[idx2.receptor, c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")] <- net.temp.all\n }\n # net <- dplyr::select[net, -c(\"source.ligand\", \"target.receptor\")]\n return(net)\n}\n\n\n#' Compute and visualize the enrichment score of ligand-receptor pairs in one condition compared to another condition\n#'\n#' @param df a dataframe\n#' @param measure compute the enrichment score in terms of \"ligand\", \"signaling\",or \"LR-pair\"\n#' @param color.use defining the color for each group of datasets\n#' @param color.name the color names in RColorBrewer::brewer.pal\n#' @param n.color the number of colors\n#' @param species define the species as one of the c('mouse','human') to extract the CellChatDB; For other species, users need to provide a ligand-receptor database `db`\n#' @param db a customized ligand-receptor database `db`\n#' @param variable.both variable.both = TRUE will require that both ligand and receptor from one pair are over-expressed;\n#' variable.both = FALSE will only require that either ligand or receptor from one pair is over-expressed.\n#' @param scale A vector of length 2 indicating the range of the size of the words.\n#' @param min.freq words with frequency below min.freq will not be plotted\n#' @param max.words Maximum number of words to be plotted. least frequent terms dropped\n#' @param random.order plot words in random order. If false, they will be plotted in decreasing frequency\n#' @param rot.per \tproportion words with 90 degree rotation\n#' @param return.data whether return the data frame for plotting wordcloud\n#' @param seed set a seed\n#' @param ... Other parameters passing to wordcloud::wordcloud\n#' @import dplyr\n#' @return A ggplot object\n#' @export\n#'\ncomputeEnrichmentScore <- function(df, measure = c(\"ligand\", \"signaling\",\"LR-pair\"), variable.both = TRUE, species = c('mouse','human'), db = NULL, color.use = NULL, color.name = \"Dark2\", n.color = 8,\n scale=c(4,.8), min.freq = 0, max.words = 200, random.order = FALSE, rot.per = 0,return.data = FALSE,seed = 1,...) {\n measure <- match.arg(measure)\n species <- match.arg(species)\n LRpairs <- as.character(unique(df$interaction_name))\n ES <- vector(length = length(LRpairs))\n for (i in 1:length(LRpairs)) {\n df.i <- subset(df, interaction_name == LRpairs[i])\n idx = which(rowSums(is.na(df.i)) > 0)\n if (variable.both & (length(idx) > 0)) {\n df.i <- df.i[-idx, ,drop = FALSE]\n }\n ES[i] = mean(abs(df.i$ligand.logFC) * abs(df.i$receptor.logFC) *abs(df.i$ligand.pct.2-df.i$ligand.pct.1)*abs(df.i$receptor.pct.2-df.i$receptor.pct.1), na.rm = TRUE)\n }\n idx.na <- which(is.na(ES))\n if (length(idx.na) > 0) {\n ES <- ES[-idx.na]\n LRpairs <- LRpairs[-idx.na]\n }\n\n if (length(ES) == 0) {\n stop(\"No enriched signaling! Please adjust the parameters for selecting differential expressed signaling!\")\n }\n if (is.null(db)) {\n if (species == \"mouse\") {\n CellChatDB <- CellChatDB.mouse\n } else if (species == 'human') {\n CellChatDB <- CellChatDB.human\n } else {\n stop(\"Only mouse and human are supported currently. Please provide a `db` instead! \")\n }\n } else {\n CellChatDB <- db\n }\n df.es <- CellChatDB$interaction[LRpairs, c(\"ligand\",'receptor','pathway_name')]\n df.es$score <- ES\n # summarize the enrichment score\n df.es.ensemble <- df.es %>% group_by(ligand) %>% summarize(total = sum(score)) # avg = mean(score),\n\n set.seed(seed)\n if (is.null(color.use)) {\n color.use <- RColorBrewer::brewer.pal(n.color, color.name)\n }\n\n wordcloud::wordcloud(words = df.es.ensemble$ligand, freq = df.es.ensemble$total, min.freq = min.freq, max.words = max.words,scale=scale,\n random.order = random.order, rot.per = rot.per, colors = color.use,...)\n if (return.data) {\n return(df.es.ensemble)\n }\n}\n\n\n#' Find the enriched signaling according to the genes (e.g.DEGs) and cell groups of interest\n#'\n#' @param object CellChat object\n#' @param features a vector giving the genes of interest\n#' @param idents a vector giving the names of cell groups of interest. If idents = NULL, it returns signaling according to the input features.\n#' @param pattern \"both\", \"outgoing\" or \"incoming\"\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @return a dataframe of the cell-cell communication associated with the input features.\n#' @export\n#' @examples\n#'\\dontrun{\n#' # find all the significant outgoing signaling according to the features and cell groups of interest\n#' df <- findEnrichedSignaling(object, features = c(\"CCL19\", \"CXCL12\"), idents = c(\"Inflam. FIB\", \"COL11A1+ FIB\"), pattern =\"outgoing\")\n#'}\nfindEnrichedSignaling <- function(object, features, idents = NULL, pattern = c(\"both\",\"outgoing\",\"incoming\"), thresh = 0.05) {\n pattern <- match.arg(pattern)\n df.net <- subsetCommunication(object, thresh = thresh)\n if (!is.null(idents)) {\n if (pattern == \"both\") {\n idx <- (df.net$source %in% idents) | (df.net$target %in% idents)\n } else if (pattern == \"outgoing\") {\n idx <- df.net$source %in% idents\n } else if (pattern == \"incoming\"){\n idx <- df.net$target %in% idents\n }\n idx.feature <- (df.net$ligand %in% features) | (df.net$receptor %in% features)\n df.net.sub <- df.net[idx & idx.feature, , drop = FALSE]\n } else {\n if (pattern == \"both\") {\n idx.feature <- (df.net$ligand %in% features) | (df.net$receptor %in% features)\n } else if (pattern == \"outgoing\") {\n idx.feature <- (df.net$ligand %in% features)\n } else if (pattern == \"incoming\"){\n idx.feature <- (df.net$receptor %in% features)\n }\n df.net.sub <- df.net[idx.feature, , drop = FALSE]\n }\n return(df.net.sub)\n}\n\n"], ["/CellChat/R/utilities.R", "#' Normalize data using a scaling factor\n#'\n#' @param data.raw input raw data\n#' @param scale.factor the scaling factor used for each cell\n#' @param do.log whether to do log transformation with pseudocount 1\n#' @param do.sparse whether to use sparse format\n#' @export\n#'\nnormalizeData <- function(data.raw, scale.factor = 10000, do.log = TRUE, do.sparse = TRUE) {\n # Scale counts within a sample\n library.size <- Matrix::colSums(data.raw)\n #scale.factor <- median(library.size)\n expr <- Matrix::t(Matrix::t(data.raw) / library.size) * scale.factor\n if (do.log) {\n data.norm <-log1p(expr)\n }\n if (do.sparse) {\n data.input <- as(data.norm, \"dgCMatrix\")\n }\n return(data.norm)\n}\n\n\n#' Scale the data\n#'\n#' @param data.use input data\n#' @param do.center whether center the values\n#' @export\n#'\nscaleData <- function(data.use, do.center = T) {\n data.use <- Matrix::t(scale(Matrix::t(data.use), center = do.center, scale = TRUE))\n return(data.use)\n}\n\n\n#' Scale a data matrix\n#'\n#' @param x data matrix\n#' @param scale the method to scale the data\n#' @param na.rm whether remove na\n#' @importFrom Matrix rowMeans colMeans rowSums colSums\n#' @return\n#' @export\n#'\n#' @examples\nscaleMat <- function(x, scale, na.rm=TRUE){\n\n av <- c(\"none\", \"row\", \"column\", 'r1', 'c1')\n i <- pmatch(scale, av)\n if(is.na(i) )\n stop(\"scale argument shoud take values: 'none', 'row' or 'column'\")\n scale <- av[i]\n\n switch(scale, none = x\n , row = {\n x <- sweep(x, 1L, rowMeans(x, na.rm = na.rm), '-',check.margin = FALSE)\n sx <- apply(x, 1L, sd, na.rm = na.rm)\n sweep(x, 1L, sx, \"/\", check.margin = FALSE)\n }\n , column = {\n x <- sweep(x, 2L, colMeans(x, na.rm = na.rm), '-',check.margin = FALSE)\n sx <- apply(x, 2L, sd, na.rm = na.rm)\n sweep(x, 2L, sx, \"/\", check.margin = FALSE)\n }\n , r1 = sweep(x, 1L, rowSums(x, na.rm = na.rm), '/', check.margin = FALSE)\n , c1 = sweep(x, 2L, colSums(x, na.rm = na.rm), '/', check.margin = FALSE)\n )\n}\n\n#' Downsampling single cell data using geometric sketching algorithm\n#'\n#' USERs need to install the python package `pip install geosketch` (https://github.com/brianhie/geosketch)\n#'\n#' @param object A data matrix (should have row names; samples in rows, features in columns) or a Seurat object.\n#'\n#' When object is a PCA or UMAP space, please set `do.PCA = FALSE`\n#'\n#' When object is a data matrix (cells in rows and genes in columns), it is better to use the highly variable genes. PCA will be done on this input data matrix.\n#' @param percent the percent of data to sketch\n#' @param idents A vector of identity classes to keep for sketching\n#' @param do.PCA whether doing PCA on the input data\n#' @param dimPC the number of components to use\n#' @importFrom reticulate import\n#' @return A vector of cell names to use for downsampling\n#' @export\n#'\nsketchData <- function(object, percent, idents = NULL, do.PCA = TRUE, dimPC = 30) {\n # pip install geosketch\n geosketch <- reticulate::import('geosketch')\n if (is(object,\"Seurat\")) {\n sketch.size <- as.integer(percent*ncol(object))\n if (!is.null(idents)) {\n object <- subset(object, idents = idents)\n }\n object <- object %>% #Seurat::NormalizeData(verbose = FALSE) %>%\n FindVariableFeatures(selection.method = \"vst\", nfeatures = 2000) %>%\n RunPCA(pc.genes = object@var.genes, npcs = dimPC, verbose = FALSE)\n\n X.pcs <- object@reductions$pca@cell.embeddings\n cells.all <- Cells(object)\n\n } else {\n # Get top PCs\n if (do.PCA) {\n X.pcs <- runPCA(object, dimPC = dimPC)\n } else {\n X.pcs <- object\n }\n\n # Sketch percent of data.\n sketch.size <- as.integer(percent*nrow(X))\n cells.all <- rownames(object)\n }\n sketch.index <- geosketch$gs(X.pcs, sketch.size)\n sketch.index <- unlist(sketch.index) + 1\n sketch.cells <- cells.all[sketch.index]\n return(sketch.cells)\n}\n\n\n#' Add the cell information into meta slot\n#'\n#' @param object CellChat object\n#' @param meta cell information to be added\n#' @param meta.name the name of column to be assigned\n#'\n#' @return\n#' @export\n#'\n#' @examples\naddMeta <- function(object, meta, meta.name = NULL) {\n if (is.null(x = meta.name) && is.atomic(x = meta)) {\n stop(\"'meta.name' must be provided for atomic meta types (eg. vectors)\")\n }\n if (inherits(x = meta, what = c(\"matrix\", \"Matrix\"))) {\n meta <- as.data.frame(x = meta)\n }\n\n if (is.null(x = meta.name)) {\n meta.name <- names(meta)\n } else {\n names(meta) <- meta.name\n }\n object@meta <- meta\n return(object)\n}\n\n\n#' Set the default identity of cells\n#' @param object CellChat object\n#' @param ident.use the name of the variable in object.meta;\n#' @param levels set the levels of factor\n#' @param display.warning whether display the warning message\n#' @return\n#' @export\n#'\n#' @examples\nsetIdent <- function(object, ident.use = NULL, levels = NULL, display.warning = TRUE){\n if (!is.null(ident.use)) {\n object@idents <- as.factor(object@meta[[ident.use]])\n }\n\n if (!is.null(levels)) {\n object@idents <- factor(object@idents, levels = levels)\n }\n if (\"0\" %in% as.character(object@idents)) {\n stop(\"Cell labels cannot contain `0`! \")\n }\n if (length(object@net) > 0) {\n if (all(dimnames(object@net$prob)[[1]] %in% levels(object@idents) )) {\n message(\"Reorder cell groups! \")\n cat(\"The cell group order before reordering is \", dimnames(object@net$prob)[[1]],'\\n')\n # idx <- match(dimnames(object@net$prob)[[1]], levels(object@idents))\n idx <- match(levels(object@idents), dimnames(object@net$prob)[[1]])\n object@net$prob <- object@net$prob[idx, , ]\n object@net$prob <- object@net$prob[, idx, ]\n object@net$pval <- object@net$pval[idx, , ]\n object@net$pval <- object@net$pval[, idx, ]\n cat(\"The cell group order after reordering is \", dimnames(object@net$prob)[[1]],'\\n')\n } else {\n message(\"Rename cell groups but do not change the order! \")\n cat(\"The cell group order before renaming is \", dimnames(object@net$prob)[[1]],'\\n')\n dimnames(object@net$prob) <- list(levels(object@idents), levels(object@idents), dimnames(object@net$prob)[[3]])\n dimnames(object@net$pval) <- dimnames(object@net$prob)\n cat(\"The cell group order after renaming is \", dimnames(object@net$prob)[[1]],'\\n')\n }\n if (display.warning) {\n warning(\"All the calculations after `computeCommunProb` should be re-run!!\n These include but not limited to `computeCommunProbPathway`,`aggregateNet`, and `netAnalysis_computeCentrality`.\")\n }\n\n\n }\n return(object)\n}\n\n\n#' Add a reduced space of the data into CellChat object\n#'\n#' @param object CellChat object from a single dataset\n#' @param dr A data frame (rows are cells with rownames) consisting of a low-dimensional space for visualization\n#' @param dr.name A char name of the reduction method for the input `dr`\n#' @param seu.obj A Seurat object with the reduced space of the data\n#' @param dr.use A char name of the reduction method to use when taking `seu.obj` as input. By default, all reduced space in `seu.obj` will be added in `object@dr`\n#' @param force.add Whether to force to add a new reduced space when a reduced space exists in `object@dr`\n#' @return\n#' @export\n#' @examples\n#' \\dontrun{\n#' cellChat <- addReduction(object = cellchat, dr = cell.embeddings, dr.name = \"umap\")\n#'\n#' cellChat <- addReduction(object = cellchat, seu.obj = seu.obj)\n#' }\naddReduction <- function(object, dr = NULL, dr.name = NULL, seu.obj = NULL, dr.use = NULL, force.add = FALSE) {\n if (length(names(object@dr)) > 0) {\n if (!force.add) {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please set `force.add = TRUE` if intending to add a new reduced space. \\n\"))\n }\n }\n if (!is.null(dr)) {\n if (is.null(dr.name)) {\n stop(\"When inputing `dr`, please also provide the `dr.name`! \\n\")\n }\n dr <- as.data.frame(dr)\n if (all(colnames(object@data.signaling) %in% rownames(dr))) {\n object@dr[[dr.name]] <- dr[colnames(object@data.signaling), ]\n } else {\n stop(\"Some cell barcodes in the CellChat object are not the rownames of the input `dr`. Please check the input `dr` and make sure it contains all cells in the CellChat analysis. \\n\")\n }\n } else if(!is.null(seu.obj)) {\n if (!is(seu.obj,\"Seurat\")) {\n stop(\"The input `seu.obj` can be only the Seurat object. \\n\")\n }\n reductions <- names(seu.obj@reductions)\n if (length(reductions) == 0) {\n stop(\"The input `seu.obj` does not contain any low-dimensional space. Please generate a low-dimensional space for visualization. \\n\")\n }\n if (!is.null(dr.use)) {\n reductions <- intersect(reductions, dr.use)\n }\n if (length(reductions) == 0) {\n stop(\"The input `dr.use` is not in the reduced space in `seu.obj`. \\n\")\n }\n for (i in 1:length(reductions)) {\n dr.name <- reductions[i]\n dr = seu.obj@reductions[[dr.name]]@cell.embeddings\n if (all(colnames(object@data.signaling) %in% rownames(dr))) {\n cat(paste0(dr.name, \" is now added in `object@dr` as a low-dimensional space. \\n\"))\n object@dr[[dr.name]] <- dr[colnames(object@data.signaling), ]\n } else {\n stop(\"Some cell barcodes in the CellChat object are not in the input `seu.obj`. Please check the input `seu.obj` and make sure it contains all cells in the CellChat analysis. \\n\")\n }\n }\n } else {\n stop(\"Please input either `dr` or `seu.obj`! \\n\")\n }\n return(object)\n}\n\n\n#' Update and re-order the cell group names after running `computeCommunProb`\n#'\n#' @param object CellChat object\n#' @param old.cluster.name A vector defining old cell group labels in `object@idents`; Default = NULL, which will use `levels(object@idents)`\n#' @param new.cluster.name A vector defining new cell group labels to rename\n#' @param new.order reset order of cell group labels\n#' @param new.cluster.metaname assign a name of the new labels, which will be the column name of new labels in `object@meta`\n#' @return An updated CellChat object\n#' @export\n#'\nupdateClusterLabels <- function(object, old.cluster.name = NULL, new.cluster.name = NULL, new.order = NULL, new.cluster.metaname = \"new.labels\") {\n if (is.null(old.cluster.name)) {\n old.cluster.name <- levels(object@idents)\n }\n if (new.cluster.metaname %in% colnames(object@meta)) {\n stop(\"Please define another `new.cluster.metaname` as it exists in `colnames(object@meta)`!\")\n }\n if (!is.null(new.cluster.name)) {\n labels.new <- plyr::mapvalues(object@idents, from = old.cluster.name, to = new.cluster.name)\n object@meta[[new.cluster.metaname]] <- labels.new\n object <- setIdent(object, ident.use = new.cluster.metaname, display.warning = FALSE)\n } else {\n new.cluster.metaname <- NULL\n cat(\"Only reorder cell groups but do not rename cell groups!\")\n }\n\n if (!is.null(new.order)) {\n object <- setIdent(object, ident.use = new.cluster.metaname, levels = new.order, display.warning = FALSE)\n }\n message(\"We now re-run computeCommunProbPathway`,`aggregateNet`, and `netAnalysis_computeCentrality`...\")\n object <- computeCommunProbPathway(object)\n ## calculate the aggregated network by counting the number of links or summarizing the communication probability\n object <- aggregateNet(object)\n # network importance analysis\n object <-netAnalysis_computeCentrality(object, slot.name = \"netP\")\n return(object)\n}\n\n\n\n\n\n#' Subset the expression data of signaling genes for saving computation cost\n#'\n#' @param object CellChat object\n#' @param features default = NULL: subset the expression data of signaling genes in CellChatDB.use\n#'\n#' @return An updated CellChat object by assigning a subset of the data into the slot `data.signaling`\n#' @export\n#'\nsubsetData <- function(object, features = NULL) {\n interaction_input <- object@DB$interaction\n if (object@options$datatype != \"RNA\") {\n if (\"annotation\" %in% colnames(interaction_input) == FALSE) {\n warning(\"A column named `annotation` is required in `object@DB$interaction` when running CellChat on spatial transcriptomics! The `annotation` column is now automatically added and all L-R pairs are assigned as `Secreted Signaling`, which means that these L-R pairs are assumed to mediate diffusion-based cellular communication.\")\n interaction_input$annotation <- \"Secreted Signaling\"\n }\n }\n if (\"annotation\" %in% colnames(interaction_input) == TRUE) {\n if (length(unique(interaction_input$annotation)) > 1) {\n interaction_input$annotation <- factor(interaction_input$annotation, levels = c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\", \"Cell-Cell Contact\"))\n interaction_input <- interaction_input[order(interaction_input$annotation), , drop = FALSE]\n interaction_input$annotation <- as.character(interaction_input$annotation)\n }\n object@DB$interaction <- interaction_input\n }\n\n if (is.null(features)) {\n DB <- object@DB\n gene.use_input <- extractGene(DB)\n gene.use <- intersect(gene.use_input, rownames(object@data))\n } else {\n gene.use <- intersect(features, rownames(object@data))\n }\n object@data.signaling <- object@data[rownames(object@data) %in% gene.use, ]\n return(object)\n}\n\n\n\n#' Identify over-expressed signaling genes associated with each cell group\n#'\n#' USERS can use customized gene set as over-expressed signaling genes by setting `object@var.features[[features.name]] <- features.sig`\n#' The Bonferroni corrected/adjusted p value can be obtained via `object@var.features[[paste0(features.name, \".info\")]]`. Note that by default `features.name = \"features\"`\n#'\n#' @param object CellChat object\n#' @param data.use a customed data matrix. Default: data.use = NULL and the expression matrix in the slot 'data.signaling' is used\n#' @param group.by cell group information; default is `object@idents`; otherwise it should be one of the column names of the meta slot\n#' @param idents.use a subset of cell groups used for analysis\n#' @param invert whether to invert the idents.use\n#' @param group.dataset dataset origin information in a merged CellChat object; set it as one of the column names of meta slot when identifying the highly enriched genes in one dataset for each cell group\n#' @param pos.dataset the dataset name used for identifying highly enriched genes in this dataset for each cell group\n#' @param group.DE.combined Whether to perform differential expression between conditions by ignoring cell group information. By default, group.DE.combined = FALSE, which will perform differential expression analysis between two biological conditions for each cell group;\n#' When group.DE.combined = TRUE, it will perform DE analysis by combining all cell groups together.\n#'\n#' @param features.name a char name used for storing the over-expressed signaling genes in `object@var.features[[features.name]]`\n#' @param only.pos Only return positive markers\n#' @param features features used for identifying Over Expressed genes. default use all features\n#' @param return.object whether to return the object; otherwise return a data frame consisting of over-expressed signaling genes associated with each cell group\n#' @param thresh.pc Threshold of the fraction of cells expressed in one cluster, i.e., thresh.pc = 0.1\n#' @param thresh.fc Threshold of Log Fold Change, i.e., thresh.pc = 0.1\n#' @param thresh.p Threshold of p-values, i.e., thresh.pc = 0.05\n#' @param do.DE Whether to perform differential expression analysis. By default do.DE = TRUE; When do.DE = FALSE, selecting over-expressed genes that are expressed in more than `min.cells` cells.\n#' @param do.fast If do.fast = TRUE, then perform a ultra-fast Wilcoxon test using presto package; otherwise using stats package. These two methods produce different logFC values, and the presto::wilcoxauc method gives smaller values.\n#' @param min.cells the minmum number of expressed cells required for the genes that are considered for cell-cell communication analysis\n#' @importFrom future nbrOfWorkers\n#' @importFrom pbapply pbsapply\n#' @importFrom future.apply future_sapply\n#' @importFrom stats sd wilcox.test p.adjust\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, two new elements named 'features.name' and paste0(features.name, \".info\") will be added into the list `object@var.features`\n#' `object@var.features[[features.name]]` is a vector consisting of the identified over-expressed signaling genes;\n#' `object@var.features[[paste0(features.name, \".info\")]]` is a data frame returned from the differential expression analysis\n#' @export\n#'\nidentifyOverExpressedGenes <- function(object, data.use = NULL, group.by = NULL, idents.use = NULL, invert = FALSE,\n group.dataset = NULL, pos.dataset = NULL, group.DE.combined = FALSE,\n features.name = \"features\", only.pos = TRUE, features = NULL, return.object = TRUE,\n thresh.pc = 0, thresh.fc = 0, thresh.p = 0.05, do.DE = TRUE, do.fast = TRUE, min.cells = 10) {\n if (!is.list(object@var.features)) {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n if (is.null(data.use)) {\n X <- object@data.signaling\n if (nrow(X) < 3) {stop(\"Please check `object@data.signaling` and ensure that you have run `subsetData` and that the data matrix `object@data.signaling` looks OK.\")}\n } else {\n X <- data.use\n }\n\n if (is.null(features)) {\n features.use <- row.names(X)\n } else {\n features.use <- intersect(features, row.names(X))\n }\n data.use <- X[features.use,]\n\n if (do.DE) {\n # select genes based on differential expression\n data.use <- as.matrix(data.use)\n\n if (is.null(group.by)) {\n labels <- object@idents\n if (!is.factor(labels)) {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n level.use <- levels(labels)[levels(labels) %in% unique(labels)]\n if (!is.null(idents.use)) {\n if (invert) {\n level.use <- level.use[!(level.use %in% idents.use)]\n } else {\n level.use <- level.use[level.use %in% idents.use]\n }\n }\n numCluster <- length(level.use)\n\n if (!is.null(group.dataset)) {\n labels.dataset <- as.character(object@meta[[group.dataset]])\n if (!(pos.dataset %in% unique(labels.dataset))) {\n cat(\"Please set pos.dataset to be one of the following dataset names: \", unique(as.character(labels.dataset)))\n stop()\n }\n labels.dataset[labels.dataset != pos.dataset] <- toString(setdiff(unique(labels.dataset), pos.dataset))\n labels.dataset <- factor(labels.dataset, levels = c(pos.dataset, setdiff(unique(labels.dataset), pos.dataset)))\n }\n\n if (do.fast) {\n presto.check <- rlang::is_installed(c(\"presto\"))\n if (!presto.check) {\n stop(\n \"For a faster implementation of the Wilcoxon Test, please install the presto package\",\n \"\\n--------------------------------------------\",\n \"\\n devtools::install_github('immunogenomics/presto')\",\n \"\\n--------------------------------------------\",\n \"\\n Otherwise, plase set `do.fast = FALSE` for running the standard Wilcoxon Test!\\n\"\n )\n }\n if (is.null(group.dataset)) {\n genes.de <- presto::wilcoxauc(data.use, labels, groups_use = level.use)\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"clusters\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100) %>% arrange(pvalues)\n\n } else if ((!is.null(group.dataset)) & (group.DE.combined == FALSE)) {\n genes.de <- data.frame()\n for (i in 1:numCluster) {\n idx <- which(labels == level.use[i])\n data.use.i <- data.use[ ,idx]\n labels.i <- labels.dataset[idx]\n genes.de.i <- presto::wilcoxauc(data.use.i, labels.i)\n # genes.de.i <- genes.de.i[1:(nrow(genes.de.i)/2),]\n genes.de.i$clusters <- level.use[i]\n genes.de <- rbind(genes.de, genes.de.i)\n }\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"datasets\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100)\n markers.all$datasets <- factor(markers.all$datasets, levels = levels(labels.dataset))\n markers.all <- markers.all[order(markers.all$datasets, markers.all$pvalues, -markers.all$logFC), ]\n } else if ((!is.null(group.dataset)) & (group.DE.combined == TRUE)) {\n genes.de.c <- presto::wilcoxauc(data.use, labels.dataset)\n genes.de.c <- genes.de.c[1:(nrow(genes.de.c)/2),]\n genes.de <- data.frame()\n for (i in 1:numCluster) {\n genes.de.c$clusters <- level.use[i]\n genes.de <- rbind(genes.de, genes.de.c)\n }\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"datasets\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100) %>% arrange(pvalues)\n\n }\n markers.all <- dplyr::select(markers.all, -c(\"logFC_abs\",\"statistic\",\"pct.max\"))\n\n if (only.pos & nrow(markers.all) > 0) {\n markers.all <- subset(markers.all, subset = logFC > 0)\n }\n markers.all$features <- as.character(markers.all$features)\n\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- unique(features.sig)\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n\n } else {\n\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n\n mean.fxn <- function(x) {\n return(log(x = mean(x = expm1(x = x)) + 1))\n }\n labels <- as.character(labels)\n genes.de <- vector(\"list\", length = numCluster)\n for (i in 1:numCluster) {\n features <- features.use\n if (is.null(group.dataset)) {\n cell.use1 <- which(labels == level.use[i])\n cell.use2 <- base::setdiff(1:length(labels), cell.use1)\n } else if ((!is.null(group.dataset)) & (group.DE.combined == FALSE)) {\n cell.use1 <- which((labels == level.use[i]) & (labels.dataset == pos.dataset))\n cell.use2 <- which((labels == level.use[i]) & (labels.dataset != pos.dataset))\n } else if ((!is.null(group.dataset)) & (group.DE.combined == TRUE)) {\n cell.use1 <- which(labels.dataset == pos.dataset)\n cell.use2 <- which(labels.dataset != pos.dataset)\n }\n\n # feature selection (based on percentages)\n thresh.min <- 0\n pct.1 <- round(\n x = rowSums(data.use[features, cell.use1, drop = FALSE] > thresh.min) /\n length(x = cell.use1),\n digits = 3\n )\n pct.2 <- round(\n x = rowSums(data.use[features, cell.use2, drop = FALSE] > thresh.min) /\n length(x = cell.use2),\n digits = 3\n )\n data.alpha <- cbind(pct.1, pct.2)\n colnames(x = data.alpha) <- c(\"pct.1\", \"pct.2\")\n alpha.min <- apply(X = data.alpha, MARGIN = 1, FUN = max)\n names(x = alpha.min) <- rownames(x = data.alpha)\n features <- names(x = which(x = alpha.min > thresh.pc))\n if (length(x = features) == 0) {\n #stop(\"No features pass thresh.pc threshold\")\n next\n }\n\n # feature selection (based on average difference)\n data.1 <- apply(X = data.use[features, cell.use1, drop = FALSE],MARGIN = 1,FUN = mean.fxn)\n data.2 <- apply(X = data.use[features, cell.use2, drop = FALSE],MARGIN = 1,FUN = mean.fxn)\n FC <- (data.1 - data.2)\n if (only.pos) {\n features.diff <- names(which(FC > thresh.fc))\n } else {\n features.diff <- names(which(abs(FC) > thresh.fc))\n }\n\n features <- intersect(x = features, y = features.diff)\n if (length(x = features) == 0) {\n # stop(\"No features pass thresh.fc threshold\")\n next\n }\n\n data1 <- data.use[features, cell.use1, drop = FALSE]\n data2 <- data.use[features, cell.use2, drop = FALSE]\n\n pvalues <- unlist(\n x = my.sapply(\n X = 1:nrow(x = data1),\n FUN = function(x) {\n # return(wilcox.test(data1[x, ], data2[x, ], alternative = \"greater\")$p.value)\n return(wilcox.test(data1[x, ], data2[x, ])$p.value)\n }\n )\n )\n\n pval.adj = stats::p.adjust(\n p = pvalues,\n method = \"bonferroni\",\n n = nrow(X)\n )\n genes.de[[i]] <- data.frame(clusters = level.use[i], features = as.character(rownames(data1)), pvalues = pvalues, logFC = FC[features], data.alpha[features,, drop = F],pvalues.adj = pval.adj, stringsAsFactors = FALSE)\n }\n\n markers.all <- data.frame()\n for (i in 1:numCluster) {\n gde <- genes.de[[i]]\n if (!is.null(gde)) {\n gde <- gde[order(gde$pvalues, -gde$logFC), ]\n gde <- subset(gde, subset = pvalues < thresh.p)\n if (nrow(gde) > 0) {\n markers.all <- rbind(markers.all, gde)\n }\n }\n }\n if (only.pos & nrow(markers.all) > 0) {\n markers.all <- subset(markers.all, subset = logFC > 0)\n }\n if (!is.null(group.dataset)) {\n markers.all$datasets[markers.all$logFC > 0] <- pos.dataset\n markers.all$datasets[markers.all$logFC < 0] <- setdiff(unique(labels.dataset), pos.dataset)\n markers.all$datasets <- factor(markers.all$datasets, levels = levels(labels.dataset))\n markers.all <- markers.all[order(markers.all$datasets, markers.all$pvalues, -markers.all$logFC), ]\n }\n markers.all$features <- as.character(markers.all$features)\n\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- features.sig\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n }\n\n } else {\n # select genes if they are exprssed in at least `min.cells` cells\n markers.all <- data.frame(features = as.character(rownames(data.use)), nCells = rowSums(data.use > 0))\n markers.all <- dplyr::filter(markers.all, nCells >= min.cells)\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- unique(features.sig)\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n }\n\n\n if (return.object) {\n return(object)\n } else {\n return(markers.all)\n }\n}\n\n\n#' Identify over-expressed ligands and (complex) receptors associated with each cell group\n#'\n#' This function identifies the over-expressed ligands and (complex) receptors based on the identified signaling genes from 'identifyOverExpressedGenes'.\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for storing the over-expressed ligands and receptors in `object@var.features[[paste0(features.name, \".LR\")]]`\n#' @param features a vector of features to use. default use all over-expressed genes in `object@var.features[[features.name]]`\n#' @param return.object whether returning a CellChat object. If FALSE, it will return a data frame containing over-expressed ligands and (complex) receptors associated with each cell group\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom dplyr select\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, a new element named paste0(features.name, \".LR\") will be added into the list `object@var.features`\n#' @export\n#'\nidentifyOverExpressedLigandReceptor <- function(object, features.name = \"features\", features = NULL, return.object = TRUE) {\n\n features.name.LR <- paste0(features.name, \".LR\")\n features.name <- paste0(features.name, \".info\")\n DB <- object@DB\n interaction_input <- DB$interaction\n complex_input <- DB$complex\n pairLR <- select(interaction_input, ligand, receptor)\n LR.use <- unique(c(pairLR$ligand, pairLR$receptor))\n if (is.null(features)) {\n if (is.list(object@var.features)) {\n markers.all <- object@var.features[[features.name]] # use the updated CellChat object 12/2020\n } else {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n\n } else {\n features.use <- features\n rm(features)\n markers.all <- subset(markers.all, subset = features %in% features.use)\n }\n\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n complexSubunits <- complex_input[, grepl(\"subunit\" , colnames(complex_input))]\n\n markers.all.new <- data.frame()\n for (i in 1:nrow(markers.all)) {\n if (markers.all$features[i] %in% LR.use) {\n markers.all.new <- rbind(markers.all.new, markers.all[i, , drop = FALSE])\n } else {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (markers.all$features[i] %in% complexsubunitsV) {\n return(x)\n }\n }\n )\n )\n complexSubunits.sig <- rownames(complexSubunits[index.sig,])\n markers.all.complex <- data.frame()\n for (j in 1:length(complexSubunits.sig)) {\n markers.all.complex <- rbind(markers.all.complex, markers.all[i, , drop = FALSE])\n }\n markers.all.complex$features <- complexSubunits.sig\n markers.all.new <- rbind(markers.all.new, markers.all.complex)\n }\n }\n\n object@var.features[[features.name.LR]] <- markers.all.new\n\n if (return.object) {\n return(object)\n } else {\n return(markers.all.new)\n }\n}\n\n\n\n#' Identify over-expressed ligand-receptor interactions (pairs) within the used CellChatDB\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for assess the results in `object@var.features[[features.name]]`\n#' @param features a vector of features to use. default use all over-expressed genes in `object@var.features[[features.name]]`\n#' @param variable.both variable.both = TRUE will require that both ligand and receptor from one pair are over-expressed;\n#'\n#' variable.both = FALSE will only require that either ligand or receptor from one pair is over-expressed, leading to more over-expressed ligand-receptor interactions (pairs) for further analysis.\n#' @param return.object whether returning a CellChat object. If FALSE, it will return a data frame containing the over-expressed ligand-receptor pairs\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom dplyr select\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, a new element named 'LRsig' will be added into the list `object@LR`\n#' @export\n#'\nidentifyOverExpressedInteractions <- function(object, features.name = \"features\", variable.both = TRUE, features = NULL, return.object = TRUE) {\n gene.use <- row.names(object@data.signaling)\n DB <- object@DB\n if (is.null(features)) {\n if (is.list(object@var.features)) {\n features.sig <- object@var.features[[features.name]] # use the updated CellChat object 12/2020\n } else {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n\n } else {\n features.sig <- features\n }\n\n interaction_input <- DB$interaction\n complex_input <- DB$complex\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n complexSubunits <- complex_input[, grepl(\"subunit\" , colnames(complex_input))]\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (length(intersect(complexsubunitsV, features.sig)) > 0 & all(complexsubunitsV %in% gene.use)) {\n return(x)\n }\n }\n )\n )\n complexSubunits.sig <- complexSubunits[index.sig,]\n\n index.use <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (all(complexsubunitsV %in% gene.use)) {\n return(x)\n }\n }\n )\n )\n complexSubunits.use <- complexSubunits[index.use,]\n\n pairLR <- select(interaction_input, ligand, receptor)\n\n if (variable.both) {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(pairLR),\n FUN = function(x) {\n if (all(unlist(pairLR[x,], use.names = F) %in% c(features.sig, rownames(complexSubunits.sig)))) {\n return(x)\n }\n }\n )\n )\n } else {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(pairLR),\n FUN = function(x) {\n # if (all(unlist(pairLR[x,], use.names = F) %in% c(features.sig, rownames(complexSubunits.sig)))) {\n if (all(unlist(pairLR[x,], use.names = F) %in% c(gene.use, rownames(complexSubunits.use))) & (length(intersect(unlist(pairLR[x,], use.names = F), c(features.sig, rownames(complexSubunits.sig)))) > 0)) {\n return(x)\n }\n }\n )\n )\n }\n\n pairLRsig <- interaction_input[index.sig, ]\n object@LR$LRsig <- pairLRsig\n cat(\"The number of highly variable ligand-receptor pairs used for signaling inference is\", nrow(pairLRsig), '\\n')\n if (return.object) {\n return(object)\n } else {\n return(pairLRsig)\n }\n}\n\n\n#' Smooth the gene expression data\n#'\n#' A diffusion process is used to smooth genes’ expression values based on their neighbors’ defined in a high-confidence experimentally validated protein-protein network.\n#'\n#' This function is useful when analyzing single-cell data with shallow sequencing depth because the projection reduces the dropout effects of signaling genes, in particular for possible zero expression of subunits of ligands/receptors\n#'\n#' @param object CellChat object\n#' @param method When method = \"netSmooth\", smoothing a gene’s expression values based on its neighbors defined in a high-confidence experimentally validated protein-protein network.\n#' @param adj adjacency matrix of protein-protein interaction network to use\n#' @param alpha numeric in [0,1] alpha = 0: no smoothing; a larger value alpha results in increasing levels of smoothing.\n#' @param normalizeAdjMatrix how to normalize the adjacency matrix\n#' possible values are 'rows' (in-degree)\n#' and 'columns' (out-degree)\n#' @return a smoothed gene expression matrix\n#' @export\n#'\n# This function is adapted from https://github.com/BIMSBbioinfo/netSmooth\nsmoothData <- function(object, method = c(\"netSmooth\"), adj = NULL, alpha=0.5, normalizeAdjMatrix=c('rows','columns')){\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n stop(\"`object@data.smooth` is missing. Please update the CellChat object via `updateCellChat`! \\n\")\n }\n data <- as.matrix(object@data.signaling)\n normalizeAdjMatrix <- match.arg(normalizeAdjMatrix)\n if (method == \"netSmooth\") {\n if (is.null(adj)) stop(\"Please provide the `adj`. \\n\")\n stopifnot(is(adj, 'matrix') | is(adj, 'sparseMatrix'))\n stopifnot((is.numeric(alpha) & (alpha > 0 & alpha < 1)))\n if(sum(Matrix::rowSums(adj)==0)>0) stop(\"PPI cannot have zero rows/columns\")\n if(sum(Matrix::colSums(adj)==0)>0) stop(\"PPI cannot have zero rows/columns\")\n }\n if(is.numeric(alpha)) {\n if(alpha<0 | alpha > 1) {\n stop('alpha must be between 0 and 1')\n }\n data.projected <- projectAndRecombine(data, adj, alpha,normalizeAdjMatrix=normalizeAdjMatrix)\n } else stop(\"unsupported alpha value: \", class(alpha))\n object@data.smooth <- data.projected\n return(object)\n}\n\n#' Perform network projecting on network when the network genes and the\n#' experiment genes aren't exactly the same.\n#'\n#' The gene network might be defined only on a subset of genes that are\n#' measured in any experiment. Further, an experiment might not measure all\n#' genes that are present in the network. This function projects the experiment\n#' data onto the gene space defined by the network prior to projecting. Then,\n#' it projects the projected data back into the original dimansions.\n#'\n#' @param gene_expression gene expession data to be projected\n#' [N_genes x M_samples]\n#' @param adj_matrix adjacenty matrix of network to perform projecting over.\n#' Will be column-normalized.\n#' Rownames and colnames should be genes.\n#' @param alpha network projecting parameter (1 - restart probability in random\n#' walk model.\n#' @param projecting.function must be a function that takes in data, adjacency\n#' matrix, and alpha. Will be used to perform the\n#' actual projecting.\n#' @param normalizeAdjMatrix which dimension (rows or columns) should the\n#' adjacency matrix be normalized by. rows\n#' corresponds to in-degree, columns to\n#' out-degree.\n#' @return matrix with network-projected gene expression data. Genes that are\n#' not present in projecting network will retain original values.\n#' @keywords internal\n#'\nprojectAndRecombine <- function(gene_expression, adj_matrix, alpha,\n projecting.function=randomWalkBySolve,\n normalizeAdjMatrix=c('rows','columns')) {\n normalizeAdjMatrix <- match.arg(normalizeAdjMatrix)\n gene_expression_in_A_space <- projectOnNetwork(gene_expression,rownames(adj_matrix))\n gene_expression_in_A_space_project <- projecting.function(gene_expression_in_A_space, adj_matrix, alpha, normalizeAdjMatrix)\n gene_expression_project <- projectFromNetworkRecombine(gene_expression, gene_expression_in_A_space_project)\n return(gene_expression_project)\n}\n\n\n#' Project the gene expression matrix onto a lower space\n#' of the genes defined in the projecting network\n#' @param gene_expression gene expression matrix\n#' @param new_features the genes in the network, on which to project\n#' the gene expression matrix\n#' @param missing.value value to assign to genes that are in network,\n#' but missing from gene expression matrix\n#' @return the gene expression matrix projected onto the gene space defined by new_features\n#' @keywords internal\nprojectOnNetwork <- function(gene_expression, new_features, missing.value=0) {\n # data_in_new_space = matrix(rep(0, length(new_features)*dim(gene_expression)[2]),nrow=length(new_features))\n data_in_new_space = matrix(0, ncol=dim(gene_expression)[2], nrow=length(new_features))\n rownames(data_in_new_space) <- new_features\n colnames(data_in_new_space) <- colnames(gene_expression)\n genes_in_both <- intersect(rownames(data_in_new_space),rownames(gene_expression))\n data_in_new_space[genes_in_both,] <- gene_expression[genes_in_both,]\n genes_only_in_network <- setdiff(new_features, rownames(gene_expression))\n data_in_new_space[genes_only_in_network,] <- missing.value\n return(data_in_new_space)\n}\n\n#' project data on graph by solving the linear equation (I - alpha*A) * E_sm = E * (1-alpha)\n\n#' @param E initial data matrix [NxM]\n#' @param A adjacency matrix of graph to network project on will be column-normalized.\n#' @param alpha projecting coefficient (1 - restart probability of random walk)\n#' @return network-projected gene expression\n#' @keywords internal\nrandomWalkBySolve <- function(E, A, alpha, normalizeAjdMatrix=c('rows','columns')) {\n normalizeAjdMatrix <- match.arg(normalizeAjdMatrix)\n if (normalizeAjdMatrix=='rows') {\n Anorm <- l1NormalizeRows(A)\n } else if (normalizeAjdMatrix=='columns') {\n Anorm <- l1NormalizeColumns(A)\n }\n eye <- diag(dim(A)[1])\n AA <- eye - alpha*Anorm\n BB <- (1-alpha) * E\n return(solve(AA, BB))\n}\n\n#' Column-normalize a sparse, symmetric matrix (using the l1 norm) so that each\n#' column sums to 1.\n#'\n#' @param A matrix\n#' @usage l1NormalizeColumns(A)\n#' @return column-normalized sparse matrix object\n#' @keywords internal\nl1NormalizeColumns <- function(A) {\n return(Matrix::t(Matrix::t(A)/Matrix::colSums(A)))\n}\n\n#' Row-normalize a sparse, symmetric matrix (using the l1 norm) so that each\n#' row sums to 1.\n#'\n#' @param A matrix\n#' @usage l1NormalizeRows(A)\n#' @return row-normalized sparse matrix object\n#' @keywords internal\nl1NormalizeRows <- function(A) {\n return(A/Matrix::rowSums(A))\n}\n\n#' Combine gene expression from projected space (that of the network) with the\n#' expression of genes that were not projected (not present in network)\n#' @keywords internal\n#' @param original_expression the non-projected expression\n#' @param projected_expression the projected gene expression, in the space\n#' of the genes defined by the network\n#' @return a matrix in the dimensions of original_expression, where values that\n#' are present in projected_expression are copied from there.\nprojectFromNetworkRecombine <- function(original_expression, projected_expression) {\n data_in_original_space <- original_expression\n genes_in_both <- intersect(rownames(original_expression),rownames(projected_expression))\n data_in_original_space[genes_in_both,] <- as.matrix(projected_expression[genes_in_both,])\n return(data_in_original_space)\n}\n\n\n#' Dimension reduction using PCA\n#'\n#' @param data.use input data (samples in rows, features in columns)\n#' @param do.fast whether do fast PCA\n#' @param dimPC the number of components to keep\n#' @param seed.use set a seed\n#' @param weight.by.var whether use weighted pc.scores\n#' @importFrom stats prcomp\n#' @importFrom irlba irlba\n#' @return\n#' @export\n#'\n#' @examples\nrunPCA <- function(data.use, do.fast = T, dimPC = 50, seed.use = 42, weight.by.var = T) {\n set.seed(seed = seed.use)\n if (do.fast) {\n dimPC <- min(dimPC, ncol(data.use) - 1)\n pca.res <- irlba::irlba(data.use, nv = dimPC)\n sdev <- pca.res$d/sqrt(max(1, nrow(data.use) - 1))\n if (weight.by.var){\n pc.scores <- pca.res$u %*% diag(pca.res$d)\n } else {\n pc.scores <- pca.res$u\n }\n } else {\n dimPC <- min(dimPC, ncol(data.use) - 1)\n pca.res <- stats::prcomp(x = data.use, rank. = dimPC)\n sdev <- pca.res$sdev\n if (weight.by.var) {\n pc.scores <- pca.res$x %*% diag(pca.res$sdev[1:dimPC]^2)\n } else {\n pc.scores <- pca.res$x\n }\n }\n rownames(pc.scores) <- rownames(data.use)\n colnames(pc.scores) <- paste0('PC', 1:ncol(pc.scores))\n return(pc.scores)\n}\n\n\n#' Run UMAP\n#' @param data.use input data matrix\n#' @param n_neighbors This determines the number of neighboring points used in\n#' local approximations of manifold structure. Larger values will result in more\n#' global structure being preserved at the loss of detailed local structure. In general this parameter should often be in the range 5 to 50.\n#' @param n_components The dimension of the space to embed into.\n#' @param metric This determines the choice of metric used to measure distance in the input space.\n#' @param n_epochs the number of training epochs to be used in optimizing the low dimensional embedding. Larger values result in more accurate embeddings. If NULL is specified, a value will be selected based on the size of the input dataset (200 for large datasets, 500 for small).\n#' @param learning_rate The initial learning rate for the embedding optimization.\n#' @param min_dist This controls how tightly the embedding is allowed compress points together.\n#' Larger values ensure embedded points are moreevenly distributed, while smaller values allow the\n#' algorithm to optimise more accurately with regard to local structure. Sensible values are in the range 0.001 to 0.5.\n#' @param spread he effective scale of embedded points. In combination with min.dist this determines how clustered/clumped the embedded points are.\n#' @param set_op_mix_ratio Interpolate between (fuzzy) union and intersection as the set operation used to combine local fuzzy simplicial sets to obtain a global fuzzy simplicial sets.\n#' @param local_connectivity The local connectivity required - i.e. the number of nearest neighbors\n#' that should be assumed to be connected at a local level. The higher this value the more connected\n#' the manifold becomes locally. In practice this should be not more than the local intrinsic dimension of the manifold.\n#' @param repulsion_strength Weighting applied to negative samples in low dimensional embedding\n#' optimization. Values higher than one will result in greater weight being given to negative samples.\n#' @param negative_sample_rate The number of negative samples to select per positive sample in the\n#' optimization process. Increasing this value will result in greater repulsive force being applied, greater optimization cost, but slightly more accuracy.\n#' @param a More specific parameters controlling the embedding. If NULL, these values are set automatically as determined by min. dist and spread.\n#' @param b More specific parameters controlling the embedding. If NULL, these values are set automatically as determined by min. dist and spread.\n#' @param seed.use Set a random seed. By default, sets the seed to 42.\n#' @param metric_kwds,angular_rp_forest,verbose other parameters used in UMAP\n#' @import reticulate\n#' @export\n#'\nrunUMAP <- function(\n data.use,\n n_neighbors = 30L,\n n_components = 2L,\n metric = \"correlation\",\n n_epochs = NULL,\n learning_rate = 1.0,\n min_dist = 0.3,\n spread = 1.0,\n set_op_mix_ratio = 1.0,\n local_connectivity = 1L,\n repulsion_strength = 1,\n negative_sample_rate = 5,\n a = NULL,\n b = NULL,\n seed.use = 42L,\n metric_kwds = NULL,\n angular_rp_forest = FALSE,\n verbose = FALSE){\n if (!reticulate::py_module_available(module = 'umap')) {\n stop(\"Cannot find UMAP, please install through pip (e.g. pip install umap-learn or reticulate::py_install(packages = 'umap-learn')).\")\n }\n set.seed(seed.use)\n reticulate::py_set_seed(seed.use)\n umap_import <- reticulate::import(module = \"umap\", delay_load = TRUE)\n umap <- umap_import$UMAP(\n n_neighbors = as.integer(n_neighbors),\n n_components = as.integer(n_components),\n metric = metric,\n n_epochs = n_epochs,\n learning_rate = learning_rate,\n min_dist = min_dist,\n spread = spread,\n set_op_mix_ratio = set_op_mix_ratio,\n local_connectivity = local_connectivity,\n repulsion_strength = repulsion_strength,\n negative_sample_rate = negative_sample_rate,\n a = a,\n b = b,\n metric_kwds = metric_kwds,\n angular_rp_forest = angular_rp_forest,\n verbose = verbose\n )\n Rumap <- umap$fit_transform\n umap_output <- Rumap(t(data.use))\n colnames(umap_output) <- paste0('UMAP', 1:ncol(umap_output))\n rownames(umap_output) <- colnames(data.use)\n return(umap_output)\n}\n\n.error_if_no_Seurat <- function() {\n if (!requireNamespace(\"Seurat\", quietly = TRUE)) {\n stop(\"Seurat installation required for working with Seurat objects\")\n }\n}\n\n\n#' Color interpolation\n#'\n#' This function is modified from https://rdrr.io/cran/circlize/src/R/utils.R\n#' Colors are linearly interpolated according to break values and corresponding colors through CIE Lab color space (`colorspace::LAB`) by default.\n#' Values exceeding breaks will be assigned with corresponding maximum or minimum colors.\n#'\n#' @param breaks A vector indicating numeric breaks\n#' @param colors A vector of colors which correspond to values in ``breaks``\n#' @param transparency A single value in ``[0, 1]``. 0 refers to no transparency and 1 refers to full transparency\n#' @param space color space in which colors are interpolated. Value should be one of \"RGB\", \"HSV\", \"HLS\", \"LAB\", \"XYZ\", \"sRGB\", \"LUV\", see `colorspace::color-class` for detail.\n#' @importFrom colorspace coords RGB HSV HLS LAB XYZ sRGB LUV hex\n#' @importFrom grDevices col2rgb\n#' @return It returns a function which accepts a vector of numeric values and returns interpolated colors.\n#' @export\n#' @examples\n#' \\dontrun{\n#' col_fun = colorRamp3(c(-1, 0, 1), c(\"green\", \"white\", \"red\"))\n#' col_fun(c(-2, -1, -0.5, 0, 0.5, 1, 2))\n#' }\ncolorRamp3 = function(breaks, colors, transparency = 0, space = \"LAB\") {\n\n if(length(breaks) != length(colors)) {\n stop(\"Length of `breaks` should be equal to `colors`.\\n\")\n }\n\n colors = colors[order(breaks)]\n breaks = sort(breaks)\n\n l = duplicated(breaks)\n breaks = breaks[!l]\n colors = colors[!l]\n\n if(length(breaks) == 1) {\n stop(\"You should have at least two distinct break values.\")\n }\n\n\n if(! space %in% c(\"RGB\", \"HSV\", \"HLS\", \"LAB\", \"XYZ\", \"sRGB\", \"LUV\")) {\n stop(\"`space` should be in 'RGB', 'HSV', 'HLS', 'LAB', 'XYZ', 'sRGB', 'LUV'\")\n }\n\n colors = t(grDevices::col2rgb(colors)/255)\n\n attr = list(breaks = breaks, colors = colors, transparency = transparency, space = space)\n\n if(space == \"LUV\") {\n i = which(apply(colors, 1, function(x) all(x == 0)))\n colors[i, ] = 1e-5\n }\n\n transparency = 1-ifelse(transparency > 1, 1, ifelse(transparency < 0, 0, transparency))[1]\n transparency_str = sprintf(\"%X\", round(transparency*255))\n if(nchar(transparency_str) == 1) transparency_str = paste0(\"0\", transparency_str)\n\n fun = function(x = NULL, return_rgb = FALSE, max_value = 1) {\n if(is.null(x)) {\n stop(\"Please specify `x`\\n\")\n }\n\n att = attributes(x)\n if(is.data.frame(x)) x = as.matrix(x)\n\n l_na = is.na(x)\n if(all(l_na)) {\n return(rep(NA, length(l_na)))\n }\n\n x2 = x[!l_na]\n\n x2 = ifelse(x2 < breaks[1], breaks[1],\n ifelse(x2 > breaks[length(breaks)], breaks[length(breaks)],\n x2\n ))\n ibin = .bincode(x2, breaks, right = TRUE, include.lowest = TRUE)\n res_col = character(length(x2))\n for(i in unique(ibin)) {\n l = ibin == i\n res_col[l] = .get_color(x2[l], breaks[i], breaks[i+1], colors[i, ], colors[i+1, ], space = space)\n }\n res_col = paste(res_col, transparency_str[1], sep = \"\")\n\n if(return_rgb) {\n res_col = t(grDevices::col2rgb(as.vector(res_col), alpha = TRUE)/255)\n return(res_col)\n } else {\n res_col2 = character(length(x))\n res_col2[l_na] = NA\n res_col2[!l_na] = res_col\n\n attributes(res_col2) = att\n return(res_col2)\n }\n }\n\n attributes(fun) = attr\n return(fun)\n}\n\n.restrict_in = function(x, lower, upper) {\n x[x > upper] = upper\n x[x < lower] = lower\n x\n}\n\n# x: vector\n# break1 single value\n# break2 single value\n# rgb1 vector with 3 elements\n# rgb2 vector with 3 elements\n.get_color = function(x, break1, break2, col1, col2, space) {\n\n col1 = colorspace::coords(as(colorspace::sRGB(col1[1], col1[2], col1[3]), space))\n col2 = colorspace::coords(as(colorspace::sRGB(col2[1], col2[2], col2[3]), space))\n\n res_col = matrix(ncol = 3, nrow = length(x))\n for(j in 1:3) {\n xx = (x - break2)*(col2[j] - col1[j]) / (break2 - break1) + col2[j]\n res_col[, j] = xx\n }\n\n res_col = get(space)(res_col)\n res_col = colorspace::coords(as(res_col, \"sRGB\"))\n res_col[, 1] = .restrict_in(res_col[,1], 0, 1)\n res_col[, 2] = .restrict_in(res_col[,2], 0, 1)\n res_col[, 3] = .restrict_in(res_col[,3], 0, 1)\n colorspace::hex(colorspace::sRGB(res_col))\n}\n\n#' Update the cell-cell communication array from a customized cell-cell-communication scores between different cell groups\n#'\n#' Users may also check the `updateCellChatDB` function for integrating other resources or utilizing a custom database\n#'\n#' @param object CellChat object\n#' @param net a data frame with at least five columns named as `source`,`target`,`ligand`,`receptor` and `score`, which defines the customized cell-cell-communication scores between different cell groups.\n#' a p-value column named `pval`, and additional columns named `interaction_name` and `interaction_name_2` can be also provided.\n#' @return a CellChat object with updated slot `net` and slot `DB` if db is not NULL.\n#' @export\n\nupdateCCC_score <- function(object, net) {\n df.net <- net\n if (all(c(\"source\",\"target\",\"ligand\",\"receptor\",\"score\") %in% colnames(df.net)) == FALSE) {\n stop(\"The input `net` must contain at least five columns named as source,target,ligand,receptor,score\")\n }\n if (all(c(\"interaction_name\") %in% colnames(df.net)) == FALSE) {\n df.net$interaction_name <- paste0(toupper(df.net$ligand), \"_\", toupper(df.net$receptor))\n }\n if (all(c(\"interaction_name_2\") %in% colnames(df.net)) == FALSE) {\n df.net$interaction_name_2 <- paste0(df.net$ligand, \" - \", df.net$receptor)\n }\n if (all(c(\"pval\") %in% colnames(df.net)) == FALSE) {\n df.net$pval <- rep(0, nrow(df.net))\n }\n df.net$prob <- df.net$score\n\n LR <- unique(df.net$interaction_name)\n cell.levels <- levels(object@idents)\n numCluster <- length(cell.levels)\n mat.prob.all <- array(0, dim = c(numCluster,numCluster,length(LR)))\n mat.pval.all <- mat.prob.all\n for (i in 1:length(LR)) {\n df.i <- df.net[df.net$interaction_name == LR[i], , drop = FALSE]\n mat.prob <- matrix(0, nrow = numCluster, ncol = numCluster)\n mat.pval <- mat.prob\n for (j in 1:nrow(df.i)) {\n idx.s <- which(df.i$source[j] == cell.levels)\n idx.t <- which(df.i$target[j] == cell.levels)\n mat.prob[idx.s, idx.t] <- df.i$prob[j]\n mat.pval[idx.s, idx.t] <- df.i$pval[j]\n }\n mat.prob.all[,,i] <- mat.prob\n mat.pval.all[,,i] <- mat.pval\n }\n\n dimnames(mat.prob.all) <- list(cell.levels, cell.levels, LR)\n dimnames(mat.pval.all) <- dimnames(mat.prob.all)\n net <- list(\"prob\" = mat.prob.all, \"pval\" = mat.pval.all)\n object@net <- net\n\n return(object)\n}\n\n#' Preprocessing multi-omics data and preparing the L-R database\n#'\n#' @param data.list a list consisting of multi-omics data (e.g., RNA & ADT)\n#' @param db one of the CellChatDB databases: CellChatDB.human, CellChatDB.mouse, CellChatDB.zebrafish\n#' @param do.sparse whether to use sparse format\n#' @export\n#'\npreProcMultiomics <- function(data.list, db, do.sparse = TRUE) {\n # normalize the data\n data.input.rna <- data.list[[1]]\n data.input.adt <- data.list[[2]]\n data.input.rna = data.input.rna/max(data.input.rna)\n data.input.adt = data.input.adt/max(data.input.adt)\n data.input.adt.temp = data.input.adt\n X = data.input.adt\n for (i in 1:nrow(X)) {\n data.input.adt.temp[i,] = (X[i,]-min(X[i,]))/(max(X[i,])-min(X[i,]))\n }\n data.input.adt[data.input.adt.temp < 0.5] <- 0\n if (do.sparse) {\n data.input = rbind(data.input.rna, as(data.input.adt, \"dgCMatrix\"))\n } else {\n data.input = rbind(as.matrix(data.input.rna), as.matrix(data.input.adt))\n }\n\n # create a new L-R database\n proteins <- rownames(data.input.adt)\n geneInfo.subset <- db$geneInfo[db$geneInfo$AntibodyName %in% proteins, ]\n proteins.nonmapping <- setdiff(proteins, geneInfo.subset$AntibodyName)\n if (length(proteins.nonmapping) > 0) {\n warning(cat(\"The following antibodies are not found in `CellChatDB$geneInfo$AntibodyName`: \", toString(proteins.nonmapping), \"! Please manually add them via the function `updateCellChatDB`. \\n\"))\n }\n out <- extractLRfromGenes(geneSet = geneInfo.subset$Symbol, db)\n LR.use <- out$LR.use\n idx <- match(LR.use$ligand, geneInfo.subset$Symbol)\n LR.use$ligand[!is.na(idx)] <- geneInfo.subset$AntibodyName[idx[!is.na(idx)]]\n idx <- match(LR.use$receptor, geneInfo.subset$Symbol)\n LR.use$receptor[!is.na(idx)] <- geneInfo.subset$AntibodyName[idx[!is.na(idx)]]\n\n db.use <- db\n db.use$interaction <- LR.use\n db.use$geneInfo <- dplyr::add_row(db.use$geneInfo, Symbol = geneInfo.subset$AntibodyName)\n\n return(list(data.input = data.input, db.use = db.use))\n}\n\n\n \n"], ["/CellChat/R/modeling.R", "\n#' Compute the communication probability/strength between any interacting cell groups\n#'\n#' To further speed up on large-scale datasets, USER can downsample the data using the function 'subset' from Seurat package (e.g., pbmc.small <- subset(pbmc, downsample = 500)), or using the function `sketchData` from CellChat, in particular for the large cell clusters;\n#'\n#'\n#' @param object CellChat object\n#' @param type Methods for computing the average gene expression per cell group. By default = \"triMean\", producing fewer but stronger interactions;\n#' When setting `type = \"truncatedMean\"`, a value should be assigned to 'trim', producing more interactions.\n#' @param trim the fraction (0 to 0.25) of observations to be trimmed from each end of x before the mean is computed\n#' @param LR.use A subset of ligand-receptor interactions used in inferring communication network\n#' @param raw.use Whether use the raw data (i.e., `object@data.signaling`) or the smoothed data (i.e., `object@data.smooth`).\n#' Set raw.use = FALSE to use the projected data when analyzing single-cell data with shallow sequencing depth because the projected data could help to reduce the dropout effects of signaling genes, in particular for possible zero expression of subunits of ligands/receptors.\n#' @param population.size Whether consider the proportion of cells in each group across all sequenced cells.\n#' Set population.size = FALSE if analyzing sorting-enriched single cells, to remove the potential artifact of population size.\n#' Set population.size = TRUE if analyzing unsorted single-cell transcriptomes, with the reason that abundant cell populations tend to send collectively stronger signals than the rare cell populations.\n#'\n#' Parameters for spatial data analysis:\n#' @param distance.use Whether to use distance constraints to compute communication probability. Setting `distance.use = TRUE` indicates that the cell-cell communication probability is inversely proportional to the computed distance.\n#' Setting `distance.use = FALSE` will only filter out interactions between spatially distant regions, but not add distance constraints.\n#' @param interaction.range The maximum interaction/diffusion length of ligands (Unit: microns). This hard threshold is used to filter out the connections between spatially distant regions\n#' @param scale.distance A scale or normalization factor for the spatial distances when setting `distance.use = TRUE`. For example, scale.distance equals 1, 0.1, 0.01, 0.001, 0.11, or 0.011. We choose this values such that the minimum value of the scaled distances is in [1,2]. This value is not necessary when setting `distance.use = FALSE`.\n#'\n#' When comparing communication across different CellChat objects, the same scale factor should be used. For a single CellChat analysis, different scale factors will not affect the ranking of the signaling based on their interaction strength.\n#'\n#' @param k.min The minimum number of interacting cell pairs required for defining spatially proximal cell groups.\n#' @param contact.dependent Whether using the `contact-dependent` manner for inference signaling, that is determining interacting cell pairs by requiring cells to be in direct membrane-membrane contact. By default `contact.dependent = TRUE` when inferring contact-dependent and juxtacrine signaling (that is \"Cell-Cell Contact\" signaling classified in CellChatDB$interaction$annotation).\n#' If only focusing on `Secreted Signaling`, the `contact-dependent` manner will be not used except for setting `contact.dependent.forced = TRUE`.\n#' @param contact.range The interaction range (Unit: microns) to restrict the contact-dependent signaling when `contact.dependent = TRUE`.\n#' For spatial transcriptomics in a single-cell resolution, `contact.range` is approximately equal to the estimated cell diameter (i.e., the cell center-to-center distance), which means that contact-dependent and juxtacrine signaling can only happens when the two cells are contact to each other.\n#'\n#' Typically, `contact.range = 10`, which is a typical human cell size. However, for low-resolution spatial data such as 10X visium, it should be the cell center-to-center distance (i.e., `contact.range = 100` for visium data). The function `computeCellDistance` can compute the center-to-center distance.\n#'\n#' @param contact.knn.k Number of neighbors to restrict the contact-dependent signaling within the neatest neighbors when `contact.dependent = TRUE`. By default, CellChat uses `contact.range` to restrict the contact-dependent signaling; however, users can also provide a value of `contact.knn.k`, in order to determine interacting cell pairs based on the k-nearest neighbors (knn).\n#' For 10X visium, contact.knn.k = 6. For other spatial technologies, this value may be hard to determine because the sequenced cells/spots are usually not regularly arranged.\n#' @param do.symmetric Whether converting the adjacent matrix into symmetric one when determining spatially proximal cell groups. Default is TRUE, indicating that if adj(i,j) or adj(j,i) is zero, then both are zeros.\n#'\n#' @param contact.dependent.forced Whether forcing to use the `contact-dependent` manner for inference signaling for all L-R pairs including secreted signaling. Users can set `contact.dependent.forced = TRUE` if also preferring interactions within a contact manner for `Secreted Signaling`.\n#'\n#' @param nboot Threshold of p-values\n#' @param seed.use Set a random seed. By default, set the seed to 1.\n#' @param Kh Parameter in Hill function\n#' @param n Parameter in Hill function\n#'\n#'\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom stats aggregate\n#' @importFrom Matrix crossprod\n#' @importFrom utils txtProgressBar setTxtProgressBar\n#'\n#' @return A CellChat object with updated slot 'net':\n#'\n#' object@net$prob is the inferred communication probability (strength) array, where the first, second and third dimensions represent a source, target and ligand-receptor pair, respectively.\n#'\n#' USER can access all the inferred cell-cell communications using the function 'subsetCommunication(object)', which returns a data frame.\n#'\n#' object@net$pval is the corresponding p-values of each interaction\n#'\n#' @export\n#'\ncomputeCommunProb <- function(object, type = c(\"triMean\", \"truncatedMean\",\"thresholdedMean\", \"median\"), trim = 0.1, LR.use = NULL, raw.use = TRUE, population.size = FALSE,\n distance.use = TRUE, interaction.range = 250, scale.distance = 0.01, k.min = 10, contact.dependent = TRUE, contact.range = NULL, contact.knn.k = NULL, contact.dependent.forced = FALSE, do.symmetric = TRUE,\n nboot = 100, seed.use = 1L, Kh = 0.5, n = 1) {\n type <- match.arg(type)\n cat(type, \"is used for calculating the average gene expression per cell group.\", \"\\n\")\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n thresholdedMean = function(x) thresholdedMean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n if (raw.use) {\n data <- as.matrix(object@data.signaling)\n } else {\n data <- as.matrix(object@data.smooth)\n }\n if (is.null(LR.use)) {\n pairLR.use <- object@LR$LRsig\n } else {\n if (length(unique(LR.use$annotation)) > 1) {\n LR.use$annotation <- factor(LR.use$annotation, levels = c(\"Secreted Signaling\",\"ECM-Receptor\", \"Non-protein Signaling\", \"Cell-Cell Contact\"))\n LR.use <- LR.use[order(LR.use$annotation), , drop = FALSE]\n LR.use$annotation <- as.character(LR.use$annotation)\n }\n pairLR.use <- LR.use\n }\n complex_input <- object@DB$complex\n cofactor_input <- object@DB$cofactor\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n\n ptm = Sys.time()\n\n pairLRsig <- pairLR.use\n group <- object@idents\n geneL <- as.character(pairLRsig$ligand)\n geneR <- as.character(pairLRsig$receptor)\n nLR <- nrow(pairLRsig)\n numCluster <- nlevels(group)\n if (numCluster != length(unique(group))) {\n stop(\"Please check `unique(object@idents)` and ensure that the factor levels are correct!\n You may need to drop unused levels using 'droplevels' function. e.g.,\n `meta$labels = droplevels(meta$labels, exclude = setdiff(levels(meta$labels),unique(meta$labels)))`\")\n }\n\n data.use <- data/max(data)\n nC <- ncol(data.use)\n\n # compute the average expression per group\n data.use.avg <- aggregate(t(data.use), list(group), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n colnames(data.use.avg) <- levels(group)\n # compute the expression of ligand or receptor\n dataLavg <- computeExpr_LR(geneL, data.use.avg, complex_input)\n dataRavg <- computeExpr_LR(geneR, data.use.avg, complex_input)\n # take account into the effect of co-activation and co-inhibition receptors\n dataRavg.co.A.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avg, pairLRsig, type = \"A\")\n dataRavg.co.I.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avg, pairLRsig, type = \"I\")\n dataRavg <- dataRavg * dataRavg.co.A.receptor/dataRavg.co.I.receptor\n\n dataLavg2 <- t(replicate(nrow(dataLavg), as.numeric(table(group))/nC))\n dataRavg2 <- dataLavg2\n\n # compute the expression of agonist and antagonist\n index.agonist <- which(!is.na(pairLRsig$agonist) & pairLRsig$agonist != \"\")\n index.antagonist <- which(!is.na(pairLRsig$antagonist) & pairLRsig$antagonist != \"\")\n # quantify the communication probability\n\n # compute the spatial constraint\n if (object@options$datatype != \"RNA\") {\n data.spatial <- object@images$coordinates\n if (\"spatial.factors\" %in% names(object@images)) {\n ratio <- object@images$spatial.factors$ratio\n tol <- object@images$spatial.factors$tol\n } else {\n stop(\"`object@images$spatial.factors` is missing. Please update the object via `updateCellChat`! \\n\")\n }\n\n meta.t = data.frame(group = group, samples = object@meta$samples, row.names = rownames(object@meta))\n res <- computeRegionDistance(coordinates = data.spatial, meta = meta.t, interaction.range = interaction.range, ratio = ratio, tol = tol, k.min = k.min, contact.dependent = contact.dependent, contact.range = contact.range, contact.knn.k = contact.knn.k)\n d.spatial <- res$d.spatial # NaN if no nearby cell pairs\n adj.contact <- res$adj.contact # zeros if no nearby cell pairs\n if (distance.use) {\n print(paste0('>>> Run CellChat on spatial transcriptomics data using distances as constraints of the computed communication probability <<< [', Sys.time(),']'))\n d.spatial <- d.spatial * scale.distance\n diag(d.spatial) <- NaN\n d.min <- min(d.spatial, na.rm = TRUE)\n if (d.min < 1) {\n cat(\"The suggested minimum value of scaled distances is in [1,2], and the calculated value here is \", d.min,\"\\n\")\n stop(\"Please increase the value of `scale.distance` and use a value that is slighly smaller than \", format(1/d.min, digits = 2) ,\"\\n\")\n }\n P.spatial <- 1/d.spatial\n P.spatial[is.na(d.spatial)] <- 0\n diag(P.spatial) <- max(P.spatial) # if this value is 1, the self-connections will have more larger weight.\n d.spatial <- d.spatial/scale.distance # This is only for saving the data\n } else {\n print(paste0('>>> Run CellChat on spatial transcriptomics data without distance values as constraints of the computed communication probability <<< [', Sys.time(),']'))\n P.spatial <- matrix(1, nrow = numCluster, ncol = numCluster)\n P.spatial[is.na(d.spatial)] <- 0 # diagonal is 1\n }\n\n } else {\n print(paste0('>>> Run CellChat on sc/snRNA-seq data <<< [', Sys.time(),']'))\n d.spatial <- matrix(NaN, nrow = numCluster, ncol = numCluster)\n P.spatial <- matrix(1, nrow = numCluster, ncol = numCluster)\n adj.contact <- matrix(1, nrow = numCluster, ncol = numCluster)\n contact.dependent = FALSE; contact.dependent.forced = FALSE; contact.range = NULL; contact.knn.k = NULL;\n distance.use = NULL; interaction.range = NULL; ratio = NULL; tol = NULL; k.min = NULL;\n }\n\n if (object@options$datatype == \"RNA\") {\n nLR1 <- nLR\n } else {\n if (contact.dependent.forced == TRUE) {\n cat(\"Force to run CellChat in a `contact-dependent` manner for all L-R pairs including secreted signaling.\\n\")\n P.spatial <- P.spatial * adj.contact\n nLR1 <- nLR\n } else { # contact.dependent.forced == F\n if (contact.dependent == TRUE && length(unique(pairLRsig$annotation)) > 0) {\n if (all(unique(pairLRsig$annotation) %in% c(\"Cell-Cell Contact\"))) {\n cat(\"All the input L-R pairs are `Cell-Cell Contact` signaling. Run CellChat in a contact-dependent manner. \\n\")\n P.spatial <- P.spatial * adj.contact\n nLR1 <- nLR\n } else if (all(unique(pairLRsig$annotation) %in% c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\"))) {\n cat(\"Molecules of the input L-R pairs are diffusible. Run CellChat in a diffusion manner based on the `interaction.range`.\\n\")\n nLR1 <- nLR\n } else {\n cat(\"The input L-R pairs have both secreted signaling and contact-dependent signaling. Run CellChat in a contact-dependent manner for `Cell-Cell Contact` signaling, and in a diffusion manner based on the `interaction.range` for other L-R pairs. \\n\")\n nLR1 <- max(which(pairLRsig$annotation %in% c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\")))\n }\n } else { # contact.dependent == F or there is no `annotation` column in the database\n cat(\"Run CellChat in a diffusion manner based on the `interaction.range` for all L-R pairs. Setting `contact.dependent = TRUE` if preferring a contact-dependent manner for `Cell-Cell Contact` signaling. \\n\")\n nLR1 <- nLR\n }\n }\n }\n\n Prob <- array(0, dim = c(numCluster,numCluster,nLR))\n Pval <- array(0, dim = c(numCluster,numCluster,nLR))\n\n set.seed(seed.use)\n permutation <- replicate(nboot, sample.int(nC, size = nC))\n data.use.avg.boot <- my.sapply(\n X = 1:nboot,\n FUN = function(nE) {\n groupboot <- group[permutation[, nE]]\n data.use.avgB <- aggregate(t(data.use), list(groupboot), FUN = FunMean)\n data.use.avgB <- t(data.use.avgB[,-1])\n return(data.use.avgB)\n },\n simplify = FALSE\n )\n pb <- txtProgressBar(min = 0, max = nLR, style = 3, file = stderr())\n\n for (i in 1:nLR) {\n # ligand/receptor\n dataLR <- Matrix::crossprod(matrix(dataLavg[i,], nrow = 1), matrix(dataRavg[i,], nrow = 1))\n P1 <- dataLR^n/(Kh^n + dataLR^n)\n P1_Pspatial <- P1*P.spatial\n if (sum(P1_Pspatial) == 0) {\n Pnull = P1_Pspatial\n Prob[ , , i] <- Pnull\n p = 1\n Pval[, , i] <- matrix(p, nrow = numCluster, ncol = numCluster, byrow = FALSE)\n } else {\n if (i > nLR1) {\n P.spatial <- P.spatial * adj.contact\n }\n # agonist and antagonist\n if (is.element(i, index.agonist)) {\n data.agonist <- computeExpr_agonist(data.use = data.use.avg, pairLRsig, cofactor_input, index.agonist = i, Kh = Kh, n = n)\n P2 <- Matrix::crossprod(matrix(data.agonist, nrow = 1))\n } else {\n P2 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n if (is.element(i, index.antagonist)) {\n data.antagonist <- computeExpr_antagonist(data.use = data.use.avg, pairLRsig, cofactor_input, index.antagonist = i, Kh = Kh, n = n)\n P3 <- Matrix::crossprod(matrix(data.antagonist, nrow = 1))\n } else {\n P3 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n # number of cells\n if (population.size) {\n P4 <- Matrix::crossprod(matrix(dataLavg2[i,], nrow = 1), matrix(dataRavg2[i,], nrow = 1))\n } else {\n P4 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n # Pnull = P1*P2*P3*P4\n Pnull = P1*P2*P3*P4*P.spatial\n Prob[ , , i] <- Pnull\n\n Pnull <- as.vector(Pnull)\n\n #Pboot <- foreach(nE = 1:nboot) %dopar% {\n Pboot <- sapply(\n X = 1:nboot,\n FUN = function(nE) {\n data.use.avgB <- data.use.avg.boot[[nE]]\n dataLavgB <- computeExpr_LR(geneL[i], data.use.avgB, complex_input)\n dataRavgB <- computeExpr_LR(geneR[i], data.use.avgB, complex_input)\n # take account into the effect of co-activation and co-inhibition receptors\n dataRavgB.co.A.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avgB, pairLRsig[i, , drop = FALSE], type = \"A\")\n dataRavgB.co.I.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avgB, pairLRsig[i, , drop = FALSE], type = \"I\")\n dataRavgB <- dataRavgB * dataRavgB.co.A.receptor/dataRavgB.co.I.receptor\n dataLRB = Matrix::crossprod(dataLavgB, dataRavgB)\n P1.boot <- dataLRB^n/(Kh^n + dataLRB^n)\n # agonist and antagonist\n if (is.element(i, index.agonist)) {\n data.agonist <- computeExpr_agonist(data.use = data.use.avgB, pairLRsig, cofactor_input, index.agonist = i, Kh = Kh, n = n)\n P2.boot <- Matrix::crossprod(matrix(data.agonist, nrow = 1))\n } else {\n P2.boot <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n if (is.element(i, index.antagonist)) {\n data.antagonist <- computeExpr_antagonist(data.use = data.use.avgB, pairLRsig, cofactor_input, index.antagonist = i, Kh = Kh, n= n)\n P3.boot <- Matrix::crossprod(matrix(data.antagonist, nrow = 1))\n } else {\n P3.boot <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n if (population.size) {\n groupboot <- group[permutation[, nE]]\n dataLavg2B <- as.numeric(table(groupboot))/nC\n dataLavg2B <- matrix(dataLavg2B, nrow = 1)\n dataRavg2B <- dataLavg2B\n P4.boot = Matrix::crossprod(dataLavg2B, dataRavg2B)\n } else {\n P4.boot = matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n # Pboot = P1.boot*P2.boot*P3.boot*P4.boot\n Pboot = P1.boot*P2.boot*P3.boot*P4.boot*P.spatial\n return(as.vector(Pboot))\n }\n )\n Pboot <- matrix(unlist(Pboot), nrow=length(Pnull), ncol = nboot, byrow = FALSE)\n nReject <- rowSums(Pboot - Pnull > 0)\n p = nReject/nboot\n Pval[, , i] <- matrix(p, nrow = numCluster, ncol = numCluster, byrow = FALSE)\n }\n setTxtProgressBar(pb = pb, value = i)\n }\n close(con = pb)\n Pval[Prob == 0] <- 1\n dimnames(Prob) <- list(levels(group), levels(group), rownames(pairLRsig))\n dimnames(Pval) <- dimnames(Prob)\n net <- list(\"prob\" = Prob, \"pval\" = Pval)\n execution.time = Sys.time() - ptm\n object@options$run.time <- as.numeric(execution.time, units = \"secs\")\n\n object@options$parameter <- list(type.mean = type, trim = trim, raw.use = raw.use, population.size = population.size, nboot = nboot, seed.use = seed.use, Kh = Kh, n = n,\n distance.use = distance.use, interaction.range = interaction.range, ratio = ratio, tol = tol, k.min = k.min,\n contact.dependent = contact.dependent, contact.range = contact.range, contact.knn.k = contact.knn.k, contact.dependent.forced = contact.dependent.forced\n )\n if (object@options$datatype != \"RNA\") {\n object@images$distance <- d.spatial\n }\n object@net <- net\n print(paste0('>>> CellChat inference is done. Parameter values are stored in `object@options$parameter` <<< [', Sys.time(),']'))\n return(object)\n}\n\n\n#' Compute the communication probability on signaling pathway level by summarizing all related ligands/receptors\n#'\n#' @param object CellChat object\n#' @param net A list from object@net; If net = NULL, net = object@net\n#' @param pairLR.use A dataframe giving the ligand-receptor interactions; If pairLR.use = NULL, pairLR.use = object@LR$LRsig\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @return A CellChat object with updated slot 'netP':\n#'\n#' object@netP$prob is the communication probability array on signaling pathway level; USER can convert this array to a data frame using the function 'reshape2::melt()',\n#'\n#' e.g., `df.netP <- reshape2::melt(object@netP$prob, value.name = \"prob\"); colnames(df.netP)[1:3] <- c(\"source\",\"target\",\"pathway_name\")` or access all significant interactions using the function \\code{\\link{subsetCommunication}}\n#'\n#' object@netP$pathways list all the signaling pathways with significant communications.\n#'\n#' From version >= 1.1.0, pathways are ordered based on the total communication probabilities. NB: pathways with small total communication probabilities might be also very important since they might be specifically activated between only few cell types.\n#'\n#' @export\n#'\ncomputeCommunProbPathway <- function(object = NULL, net = NULL, pairLR.use = NULL, thresh = 0.05) {\n if (is.null(net)) {\n net <- object@net\n }\n if (is.null(pairLR.use)) {\n pairLR.use <- object@LR$LRsig\n }\n prob <- net$prob\n prob[net$pval > thresh] <- 0\n\n LR <- dimnames(prob)[[3]]\n LR.sig <- LR[apply(prob, 3, sum) != 0]\n\n pathways <- unique(pairLR.use$pathway_name)\n group <- factor(pairLR.use$pathway_name, levels = pathways)\n prob.pathways <- aperm(apply(prob, c(1, 2), by, group, sum), c(2, 3, 1))\n pathways.sig <- pathways[apply(prob.pathways, 3, sum) != 0]\n prob.pathways.sig <- prob.pathways[,,pathways.sig, drop = FALSE]\n idx <- sort(apply(prob.pathways.sig, 3, sum), decreasing=TRUE, index.return = TRUE)$ix\n pathways.sig <- pathways.sig[idx]\n prob.pathways.sig <- prob.pathways.sig[, , idx]\n\n if (is.null(object)) {\n netP = list(pathways = pathways.sig, prob = prob.pathways.sig)\n return(netP)\n } else {\n object@net$LRs <- LR.sig\n object@netP$pathways <- pathways.sig\n object@netP$prob <- prob.pathways.sig\n return(object)\n }\n}\n\n\n#' Calculate the aggregated network by counting the number of links or summarizing the communication probability\n#'\n#' @param object CellChat object\n#' @param sources.use,targets.use,signaling,pairLR.use Please check the description in function \\code{\\link{subsetCommunication}}\n#' @param remove.isolate whether removing the isolate cell groups without any interactions when applying \\code{\\link{subsetCommunication}}\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param return.object whether return an updated CellChat object\n#' @importFrom dplyr group_by summarize groups\n#' @importFrom stringr str_split\n#'\n#' @return Return an updated CellChat object:\n#'\n#' `object@net$count` is a matrix: rows and columns are sources and targets respectively, and elements are the number of interactions between any two cell groups. USER can convert a matrix to a data frame using the function `reshape2::melt()`\n#'\n#' `object@net$weight` is also a matrix containing the interaction weights between any two cell groups\n#'\n#' `object@net$sum` is deprecated. Use `object@net$weight`\n#'\n#' @export\n#'\naggregateNet <- function(object, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR.use = NULL, remove.isolate = TRUE, thresh = 0.05, return.object = TRUE) {\n net <- object@net\n if (is.null(sources.use) & is.null(targets.use) & is.null(signaling) & is.null(pairLR.use)) {\n prob <- net$prob\n pval <- net$pval\n pval[prob == 0] <- 1\n prob[pval >= thresh] <- 0\n net$count <- apply(prob > 0, c(1,2), sum)\n net$weight <- apply(prob, c(1,2), sum)\n net$weight[is.na(net$weight)] <- 0\n net$count[is.na(net$count)] <- 0\n } else {\n df.net <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.net$source_target <- paste(df.net$source, df.net$target, sep = \"_\")\n df.net2 <- df.net %>% group_by(source_target) %>% summarize(count = n(), .groups = 'drop')\n df.net3 <- df.net %>% group_by(source_target) %>% summarize(prob = sum(prob), .groups = 'drop')\n df.net2$prob <- df.net3$prob\n a <- stringr::str_split(df.net2$source_target, \"_\", simplify = T)\n df.net2$source <- as.character(a[, 1])\n df.net2$target <- as.character(a[, 2])\n cells.level <- levels(object@idents)\n if (remove.isolate) {\n message(\"Isolate cell groups without any interactions are removed. To block it, set `remove.isolate = FALSE`\")\n df.net2$source <- factor(df.net2$source, levels = cells.level[cells.level %in% unique(df.net2$source)])\n df.net2$target <- factor(df.net2$target, levels = cells.level[cells.level %in% unique(df.net2$target)])\n } else {\n df.net2$source <- factor(df.net2$source, levels = cells.level)\n df.net2$target <- factor(df.net2$target, levels = cells.level)\n }\n\n count <- tapply(df.net2[[\"count\"]], list(df.net2[[\"source\"]], df.net2[[\"target\"]]), sum)\n prob <- tapply(df.net2[[\"prob\"]], list(df.net2[[\"source\"]], df.net2[[\"target\"]]), sum)\n net$count <- count\n net$weight <- prob\n net$weight[is.na(net$weight)] <- 0\n net$count[is.na(net$count)] <- 0\n }\n if (return.object) {\n object@net <- net\n return(object)\n } else {\n return(net)\n }\n\n}\n\n\n#' Compute averaged expression values for each cell group\n#'\n#' @param object CellChat object\n#' @param features a char vector giving the used features. default use all features\n#' @param group.by cell group information; default is `object@idents` when input is a single object and `object@idents$joint` when input is a merged object; otherwise it should be one of the column names of the meta slot\n#' @param type methods for computing the average gene expression per cell group.\n#'\n#' By default = \"triMean\", defined as a weighted average of the distribution's median and its two quartiles (https://en.wikipedia.org/wiki/Trimean);\n#'\n#' When setting `type = \"truncatedMean\"`, a value should be assigned to 'trim'. See the function `base::mean`.\n#'\n#' @param trim the fraction (0 to 0.25) of observations to be trimmed from each end of x before the mean is computed.\n#' @param slot.name the data in the slot.name to use\n#' @param data.use a customed data matrix. Default: data.use = NULL and the expression matrix in the 'slot.name' is used\n#'\n#' @return Returns a matrix with genes as rows, cell groups as columns.\n\n#' @export\n#'\ncomputeAveExpr <- function(object, features = NULL, group.by = NULL, type = c(\"triMean\", \"truncatedMean\", \"median\"), trim = NULL,\n slot.name = c(\"data.signaling\", \"data\"), data.use = NULL) {\n type <- match.arg(type)\n slot.name <- match.arg(slot.name)\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n if (is.null(data.use)) {\n data.use <- slot(object, slot.name)\n }\n if (is.null(features)) {\n features.use <- row.names(data.use)\n } else {\n features.use <- intersect(features, row.names(data.use))\n }\n data.use <- data.use[features.use, , drop = FALSE]\n data.use <- as.matrix(data.use)\n\n if (is.null(group.by)) {\n labels <- object@idents\n if (!is.factor(labels)) {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n # compute the average expression per group\n data.use.avg <- aggregate(t(data.use), list(labels), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n rownames(data.use.avg) <- features.use\n colnames(data.use.avg) <- levels(labels)\n return(data.use.avg)\n}\n\n\n\n#' Compute the expression of complex in individual cells using geometric mean\n#' @param complex_input the complex_input from CellChatDB\n#' @param data.use data matrix (row are genes and columns are cells or cell groups)\n#' @param complex the names of complex\n#' @return\n#' @importFrom dplyr select starts_with\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @export\ncomputeExpr_complex <- function(complex_input, data.use, complex) {\n Rsubunits <- complex_input[complex,] %>% dplyr::select(starts_with(\"subunit\"))\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n data.complex = my.sapply(\n X = 1:nrow(Rsubunits),\n FUN = function(x) {\n RsubunitsV <- unlist(Rsubunits[x,], use.names = F)\n RsubunitsV <- RsubunitsV[RsubunitsV != \"\"]\n return(geometricMean(data.use[RsubunitsV, , drop = FALSE]))\n }\n )\n data.complex <- t(data.complex)\n return(data.complex)\n}\n\n# Compute the average expression of complex per cell group using geometric mean\n# @param complex_input the complex_input from CellChatDB\n# @param data.use data matrix (rows are genes and columns are cells)\n# @param complex the names of complex\n# @param group a factor defining the cell groups\n# @param FunMean the function for computing mean expression per group\n# @return\n# @importFrom dplyr select starts_with\n# @importFrom future nbrOfWorkers\n# @importFrom future.apply future_sapply\n# @importFrom pbapply pbsapply\n# #' @export\n.computeExprGroup_complex <- function(complex_input, data.use, complex, group, FunMean) {\n Rsubunits <- complex_input[complex,] %>% dplyr::select(starts_with(\"subunit\"))\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n data.complex = my.sapply(\n X = 1:nrow(Rsubunits),\n FUN = function(x) {\n RsubunitsV <- unlist(Rsubunits[x,], use.names = F)\n RsubunitsV <- RsubunitsV[RsubunitsV != \"\"]\n RsubunitsV <- intersect(RsubunitsV, rownames(data.use))\n if (length(RsubunitsV) > 1) {\n data.avg <- aggregate(t(data.use[RsubunitsV, ,drop = FALSE]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n } else if (length(RsubunitsV) == 1) {\n data.avg <- aggregate(matrix(data.use[RsubunitsV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n } else {\n data.avg = matrix(0, nrow = 1, ncol = length(unique(group)))\n }\n return(geometricMean(data.avg))\n }\n )\n data.complex <- t(data.complex)\n return(data.complex)\n}\n\n#' Compute the expression of ligands or receptors using geometric mean\n#' @param geneLR a char vector giving a set of ligands or receptors\n#' @param data.use data matrix (row are genes and columns are cells or cell groups)\n#' @param complex_input the complex_input from CellChatDB\n# #' @param group a factor defining the cell groups; If NULL, compute the expression of ligands or receptors in individual cells; otherwise, compute the average expression of ligands or receptors per cell group\n# #' @param FunMean the function for computing average expression per cell group\n#' @return\n#' @export\ncomputeExpr_LR <- function(geneLR, data.use, complex_input){\n nLR <- length(geneLR)\n numCluster <- ncol(data.use)\n index.singleL <- which(geneLR %in% rownames(data.use))\n dataL1avg <- data.use[geneLR[index.singleL],]\n dataLavg <- matrix(nrow = nLR, ncol = numCluster)\n dataLavg[index.singleL,] <- dataL1avg\n index.complexL <- setdiff(1:nLR, index.singleL)\n if (length(index.complexL) > 0) {\n complex <- geneLR[index.complexL]\n data.complex <- computeExpr_complex(complex_input, data.use, complex)\n dataLavg[index.complexL,] <- data.complex\n }\n return(dataLavg)\n}\n\n\n#' Modeling the effect of coreceptor on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig a data frame giving ligand-receptor interactions\n#' @param type when type == \"A\", computing expression of co-activation receptor; when type == \"I\", computing expression of co-inhibition receptor.\n#' @return\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @export\ncomputeExpr_coreceptor <- function(cofactor_input, data.use, pairLRsig, type = c(\"A\", \"I\")) {\n type <- match.arg(type)\n if (type == \"A\") {\n coreceptor.all = pairLRsig$co_A_receptor\n } else if (type == \"I\"){\n coreceptor.all = pairLRsig$co_I_receptor\n }\n index.coreceptor <- which(!is.na(coreceptor.all) & coreceptor.all != \"\")\n if (length(index.coreceptor) > 0) {\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n coreceptor <- coreceptor.all[index.coreceptor]\n coreceptor.ind <- cofactor_input[coreceptor, grepl(\"cofactor\" , colnames(cofactor_input) )]\n data.coreceptor.ind = my.sapply(\n X = 1:nrow(coreceptor.ind),\n FUN = function(x) {\n coreceptor.indV <- unlist(coreceptor.ind[x,], use.names = F)\n coreceptor.indV <- coreceptor.indV[coreceptor.indV != \"\"]\n coreceptor.indV <- intersect(coreceptor.indV, rownames(data.use))\n if (length(coreceptor.indV) == 1) {\n return(1 + data.use[coreceptor.indV, ])\n } else if (length(coreceptor.indV) > 1) {\n return(apply(1 + data.use[coreceptor.indV, ], 2, prod))\n } else {\n return(matrix(1, nrow = 1, ncol = ncol(data.use)))\n }\n }\n )\n data.coreceptor.ind <- t(data.coreceptor.ind)\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = ncol(data.use))\n data.coreceptor[index.coreceptor,] <- data.coreceptor.ind\n } else {\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = ncol(data.use))\n }\n return(data.coreceptor)\n}\n\n# Modeling the effect of coreceptor on the ligand-receptor interaction\n#\n# @param data.use data matrix\n# @param cofactor_input the cofactor_input from CellChatDB\n# @param pairLRsig a data frame giving ligand-receptor interactions\n# @param type when type == \"A\", computing expression of co-activation receptor; when type == \"I\", computing expression of co-inhibition receptor.\n# @param group a factor defining the cell groups\n# @param FunMean the function for computing mean expression per group\n# @return\n# @importFrom future nbrOfWorkers\n# @importFrom future.apply future_sapply\n# @importFrom pbapply pbsapply\n# #' @export\n.computeExprGroup_coreceptor <- function(cofactor_input, data.use, pairLRsig, type = c(\"A\", \"I\"), group, FunMean) {\n type <- match.arg(type)\n if (type == \"A\") {\n coreceptor.all = pairLRsig$co_A_receptor\n } else if (type == \"I\"){\n coreceptor.all = pairLRsig$co_I_receptor\n }\n index.coreceptor <- which(!is.na(coreceptor.all) & coreceptor.all != \"\")\n if (length(index.coreceptor) > 0) {\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n coreceptor <- coreceptor.all[index.coreceptor]\n coreceptor.ind <- cofactor_input[coreceptor, grepl(\"cofactor\" , colnames(cofactor_input) )]\n data.coreceptor.ind = my.sapply(\n X = 1:nrow(coreceptor.ind),\n FUN = function(x) {\n coreceptor.indV <- unlist(coreceptor.ind[x,], use.names = F)\n coreceptor.indV <- coreceptor.indV[coreceptor.indV != \"\"]\n coreceptor.indV <- intersect(coreceptor.indV, rownames(data.use))\n if (length(coreceptor.indV) > 1) {\n data.avg <- aggregate(t(data.use[coreceptor.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n return(apply(1 + data.avg, 2, prod))\n # return(1 + apply(data.avg, 2, mean))\n } else if (length(coreceptor.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[coreceptor.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n return(1 + data.avg)\n } else {\n return(matrix(1, nrow = 1, ncol = length(unique(group))))\n }\n }\n )\n data.coreceptor.ind <- t(data.coreceptor.ind)\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = length(unique(group)))\n data.coreceptor[index.coreceptor,] <- data.coreceptor.ind\n } else {\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = length(unique(group)))\n }\n\n return(data.coreceptor)\n}\n\n#' Modeling the effect of agonist on the ligand-receptor interaction\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n#' @param group a factor defining the cell groups\n#' @param index.agonist the index of agonist in the database\n#' @param Kh a parameter in Hill function\n#' @param FunMean the function for computing mean expression per group\n#' @param n Hill coefficient\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExprGroup_agonist <- function(data.use, pairLRsig, cofactor_input, group, index.agonist, Kh, FunMean, n) {\n agonist <- pairLRsig$agonist[index.agonist]\n agonist.ind <- cofactor_input[agonist, grepl(\"cofactor\" , colnames(cofactor_input))]\n agonist.indV <- unlist(agonist.ind, use.names = F)\n agonist.indV <- agonist.indV[agonist.indV != \"\"]\n agonist.indV <- intersect(agonist.indV, rownames(data.use))\n if (length(agonist.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[agonist.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.agonist <- 1 + data.avg^n/(Kh^n + data.avg^n)\n } else if (length(agonist.indV) > 1) {\n data.avg <- aggregate(t(data.use[agonist.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.agonist <- apply(1 + data.avg^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n data.agonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n }\n return(data.agonist)\n}\n\n#' Modeling the effect of antagonist on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n#' @param group a factor defining the cell groups\n#' @param index.antagonist the index of antagonist in the database\n#' @param Kh a parameter in Hill function\n#' @param n Hill coefficient\n#' @param FunMean the function for computing mean expression per group\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExprGroup_antagonist <- function(data.use, pairLRsig, cofactor_input, group, index.antagonist, Kh, FunMean, n) {\n antagonist <- pairLRsig$antagonist[index.antagonist]\n antagonist.ind <- cofactor_input[antagonist, grepl( \"cofactor\" , colnames(cofactor_input) )]\n antagonist.indV <- unlist(antagonist.ind, use.names = F)\n antagonist.indV <- antagonist.indV[antagonist.indV != \"\"]\n antagonist.indV <- intersect(antagonist.indV, rownames(data.use))\n if (length(antagonist.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[antagonist.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.antagonist <- Kh^n/(Kh^n + data.avg^n)\n } else if (length(antagonist.indV) > 1) {\n data.avg <- aggregate(t(data.use[antagonist.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.antagonist <- apply(Kh^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n data.antagonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n }\n return(data.antagonist)\n}\n\n\n#' Modeling the effect of agonist on the ligand-receptor interaction\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n# #' @param group a factor defining the cell groups\n#' @param index.agonist the index of agonist in the database\n#' @param Kh a parameter in Hill function\n# #' @param FunMean the function for computing mean expression per group\n#' @param n Hill coefficient\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExpr_agonist <- function(data.use, pairLRsig, cofactor_input, index.agonist, Kh, n) {\n agonist <- pairLRsig$agonist[index.agonist]\n agonist.ind <- cofactor_input[agonist, grepl(\"cofactor\" , colnames(cofactor_input))]\n agonist.indV <- unlist(agonist.ind, use.names = F)\n agonist.indV <- agonist.indV[agonist.indV != \"\"]\n agonist.indV <- intersect(agonist.indV, rownames(data.use))\n if (length(agonist.indV) == 1) {\n # data.avg <- aggregate(matrix(data.use[agonist.indV,], ncol = 1), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[agonist.indV,, drop = FALSE]\n data.agonist <- 1 + data.avg^n/(Kh^n + data.avg^n)\n } else if (length(agonist.indV) > 1) {\n # data.avg <- aggregate(t(data.use[agonist.indV,]), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[agonist.indV,, drop = FALSE]\n data.agonist <- apply(1 + data.avg^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n # data.agonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n data.agonist = matrix(1, nrow = 1, ncol = ncol(data.use))\n }\n return(data.agonist)\n}\n\n#' Modeling the effect of antagonist on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n# #' @param group a factor defining the cell groups\n#' @param index.antagonist the index of antagonist in the database\n#' @param Kh a parameter in Hill function\n#' @param n Hill coefficient\n# #' @param FunMean the function for computing mean expression per group\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExpr_antagonist <- function(data.use, pairLRsig, cofactor_input, index.antagonist, Kh, n) {\n antagonist <- pairLRsig$antagonist[index.antagonist]\n antagonist.ind <- cofactor_input[antagonist, grepl( \"cofactor\" , colnames(cofactor_input) )]\n antagonist.indV <- unlist(antagonist.ind, use.names = F)\n antagonist.indV <- antagonist.indV[antagonist.indV != \"\"]\n antagonist.indV <- intersect(antagonist.indV, rownames(data.use))\n if (length(antagonist.indV) == 1) {\n # data.avg <- aggregate(matrix(data.use[antagonist.indV,], ncol = 1), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[antagonist.indV,, drop = FALSE]\n data.antagonist <- Kh^n/(Kh^n + data.avg^n)\n } else if (length(antagonist.indV) > 1) {\n # data.avg <- aggregate(t(data.use[antagonist.indV,]), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[antagonist.indV,, drop = FALSE]\n data.antagonist <- apply(Kh^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n # data.antagonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n data.antagonist = matrix(1, nrow = 1, ncol = ncol(data.use))\n }\n return(data.antagonist)\n}\n\n\n#' Compute the geometric mean\n#' @param x a numeric vector\n#' @param na.rm whether remove na\n#' @return\n#' @export\ngeometricMean <- function(x,na.rm=TRUE){\n if (is.null(nrow(x))) {\n exp(mean(log(x),na.rm=na.rm))\n } else {\n exp(apply(log(x),2,mean,na.rm=na.rm))\n }\n}\n\n\n#' Compute the Tukey's trimean\n#' @param x a numeric vector\n#' @param na.rm whether remove na\n#' @return\n#' @importFrom stats quantile\n#' @export\ntriMean <- function(x, na.rm = TRUE) {\n mean(stats::quantile(x, probs = c(0.25, 0.50, 0.50, 0.75), na.rm = na.rm))\n}\n\n#' Compute the average expression per cell group when the percent of expressing cells per cell group larger than a threshold\n#' @param x a numeric vector\n#' @param trim the percent of expressing cells per cell group to be considered as zero\n#' @param na.rm whether remove na\n#' @return\n#' @importFrom Matrix nnzero\n# #' @export\nthresholdedMean <- function(x, trim = 0.1, na.rm = TRUE) {\n percent <- Matrix::nnzero(x)/length(x)\n if (percent < trim) {\n return(0)\n } else {\n return(mean(x, na.rm = na.rm))\n }\n}\n\n#' Filter cell-cell communication if there are only few number of cells in certain cell groups or inconsistent cell-cell communication across samples\n#'\n#' @param object CellChat object\n#' @param min.cells The minmum number of cells required in each cell group for cell-cell communication\n#' @param min.samples The minmum number of samples required for consistent cell-cell communication across samples (that is an interaction present in at least `min.samples` samples) when mutiple samples/replicates/batches are merged as an input for CellChat analysis.\n#' @param rare.keep Whether to keep the interactions associated with the rare populations when min.samples >= 2. When a rare population is identified in the merged samples (say 15 cells in this rare population from two samples), it is likely to filter out the interactions associated with this rare population when setting min.samples >= 2. Setting `rare.keep = TRUE` to retain the identified interactions associated with this rare population.\n#' @param nonFilter.keep Whether to keep the non-filtered cell-cell communication in the CellChat object. This is useful for avoiding re-running `computeCommunProb` if you want to adjust the parameters when running `filterCommunication`.\n#' @return CellChat object with an updated slot net\n#' @export\n#'\nfilterCommunication <- function(object, min.cells = 10, min.samples = NULL, rare.keep = FALSE, nonFilter.keep = FALSE) {\n net <- object@net\n if (nonFilter.keep == TRUE) {\n cat(\"The non-filtered cell-cell communication is stored in `object@net$prob.nonFilter` and `object@net$pval.nonFilter`. \\n\")\n object@net$prob.nonFilter <- net$prob\n object@net$pval.nonFilter <- net$pval\n }\n num.interaction0 <- sum(net$prob > 0)\n cell.excludes <- which(as.numeric(table(object@idents)) <= min.cells)\n if (length(cell.excludes) > 0) {\n cat(\"The cell-cell communication related with the following cell groups are excluded due to the few number of cells: \", toString(levels(object@idents)[cell.excludes]), \"!\",'\\t')\n net$prob[cell.excludes,,] <- 0\n net$prob[,cell.excludes,] <- 0\n num.interaction1 <- sum(net$prob > 0)\n pct.dicrease <- scales::percent((num.interaction0-num.interaction1)/num.interaction0, accuracy = .1)\n cat(paste0(pct.dicrease, \" interactions are removed!\",'\\n'))\n } else {\n num.interaction1 <- num.interaction0\n }\n\n sample.info <- object@meta$samples\n sample.id <- levels(sample.info)\n if (is.null(min.samples)) {\n min.samples <- 1\n } else if (min.samples > length(sample.id)) {\n stop(paste0(\"There are only \", length(sample.id), \" samples in the data. Please change the value of `min.samples`! \"))\n }\n if (length(sample.id) >= 2 & min.samples >= 2) {\n if (object@options$parameter$raw.use == TRUE) {\n data <- as.matrix(object@data.signaling)\n } else {\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n stop(\"`object@data.smooth` is missing. Please update the CellChat object via `updateCellChat`! \\n\")\n }\n data <- as.matrix(object@data.smooth)\n }\n data.use <- data/max(data)\n group <- object@idents\n type <- object@options$parameter$type.mean\n trim <- object@options$parameter$trim\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n thresholdedMean = function(x) thresholdedMean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n LR <- dimnames(net$prob)[[3]]\n idx.nonzero <- which(apply(net$prob, 3, sum) != 0)\n LR.nonzero <- LR[idx.nonzero] # only examine the L-R pairs with nonzero communication probabilities.\n\n interaction_input <- object@DB$interaction\n complex_input <- object@DB$complex\n geneIfo <- object@DB$geneInfo\n idx <- match(LR.nonzero, interaction_input$interaction_name)\n geneL <- as.character(interaction_input$ligand[idx])\n geneR <- as.character(interaction_input$receptor[idx])\n\n geneLR <- c(unique(geneL), unique(geneR))\n geneLR <- extractGeneSubset(geneLR, complex_input, geneIfo)\n data.use <- data.use[rownames(data.use) %in% geneLR, ]\n\n score.LR <- array(0, dim = c(nlevels(group),nlevels(group),length(LR.nonzero), length(sample.id)))\n LR.nonzero.all <- c()\n cell.excludes.sample <- c()\n for (i in 1:length(sample.id)) {\n cell.use <- which(sample.info == sample.id[i])\n group.use <- group[cell.use]\n group.use <- droplevels(group.use)\n # get the rare populations with few cells in each sample\n cell.excludes.sample.i <- which(as.numeric(table(object@idents[cell.use])) <= min.cells)\n cell.excludes.sample <- c(cell.excludes.sample, cell.excludes.sample.i)\n # compute average expression per cell group\n data.use.i <- data.use[, cell.use]\n data.use.avg <- aggregate(t(data.use.i), list(group.use), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n group.exist <- which(levels(group) %in% unique(group.use))\n if (length(group.exist) < nlevels(group)) {\n data.use.avg.temp <- matrix(0, nrow = nrow(data.use), ncol = nlevels(group))\n data.use.avg.temp[ , group.exist] <- data.use.avg\n rownames(data.use.avg.temp) <- rownames(data.use.avg)\n data.use.avg <- data.use.avg.temp\n }\n colnames(data.use.avg) <- levels(group)\n # compute the average expression of ligand or receptor in each cell group\n dataLavg <- computeExpr_LR(geneL, data.use.avg, complex_input)\n dataRavg <- computeExpr_LR(geneR, data.use.avg, complex_input)\n # compute the interaction scores for each ligand-receptor pair based on their expression\n for (jj in 1:length(LR.nonzero)) { # It is not good to use parallel here because it will change the order of LR\n score.LR[,,jj,i] <- Matrix::crossprod(matrix(dataLavg[jj, ], nrow = 1), matrix(dataRavg[jj, ], nrow = 1))\n }\n if (length(cell.excludes.sample.i) > 0) {\n cat(paste0(\"The number of cells of the following cell groups in \", sample.id[i], \" sample are less than \", min.cells, \" cells: \",toString(levels(object@idents)[cell.excludes.sample.i]), \"!\",'\\n'))\n score.LR[cell.excludes.sample.i, , , i] <- 0\n score.LR[ ,cell.excludes.sample.i, , i] <- 0\n }\n #LR.nonzero.all <- c(LR.nonzero.all, LR.nonzero[apply(score.LR[ , , , i], 3, sum) != 0])\n }\n #LR.nonzero.jointOnly <- setdiff(LR.nonzero, unique(LR.nonzero.all))\n\n # get the excluded cell groups that are not observed in the merged data, which is very possible for rare populations\n cell.excludes.sample <- unique(cell.excludes.sample)\n if (length(cell.excludes.sample) > 0) {\n cell.excludes.sample <- setdiff(cell.excludes.sample, cell.excludes)\n }\n\n score.LR[score.LR > 0] <- 1 # binarize the interaction score\n score.LR.consitent <- array(0, dim = c(nlevels(group),nlevels(group),length(LR.nonzero)))\n LR.inconsitent <- c()\n for (jj in 1:length(LR.nonzero)) {\n score.LR.sum <- apply(score.LR[ , , jj, ], c(1,2), sum) # elements 2 and 1 means consistent and inconsistent interactions across samples, respectively.\n # set communication probability to be zero for inconsistent interactions across samples\n if (sum((score.LR.sum > 0) * (score.LR.sum < min.samples)) > 0) {\n #LR.inconsitent <- c(LR.inconsitent, LR.nonzero[jj])\n score.LR.consitent <- (score.LR.sum >= min.samples) * 1\n if (rare.keep == TRUE & length(cell.excludes.sample) > 0) {\n score.LR.consitent[cell.excludes.sample, ] <- 1\n score.LR.consitent[ ,cell.excludes.sample] <- 1\n }\n net$prob[ , , LR.nonzero[jj]] <- net$prob[ , , LR.nonzero[jj]] * score.LR.consitent\n }\n }\n num.interaction2 <- sum(net$prob > 0)\n pct.dicrease <- scales::percent((num.interaction1-num.interaction2)/num.interaction1, accuracy = .1)\n cat(paste0(pct.dicrease, \" interactions are removed due to their inconsistence across \", min.samples, \" samples!\",'\\n'))\n }\n\n object@net <- net\n return(object)\n}\n\n\n#' Identify all the significant interactions (L-R pairs) from some cell groups to other cell groups\n#'\n#' @param object CellChat object\n#' @param from a vector giving the index or the name of source cell groups\n#' @param to a corresponding vector giving the index or the name of target cell groups. Note: The length of 'from' and 'to' must be the same, giving the corresponding pair of cell groups for communication.\n#' @param bidirection whether show the bidirectional communication, i.e., both 'from'->'to' and 'to'->'from'.\n#' @param pair.only whether only return ligand-receptor pairs without pathway names and communication strength\n#' @param pairLR.use0 ligand-receptor pairs to use; default is all the significant interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @return\n#' @export\n#'\nidentifyEnrichedInteractions <- function(object, from, to, bidirection = FALSE, pair.only = TRUE, pairLR.use0 = NULL, thresh = 0.05){\n pairwiseLR <- object@net$pairwiseRank\n if (is.null(pairwiseLR)) {\n stop(\"The interactions between pairwise cell groups have not been extracted!\n Please first run `object <- rankNetPairwise(object)`\")\n }\n group.names.all <- names(pairwiseLR)\n if (!is.numeric(from)) {\n from <- match(from, group.names.all)\n if (sum(is.na(from)) > 0) {\n message(\"Some input cell group names in 'from' do not exist!\")\n from <- from[!is.na(from)]\n }\n }\n if (!is.numeric(to)) {\n to <- match(to, group.names.all)\n if (sum(is.na(to)) > 0) {\n message(\"Some input cell group names in 'to' do not exist!\")\n to <- to[!is.na(to)]\n }\n }\n if (length(from) != length(to)) {\n stop(\"The length of 'from' and 'to' must be the same!\")\n }\n if (bidirection) {\n from2 <- c(from, to)\n to <- c(to, from)\n from <- from2\n }\n if (is.null(pairLR.use0)) {\n k <- 0\n pairLR.use0 <- list()\n for (i in 1:length(from)){\n pairwiseLR_ij <- pairwiseLR[[from[i]]][[to[i]]]\n idx <- pairwiseLR_ij$pval < thresh\n if (length(idx) > 0) {\n k <- k +1\n pairLR.use0[[k]] <- pairwiseLR_ij[idx,]\n }\n }\n pairLR.use0 <- do.call(rbind, pairLR.use0)\n }\n\n k <- 0\n pval <- matrix(nrow = length(rownames(pairLR.use0)), ncol = length(from))\n prob <- pval\n group.names <- c()\n for (i in 1:length(from)) {\n k <- k+1\n pairwiseLR_ij <- pairwiseLR[[from[i]]][[to[i]]]\n pairwiseLR_ij <- pairwiseLR_ij[rownames(pairLR.use0),]\n pval_ij <- pairwiseLR_ij$pval\n prob_ij <- pairwiseLR_ij$prob\n pval_ij[pval_ij > 0.05] = 1\n pval_ij[pval_ij > 0.01 & pval_ij <= 0.05] = 2\n pval_ij[pval_ij <= 0.01] = 3\n prob_ij[pval_ij ==1] <- 0\n pval[,k] <- pval_ij\n prob[,k] <- prob_ij\n group.names <- c(group.names, paste(group.names.all[from[i]], group.names.all[to[i]], sep = \" - \"))\n }\n prob[which(prob == 0)] <- NA\n # remove rows that are entirely NA\n pval <- pval[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n pairLR.use0 <- pairLR.use0[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n prob <- prob[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n if (pair.only) {\n pairLR.use0 <- dplyr::select(pairLR.use0, ligand, receptor)\n }\n return(pairLR.use0)\n}\n\n\n#' Compute the region distance based on the spatial locations of each splot/cell of the spatial transcriptomics\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param meta a data frame including at least two columns named `group` and `samples`. `meta$group` is a factor vector defining the regions/labels of each cell/spot. `meta$samples` is a factor vector defining the sample labels of each dataset.\n#' @param interaction.range The maximum interaction/diffusion range of ligands. This hard threshold is used to filter out the connections between spatially distant regions\n#' @param ratio a numerical vector giving the conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns).\n#'\n#' For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates.\n#' For 10X visium, it is the ratio of the theoretical spot size (i.e., 65um) over the number of pixels that span the diameter of a theoretical spot size in the full-resolution image (i.e., 'spot.size.fullres' in the 'scalefactors_json.json' file).\n#' @param tol a numerical vector giving the tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um.\n#'\n#' For example, for 10X visium, `tol` can be set as `65/2`; for slide-seq, `tol` can be set as `10/2`.\n#' If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance.\n#' @param k.min the minimum number of interacting cell pairs required for defining adjacent cell groups\n#' @param contact.dependent Whether determining spatially proximal cell groups based on either the contact.range or the k-nearest neighbors (knn). By default `contact.dependent = TRUE` when inferring contact-dependent and juxtacrine signaling (including ECM-Receptor and Cell-Cell Contact signaling classified in CellChatDB$interaction$annotation).\n#' If only focusing on `Secreted Signaling`, the `contact.dependent` will be automatically set as FALSE except for `contact.dependent.forced = TRUE`.\n#' @param contact.range The interaction range (Unit: microns) to restrict the contact-dependent signaling.\n#' For spatial transcriptomics in a single-cell resolution, `contact.range` is approximately equal to the estimated cell diameter (i.e., the cell center-to-center distance), which means that contact-dependent and juxtacrine signaling can only happens when the two cells are contact to each other.\n#'\n#' Typically, `contact.range = 10`, which is a typical human cell size. However, for low-resolution spatial data such as 10X visium, it should be the cell center-to-center distance (i.e., `contact.range = 100` for visium data). The function `computeCellDistance` can compute the center-to-center distance.\n#'\n#' @param contact.knn.k Number of neighbors to restrict the contact-dependent signaling within the neatest neighbors. By default, CellChat uses `contact.range` to restrict the contact-dependent signaling; however, users can also provide a value of `contact.knn.k`, in order to determine spatially proximal cell groups based on the k-nearest neighbors (knn).\n#' For 10X visium, contact.knn.k = 6. For other spatial technologies, this value may be hard to determine because the sequenced cells/spots are usually not regularly arranged.\n#' @param do.symmetric Whether converting the adjacent matrix into symmetric one when determining spatially proximal cell groups. Default is TRUE, indicating that if adj(i,j) or adj(j,i) is zero, then both are zeros.\n#'\n#' @importFrom BiocNeighbors queryKNN AnnoyParam\n#' @return A list including a square matrix giving the pairwise region distances and an adjacent matrix indicating physically contacting cell groups based on either the contact.range or the k-nearest neighbors\n#'\n#' @export\ncomputeRegionDistance <- function(coordinates, meta,\n interaction.range = NULL, ratio = NULL, tol = NULL, k.min = 10,\n contact.dependent = TRUE, contact.range = NULL, contact.knn.k = NULL, do.symmetric = TRUE\n) {\n trim <- 0.1\n FunMean <- function(x) mean(x, trim = trim, na.rm = TRUE) # This is used for computing the average distance between two cell groups\n group <- meta$group\n numCluster <- nlevels(group)\n level.use <- levels(group)\n level.use <- level.use[level.use %in% unique(group)]\n samples <- meta$samples\n samples.use <- levels(samples)\n d.spatial <- array(NaN, dim = c(numCluster,numCluster,length(samples.use)))\n adj.spatial <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n adj.contact <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n adj.contact.knn <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n\n if (contact.dependent == TRUE & !is.null(contact.knn.k)) {\n ## find the k-nearest neighbors for each single cell\n # my.knn <- FNN::get.knn(coordinates, k = contact.knn.k)\n # nn.ranked <- my.knn$nn.index # this is a matrix with the size of nCell * contact.knn.k\n nn.ranked <- matrix(NA, nrow = nrow(coordinates), ncol = contact.knn.k)\n for (k in 1:length(samples.use)) {\n idx.k <- which(samples == samples.use[k])\n my.knn <- suppressWarnings(BiocNeighbors::findKNN(coordinates[idx.k, ], k = contact.knn.k, BNPARAM = BiocNeighbors::AnnoyParam(), get.index = TRUE))\n nn.ranked[idx.k, ] <- my.knn$index # this is a matrix with the size of nCell * contact.knn.k\n }\n k.min.contact <- k.min\n } else {\n nn.ranked <- matrix(1, nrow = nrow(coordinates), ncol = 1)\n k.min.contact <- -1 # this produces adj.contact.knn with all elements being 1\n }\n if (contact.dependent == TRUE) {\n if (is.null(contact.range) & is.null(contact.knn.k)) {\n stop(\"Please check the documentation of `computeCommunProb` and provide the value of either `contact.range` or `contact.knn.k`\")\n }\n } else {\n contact.range <- 10000 # this produces adj.contact with all elements being 1\n }\n\n for (k in 1:length(samples.use)) {\n idx.k <- samples == samples.use[k]\n for (i in 1:numCluster) {\n for (j in 1:numCluster) {\n idx.i <- which((group == level.use[i]) & idx.k)\n idx.j <- which((group == level.use[j]) & idx.k)\n if (length(idx.i) == 0 | length(idx.j) == 0) {\n next # if one cell group is missing in one sample, just goes to next loop\n }\n data.spatial.i <- coordinates[idx.i, , drop = FALSE]\n data.spatial.j <- coordinates[idx.j, , drop = FALSE]\n # for each point in the i-th cell group, find its 1-nearest neighbor in the j-th cell group\n #qout <- suppressWarnings(BiocNeighbors::queryKNN(data.spatial.j, data.spatial.i, k = 1, BNPARAM = BiocNeighbors::KmknnParam(), get.index = TRUE))\n qout <- suppressWarnings(BiocNeighbors::queryKNN(data.spatial.j, data.spatial.i, k = 1, BNPARAM = BiocNeighbors::AnnoyParam(), get.index = TRUE))\n # qout$index is an one column matrix with length being `length(idx.i)`, which is the index of the 1-nearest neighbor in the j-th cell group defined by `idx.j`\n # qout$distance is an one column matrix with length being `length(idx.i)`, which is the distance to the 1-nearest neighbor in the j-th cell group defined by `idx.j`\n\n # conver the calculated distance into the distance in micrometers\n qout$distance <- qout$distance*ratio[k]\n # long-range distance\n idx <- qout$distance - interaction.range < tol[k]\n adj.spatial[i,j,k] <- (length(unique(qout$index[idx])) >= k.min) * 1\n # short-range distance based on contact.range\n idx2 <- qout$distance - contact.range < tol[k]\n adj.contact[i,j,k] <- (length(unique(qout$index[idx2])) >= k.min) * 1\n # short-range distance based on knn\n knn.i <- unique(as.vector(nn.ranked[idx.i, ]))\n #adj.contact.knn[i,j,k] <- (length(intersect(knn.i, idx.j)) >= k.min.contact) * 1\n adj.contact.knn[i,j,k] <- (length(intersect(knn.i, unique(qout$index[idx]))) >= k.min.contact) * 1 # knn within the long-range distance\n # computing the average distance between two cell groups\n d.spatial[i,j,k] <- FunMean(qout$distance) # since distances are positive values, different ways for computing the mean have little effects.\n\n }\n }\n }\n\n # merged spatial information from different samples\n d.spatial <- apply(d.spatial, c(1,2), function(x) mean(x, na.rm = TRUE))\n adj.spatial <- apply(adj.spatial, c(1,2), mean)\n adj.contact <- apply(adj.contact, c(1,2), mean)\n adj.contact.knn <- apply(adj.contact.knn, c(1,2), mean)\n # for multi-samples analysis, the following is needed\n adj.spatial[adj.spatial > 0] <- 1\n adj.contact[adj.contact > 0] <- 1\n adj.contact.knn[adj.contact.knn > 0] <- 1\n\n # make these adjacent matrix as symmetric\n if (do.symmetric) {\n adj.spatial <- adj.spatial * t(adj.spatial) # if one is zero, then both are zeros.\n adj.contact <- adj.contact * t(adj.contact) # if one is zero, then both are zeros.\n adj.contact.knn <- adj.contact.knn * t(adj.contact.knn) # if one is zero, then both are zeros.\n }\n d.spatial <- (d.spatial + t(d.spatial))/2\n\n # filter out the spatially distant cell groups\n adj.spatial[adj.spatial == 0] <- NaN\n d.spatial <- d.spatial * adj.spatial\n\n rownames(d.spatial) <- levels(group); colnames(d.spatial) <- levels(group)\n\n if (length(contact.knn.k) > 0) {\n adj.contact = adj.contact.knn\n }\n res <- list(d.spatial = d.spatial, adj.contact = adj.contact)\n return(res)\n\n}\n\n#' Compute cell-cell distance based on the spatial coordinates\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param interaction.range The maximum interaction/diffusion range of ligands. This hard threshold is used to filter out the connections between spatially distant cells\n#' @param ratio The conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns).\n#'\n#' For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates.\n#' For 10X visium, it is the ratio of the theoretical spot size (i.e., 65um) over the number of pixels that span the diameter of a theoretical spot size in the full-resolution image (i.e., 'spot.size.fullres' in the 'scalefactors_json.json' file).\n#' @param tol The tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um.\n#'\n#' For example, for 10X visium, `tol` can be set as `65/2`; for slide-seq, `tol` can be set as `10/2`.\n#' If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance.\n#'\n#' @return an object of class \"dist\" giving the pairwise cell-cell distance\n#' @export\n#'\ncomputeCellDistance <- function(coordinates, interaction.range = NULL, ratio = NULL, tol = NULL){\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n d.spatial <- stats::dist(coordinates)\n if (!is.null(ratio)) {\n d.spatial <- d.spatial*ratio\n }\n\n if(!is.null(interaction.range) & !is.null(tol)){\n message(\"\\n Apply a predefined spatial distance threshold based on the interaction length...\")\n d.spatial[d.spatial > (interaction.range + tol)] <- NaN\n }\n return(d.spatial)\n}\n\n\n"], ["/CellChat/R/CellChat_class.R", "\n#' The CellChat Class\n#'\n#' The CellChat object is created from a single-cell transcriptomic data matrix, Seurat V3 or SingleCellExperiment object.\n#' When inputting an data matrix, it takes a digital data matrices as input. Genes should be in rows and cells in columns. rownames and colnames should be included.\n#' The class provides functions for data preprocessing, intercellular communication network inference, communication network analysis, and visualization.\n#'\n#'\n#'# Class definitions\n#' @importFrom methods setClassUnion\n#' @importClassesFrom Matrix dgCMatrix\nsetClassUnion(name = 'AnyMatrix', members = c(\"matrix\", \"dgCMatrix\"))\nsetClassUnion(name = 'AnyFactor', members = c(\"factor\", \"list\"))\n\n#' The key slots used in the CellChat object are described below.\n#'\n#' @slot data.raw raw count data matrix\n#' @slot data normalized data matrix for CellChat analysis (Genes should be in rows and cells in columns)\n#' @slot data.signaling a subset of normalized matrix only containing signaling genes\n#' @slot data.scale scaled data matrix\n#' @slot data.smooth smoothed data\n#' @slot images a list of information of spatial transcriptomics data\n#' @slot net a three-dimensional array P (K×K×N), where K is the number of cell groups and N is the number of ligand-receptor pairs. Each row of P indicates the communication probability originating from the sender cell group to other cell groups.\n#' @slot netP a three-dimensional array representing cel-cell communication networks on a signaling pathway level\n#' @slot DB ligand-receptor interaction database used in the analysis (a subset of CellChatDB)\n#' @slot LR a list of information related with ligand-receptor pairs\n#' @slot meta data frame storing the information associated with each cell\n#' @slot idents a factor defining the cell identity used for all analysis. It becomes a list for a merged CellChat object\n#' @slot var.features A list: one element is a vector consisting of the identified over-expressed signaling genes; one element is a data frame returned from the differential expression analysis\n#' @slot dr List of the reduced 2D coordinates, one per method, e.g., umap/tsne/dm\n#' @slot options List of miscellaneous data, such as parameters used throughout analysis, and a indicator whether the CellChat object is a single or merged\n#'\n#' @exportClass CellChat\n#' @importFrom Rcpp evalCpp\n#' @importFrom methods setClass\n# #' @useDynLib CellChat\nCellChat <- methods::setClass(\"CellChat\",\n slots = c(data.raw = 'AnyMatrix',\n data = 'AnyMatrix',\n data.signaling = \"AnyMatrix\",\n data.scale = \"matrix\",\n data.smooth = \"AnyMatrix\",\n images = \"list\",\n net = \"list\",\n netP = \"list\",\n meta = \"data.frame\",\n idents = \"AnyFactor\",\n DB = \"list\",\n LR = \"list\",\n var.features = \"list\",\n dr = \"list\",\n options = \"list\")\n)\n#' show method for CellChat\n#'\n#' @param CellChat object\n#' @param show show the object\n#' @param object object\n#' @docType methods\n#'\nsetMethod(f = \"show\", signature = \"CellChat\", definition = function(object) {\n if (object@options$mode == \"single\") {\n cat(\"An object of class\", class(object), \"created from a single dataset\", \"\\n\", nrow(object@data), \"genes.\\n\", ncol(object@data), \"cells. \\n\")\n } else if (object@options$mode == \"merged\") {\n cat(\"An object of class\", class(object), \"created from a merged object with multiple datasets\", \"\\n\", nrow(object@data.signaling), \"signaling genes.\\n\", ncol(object@data.signaling), \"cells. \\n\")\n }\n if (object@options$datatype == \"RNA\") {\n cat(\"CellChat analysis of single cell RNA-seq data! \\n\")\n } else {\n cat(\"CellChat analysis of\", object@options$datatype, \"data! The input spatial locations are \\n\")\n print(head(object@images$coordinates))\n }\n\n\n invisible(x = NULL)\n})\n\n\n\n#' Create a new CellChat object from a data matrix, Seurat or SingleCellExperiment object\n#'\n#' @param object a normalized (NOT count) data matrix (genes by cells), Seurat or SingleCellExperiment object\n#' @param meta a data frame (rows are cells with rownames) consisting of cell information, which will be used for defining cell groups.\n#' If input is a Seurat or SingleCellExperiment object, the meta data in the object will be used\n#' @param group.by a char name of the variable in meta data, defining cell groups.\n#' If input is a data matrix and group.by is NULL, the input `meta` should contain a column named 'labels',\n#' If input is a Seurat or SingleCellExperiment object, USER must provide `group.by` to define the cell groups. e.g, group.by = \"ident\" for Seurat object\n#' @param datatype By default datatype = \"RNA\"; when running CellChat on spatial imaging data, set datatype = \"spatial\" and input `spatial.factors`\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param spatial.factors a data frame containing two distance factors `ratio` and `tol`, which is dependent on spatial transcriptomics technologies (and specific datasets).\n#'\n#' USER must input this data frame when datatype = \"spatial\". spatial.factors must contain an element named `ratio`, which is the conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns). For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates,\n#'\n#' and another element named `tol`, which is the tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um. If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the cell center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance. Of note, CellChat does not need an accurate tolerance factor, which is used for determining whether considering the cell-pair as spatially proximal if their distance is greater than `interaction.range` but smaller than \"`interaction.range` + `tol`\".\n#'\n#'\n#' @param assay Assay to use when the input is a Seurat or SingleCellExperiment object. NB: The data in the `integrated` assay in Seurat is not suitable for CellChat analysis because it contains negative values.\n#' @param do.sparse whether use sparse format\n#'\n#' @return\n#' @export\n#' @importFrom methods as new\n#' @examples\n#' \\dontrun{\n#' Create a CellChat object from single-cell transcriptomics data\n#' # Input is a data matrix\n#' ## create a dataframe consisting of the cell labels\n#' meta = data.frame(labels = cell.labels, row.names = names(cell.labels))\n#' cellChat <- createCellChat(object = data.input, meta = meta, group.by = \"labels\")\n#'\n#' # input is a Seurat object\n#' ## use the default cell identities of Seurat object\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"ident\", assay = \"RNA\")\n#' ## use other meta information as cell groups\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"seurat.clusters\")\n#'\n#' # input is a SingleCellExperiment object\n#' cellChat <- createCellChat(object = sce.obj, group.by = \"sce.clusters\")\n#'\n#' # input is a AnnData object\n#' sce <- zellkonverter::readH5AD(file = \"adata.h5ad\")\n#' assayNames(sce) # retrieve all the available assays within sce object\n#' counts <- assay(sce, \"X\") # add a new assay entry \"logcounts\" if not available and make sure this is the original count data matrix\n#' library.size <- Matrix::colSums(counts)\n#' logcounts(sce) <- log1p(Matrix::t(Matrix::t(counts)/library.size) * 10000)\n#' meta <- as.data.frame(SingleCellExperiment::colData(sce))\n#' cellChat <- createCellChat(object = sce, group.by = \"sce.clusters\")\n#'\n#'\n#' Create a CellChat object from spatial transcriptomics data\n#' # Input is a data matrix\n#' cellChat <- createCellChat(object = data.input, meta = meta, group.by = \"labels\",\n#' datatype = \"spatial\", coordinates = coordinates, spatial.factors = spatial.factors)\n#'\n#' # input is a Seurat object\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"ident\", assay = \"SCT\",\n#' datatype = \"spatial\", spatial.factors = spatial.factors)\n#'\n#' }\ncreateCellChat <- function(object, meta = NULL, group.by = NULL,\n datatype = c(\"RNA\", \"spatial\"), coordinates = NULL, spatial.factors = NULL,\n assay = NULL, do.sparse = T) {\n datatype <- match.arg(datatype)\n # data matrix as input\n if (inherits(x = object, what = c(\"matrix\", \"Matrix\", \"dgCMatrix\", \"dgRMatrix\",\"CsparseMatrix\"))) {\n print(\"Create a CellChat object from a data matrix\")\n data <- object\n if (is.null(group.by)) {\n group.by <- \"labels\"\n }\n }\n # Seurat object as input\n if (is(object,\"Seurat\")) {\n .error_if_no_Seurat()\n print(\"Create a CellChat object from a Seurat object\")\n if (is.null(assay)) {\n assay = Seurat::DefaultAssay(object)\n if (assay == \"integrated\") {\n warning(\"The data in the `integrated` assay is not suitable for CellChat analysis! Please use the `RNA`, `SCT` or `Spatial` assay! \")\n }\n cat(paste0(\"The `data` slot in the default assay is used. The default assay is \", assay),'\\n')\n }\n if (packageVersion(\"Seurat\") < \"5.0.0\") {\n # data <- Seurat::GetAssayData(object, assay = assay, slot = \"data\") # normalized data matrix\n data <- object[[assay]]@data\n } else {\n data <- object[[assay]]$data\n }\n if (min(data) < 0) {\n stop(\"The data matrix contains negative values. Please ensure the normalized data matrix is used.\")\n }\n if (is.null(meta)) {\n cat(\"The `meta.data` slot in the Seurat object is used as cell meta information\",'\\n')\n meta <- object@meta.data\n meta$ident <- Seurat::Idents(object)\n }\n if (is.null(group.by)) {\n group.by <- \"ident\"\n }\n if (datatype %in% c(\"spatial\")) {\n if (is.null(coordinates)) {\n coordinates <- Seurat::GetTissueCoordinates(object, scale = NULL, cols = c(\"imagerow\", \"imagecol\"))\n }\n }\n\n\n }\n # SingleCellExperiment object as input\n if (is(object,\"SingleCellExperiment\")) {\n print(\"Create a CellChat object from a SingleCellExperiment object\")\n if (is.null(assay)) {\n assay = \"logcounts\"\n }\n if (assay %in% SummarizedExperiment::assayNames(object)) {\n cat(paste0(\"The data in the \", assay, \" assay is used! \"),'\\n')\n data <- SummarizedExperiment::assay(object, assay)\n } else {\n stop(\"SingleCellExperiment object must contain an assay named `logcounts` or the input assay name! Please check the available assaynames via `assayNames(object)`. \\n\")\n }\n if (is.null(meta)) {\n cat(\"The `colData` assay in the SingleCellExperiment object is used as cell meta information\",'\\n')\n meta <- as.data.frame(SingleCellExperiment::colData(object))\n }\n if (is.null(group.by)) {\n stop(\"`group.by` should be defined!\")\n }\n }\n\n if (!inherits(x = data, what = c(\"dgCMatrix\")) & do.sparse) {\n if (inherits(x = data, what = c(\"dgRMatrix\"))) {\n data <- as(data, \"CsparseMatrix\")\n }\n data <- as(data, \"dgCMatrix\")\n }\n\n if (!is.null(meta)) {\n if (inherits(x = meta, what = c(\"matrix\", \"Matrix\",\"DataFrame\"))) {\n meta <- as.data.frame(x = meta)\n }\n if (!is.data.frame(meta)) {\n stop(\"The input `meta` should be a data frame\")\n }\n if (!identical(rownames(meta), colnames(data))) {\n cat(\"The cell barcodes in 'meta' is \", head(rownames(meta)),'\\n')\n warning(\"The cell barcodes in 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of 'mata'!\")\n rownames(meta) <- colnames(data)\n }\n } else {\n meta <- data.frame()\n }\n if (datatype %in% c(\"spatial\")) {\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n if (is.null(spatial.factors) | !(\"ratio\" %in% names(spatial.factors)) | !(\"tol\" %in% names(spatial.factors))) {\n stop(\"spatial.factors with colnames `ratio` and `tol` should be provided!\")\n } else {\n images = list(\"coordinates\" = coordinates,\n \"spatial.factors\" = spatial.factors)\n }\n cat(\"Create a CellChat object from spatial transcriptomics data...\",'\\n')\n } else {\n images <- list()\n }\n\n object <- methods::new(Class = \"CellChat\",\n data = data,\n images = images,\n meta = meta)\n\n if (!is.null(meta) & nrow(meta) > 0) {\n if (!(\"samples\" %in% colnames(meta))) {\n warning(\"The 'meta' data does not have a column named `samples`. We now add this column and all cells are assumed to belong to `sample1`! \\n\")\n meta$samples <- \"sample1\"\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n } else if (is.factor(meta$samples) == FALSE) {\n warning(\"The 'meta$samples' is not a factor. We now force it as a factor! \\n\")\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n }\n\n cat(\"Set cell identities for the new CellChat object\", '\\n')\n if (!(group.by %in% colnames(meta))) {\n stop(\"The 'group.by' is not a column name in the `meta`, which will be used for cell grouping.\")\n }\n object <- setIdent(object, ident.use = group.by) # set \"labels\" as default cell identity\n cat(\"The cell groups used for CellChat analysis are \", toString(levels(object@idents)), '\\n')\n }\n\n object@options$mode <- \"single\"\n object@options$datatype <- datatype\n return(object)\n}\n\n\n#' Merge CellChat objects\n#'\n#' @param object.list A list of multiple CellChat objects\n#' @param add.names A vector containing the name of each dataset\n#' @param merge.data whether merging the data for ALL genes. Default only merges the data of signaling genes\n#' @param cell.prefix whether prefix cell names\n#' @importFrom methods slot new\n#'\n#' @return\n#' @export\n#'\n#' @examples\nmergeCellChat <- function(object.list, add.names = NULL, merge.data = FALSE, cell.prefix = FALSE) {\n if (is.null(add.names)) {\n add.names <- paste(\"Dataset\",1:length(object.list),sep = \"_\")\n }\n slot.name <- c(\"net\", \"netP\", \"idents\" ,\"LR\", \"var.features\", \"images\")\n slot.combined <- vector(\"list\", length(slot.name))\n names(slot.combined) <- slot.name\n for (i in 1:length(slot.name)) {\n object.slot <- vector(\"list\", length(object.list))\n for (j in 1:length(object.list)) {\n object.slot[[j]] <- slot(object.list[[j]], slot.name[i])\n }\n slot.combined[[i]] <- object.slot\n names(slot.combined[[i]]) <- add.names\n }\n\n if (cell.prefix) {\n warning(\"Prefix cell names!\")\n for (i in 1:length(object.list)) {colnames(object.list[[i]]@data) <- paste(colnames(object.list[[i]]@data), add.names[i], sep = \"_\")}\n } else {\n cell.names <- c()\n for (i in 1:length(object.list)) {\n cell.names <- c(cell.names, colnames(object.list[[i]]@data))\n }\n if (sum(duplicated(cell.names))) {\n stop(\"Duplicated cell names were detected across datasets!! Please set cell.prefix = TRUE\")\n }\n }\n\n meta.use <- colnames(object.list[[1]]@meta)\n for (i in 2:length(object.list)) {\n meta.use <- meta.use[meta.use %in% colnames(object.list[[i]]@meta)]\n }\n\n dataset.name <- c()\n cell.names <- c()\n meta.joint <- data.frame()\n for (i in 1:length(object.list)) {\n dataset.name <- c(dataset.name, rep(add.names[i], length(colnames(object.list[[i]]@data))))\n cell.names <- c(cell.names, colnames(object.list[[i]]@data))\n meta.joint <- rbind(meta.joint, object.list[[i]]@meta[ , meta.use, drop = FALSE])\n }\n if (!identical(rownames(meta.joint), cell.names)) {\n cat(\"The cell barcodes in merged 'meta' is \", head(rownames(meta.joint)),'\\n')\n warning(\"The cell barcodes in merged 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of merged 'mata'!\")\n rownames(meta.joint) <- cell.names\n }\n\n #dataset.name <- data.frame(dataset.name = dataset.name, row.names = cell.names)\n meta.joint$datasets <- factor(dataset.name, levels = add.names)\n\n genes.use <- rownames(object.list[[1]]@data)\n for (i in 2:length(object.list)) {\n genes.use <- genes.use[genes.use %in% rownames(object.list[[i]]@data)]\n }\n data.joint <- c()\n for (i in 1:length(object.list)) {\n data.joint <- cbind(data.joint, object.list[[i]]@data[genes.use, ])\n }\n gene.signaling.joint = unique(unlist(lapply(object.list, function(x) rownames(x@data.signaling))))\n data.signaling.joint <- data.joint[rownames(data.joint) %in% gene.signaling.joint, ]\n\n idents.joint <- c()\n idents.levels <- c()\n for (i in 1:length(object.list)) {\n idents.joint <- c(idents.joint, as.character(object.list[[i]]@idents))\n idents.levels <- union(idents.levels, levels(object.list[[i]]@idents))\n }\n names(idents.joint) <- cell.names\n idents.joint <- factor(idents.joint, levels = idents.levels)\n slot.combined$idents$joint <- idents.joint\n\n if (merge.data) {\n message(\"Merge the following slots: 'data','data.signaling','images','net', 'netP','meta', 'idents', 'var.features', 'DB', and 'LR'.\")\n merged.object <- methods::new(\n Class = \"CellChat\",\n data = data.joint,\n data.signaling = data.signaling.joint,\n images = slot.combined$images,\n net = slot.combined$net,\n netP = slot.combined$netP,\n meta = meta.joint,\n idents = slot.combined$idents,\n var.features = slot.combined$var.features,\n LR = slot.combined$LR,\n DB = object.list[[1]]@DB)\n } else {\n message(\"Merge the following slots: 'data.signaling','images','net', 'netP','meta', 'idents', 'var.features' , 'DB', and 'LR'.\")\n merged.object <- methods::new(\n Class = \"CellChat\",\n data.signaling = data.signaling.joint,\n images = slot.combined$images,\n net = slot.combined$net,\n netP = slot.combined$netP,\n meta = meta.joint,\n idents = slot.combined$idents,\n var.features = slot.combined$var.features,\n LR = slot.combined$LR,\n DB = object.list[[1]]@DB)\n }\n merged.object@options$mode <- \"merged\"\n\n datatype.joint <- c()\n for (j in 1:length(object.list)) {\n datatype.joint <- union(datatype.joint, slot(object.list[[j]], \"options\")$datatype)\n }\n if (length(datatype.joint) == 1){\n merged.object@options$datatype <- datatype.joint\n } else {\n message(\"The data types in these objects are \", datatype.joint,'\\n')\n stop(\"Comparison analysis is not suggested for different types of data.\")\n }\n return(merged.object)\n}\n\n\n\n#' Update a single CellChat object\n#'\n#' Update a single previously calculated CellChat object for spatial transcriptomics data analysis (version < 2.1.0)\n#'\n#' Update a single previously calculated CellChat object (version < 1.6.0)\n#'\n#' version < 0.5.0: `object@var.features` is now `object@var.features$features`; `object@net$sum` is now `object@net$weight` if `aggregateNet` has been run.\n#'\n#' version 1.6.0: a `object@images` slot is added and `datatype` is added in `object@options$datatype`\n#'\n#' version 2.1.0: a column named `slices` is added in `meta` data for spatial transcriptomics data analysis.\n#'\n#' version 2.1.1: `images$scale.factors` is changed to `images$spatial.factors` for spatial transcriptomics data analysis.\n#'\n#' version 2.1.2: the column `slices` in `object@meta` is renamed as `samples` in order to identify consistent signaling across samples for cell-cell communication analysis.\n#'\n#' version 2.1.3: the slot `object@data.project` is renamed as `object@data.smooth`.\n#'\n#' @param object CellChat object\n#'\n#' @return a updated CellChat object\n#' @export\n#'\nupdateCellChat <- function(object) {\n DB <- object@DB\n # interaction_input <- DB$interaction\n # if ((\"category\" %in% colnames(interaction_input) == FALSE) & (\"annotation\" %in% colnames(interaction_input) == TRUE)) {\n # message(\"Change the column name `annotation` in object@DB$interaction to `category` since CellChat v2\")\n # colnames(interaction_input) <- plyr::mapvalues(colnames(interaction_input),from = c(\"annotation\"), to = c(\"category\"), warn_missing = TRUE)\n # DB$interaction <- interaction_input\n # }\n if (is.character(object@var.features)) {\n message(\"Update slot 'var.features' from a vector to a list\")\n var.features.new <- list(features = object@var.features)\n } else {\n var.features.new <- object@var.features\n }\n if (\"sum\" %in% names(object@net)) {\n net <- object@net\n net$weight <- net$sum\n } else {\n net <- object@net\n }\n if (!(\"mode\" %in% names(object@options))) {\n object@options$mode <- \"single\"\n }\n if (!(\"datatype\" %in% names(object@options))) {\n object@options$datatype <- \"RNA\"\n images = list()\n } else {\n images = object@images\n }\n meta = object@meta\n if (\"slices\" %in% colnames(meta)) {\n meta$samples <- meta$slices\n meta$slices = NULL\n }\n if (!(\"samples\" %in% colnames(meta))) {\n warning(\"The 'meta' data does not have a column named `samples`. We now add this column and all cells are assumed to belong to `sample1`!\")\n meta$samples <- \"sample1\"\n meta$samples <- factor(meta$samples)\n } else if (is.factor(meta$samples) == FALSE) {\n warning(\"The 'meta$samples' is not a factor. We now force it as a factor!\")\n meta$samples <- factor(meta$samples)\n }\n if (object@options$datatype %in% c(\"spatial\")) {\n if (\"scale.factors\" %in% names(object@images)) {\n images$spatial.factors <- as.data.frame(images$scale.factors)\n images$scale.factors <- NULL\n }\n }\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n data.smooth <- object@data.project\n } else {\n data.smooth <- object@data.smooth\n }\n object.new <- methods::new(\n Class = \"CellChat\",\n data.raw = object@data.raw,\n data = object@data,\n data.signaling = object@data.signaling,\n data.scale = object@data.scale,\n data.smooth = data.smooth,\n images = images,\n net = net,\n netP = object@netP,\n meta = meta,\n idents = object@idents,\n DB = DB,\n LR = object@LR,\n var.features = var.features.new,\n dr = object@dr,\n options = object@options\n )\n return(object.new)\n}\n\n#' Update a CellChat object by lifting up the cell groups to the same cell labels across all datasets\n#'\n#' This function is useful when comparing inferred communications across different datasets with different cellular compositions\n#'\n#' @param object A single or merged CellChat object\n#' @param group.new A char vector giving the cell labels to lift up. The order of cell labels in the vector will be used for setting the new cell identity.\n#'\n#' If the input is a merged CellChat object and group.new = NULL, it will use the cell labels from one dataset with the maximum number of cell groups\n#'\n#' If the input is a single CellChat object, `group.new` must be defined.\n#'\n#' @return a updated CellChat object\n#'\n#' @export\n#'\nliftCellChat <- function(object, group.new = NULL) {\n if (object@options$mode == \"merged\") {\n idents <- object@idents[1:(length(object@idents)-1)]\n if (is.null(group.new)) {\n group.max.all <- unique(unlist(sapply(idents, levels)))\n group.num <- sapply(idents, nlevels)\n group.num.max <- max(group.num)\n group.max <- levels(idents[[which(group.num == group.num.max)]])\n if (length(group.max) != length(group.max.all)) {\n stop(\"CellChat object cannot lift up due to the missing cell groups in any dataset. Please define the parameter `group.new`!\")\n }\n } else {\n group.max <- group.new\n group.num.max <- length(group.new)\n }\n message(paste0(\"The CellChat object will be lifted up using the cell labels \", paste(group.max, collapse=\", \")))\n for (i in 1:length(idents)) {\n cat(\"Update slots object@net, object@netP, object@idents in dataset \", names(object@idents)[i],'\\n')\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net[[i]]\n group.i <- levels(idents[[i]])\n # group.existing <- group.max[group.max %in% group.i]\n group.existing <- group.i[group.i %in% group.max]\n group.existing.index <- which(group.max %in% group.existing)\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max),\n dimnames = list(group.max, group.max))\n values.new[group.existing.index, group.existing.index] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"pairwiseRank\")) {\n for (k in 1:length(values)) {\n values.new1 <- vector(\"list\", group.num.max)\n values.new1[group.existing.index] <- values[[k]]\n temp <- values[[k]][[1]]\n temp$prob <- 0; temp$pval <- 1\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new1[[kk]] <- temp\n }\n names(values.new1) <- group.max\n values[[k]] <- values.new1\n }\n values.new <- vector(\"list\", group.num.max)\n values.new[group.existing.index] <- values\n temp <- lapply(values.new1, function(x) {\n x$prob <- 0; x$pval <- 1\n return(x)\n })\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new[[kk]] <- temp\n }\n names(values.new) <- group.max\n }\n net[[net.j]] <- values.new\n }\n object@net[[i]] <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n netP <- object@netP[[i]]\n for (netP.j in names(netP)) {\n values <- netP[[netP.j]]\n if (netP.j %in% c(\"pathways\")) {\n values.new <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"prob\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"centr\")) {\n for (k in 1:length(values)) {\n values.new <- lapply(values, function(x) {\n values.new2 <- lapply(x, function(x) {\n values.new1 = as.vector(matrix(0, nrow = 1, ncol = group.num.max))\n values.new1[group.existing.index] <- x\n names(values.new1) <- group.max\n return(values.new1)\n })\n names(values.new2) <- names(x)\n return(values.new2)\n })\n names(values.new) <- names(values)\n }\n netP[[netP.j]] <- values.new\n }\n\n }\n object@netP[[i]] <- netP\n # cat(\"Update slot object@idents...\", '\\n')\n # idents[[i]] <- factor(group.max, levels = group.max)\n idents[[i]] <- factor(idents[[i]], levels = group.max)\n }\n object@idents[1:(length(object@idents)-1)] <- idents\n } else {\n if (is.null(group.new)) {\n stop(\"Please define the parameter `group.new`!\")\n } else {\n group.max <- as.character(group.new)\n group.num.max <- length(group.new)\n message(paste0(\"The CellChat object will be lifted up using the cell labels \", paste(group.max, collapse=\", \")))\n }\n cat(\"Update slots object@net, object@netP, object@idents in a single dataset...\", '\\n')\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net\n idents <- object@idents\n group.i <- levels(idents)\n # group.existing <- group.max[group.max %in% group.i]\n group.existing <- group.i[group.i %in% group.max]\n group.existing.index <- which(group.max %in% group.existing)\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max),\n dimnames = list(group.max, group.max))\n values.new[group.existing.index, group.existing.index] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"pairwiseRank\")) {\n for (k in 1:length(values)) {\n values.new1 <- vector(\"list\", group.num.max)\n values.new1[group.existing.index] <- values[[k]]\n temp <- values[[k]][[1]]\n temp$prob <- 0; temp$pval <- 1\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new1[[kk]] <- temp\n }\n names(values.new1) <- group.max\n values[[k]] <- values.new1\n }\n values.new <- vector(\"list\", group.num.max)\n values.new[group.existing.index] <- values\n temp <- lapply(values.new1, function(x) {\n x$prob <- 0; x$pval <- 1\n return(x)\n })\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new[[kk]] <- temp\n }\n names(values.new) <- group.max\n }\n net[[net.j]] <- values.new\n }\n object@net <- net\n\n\n # cat(\"Update slot object@netP...\", '\\n')\n netP <- object@netP\n for (netP.j in names(netP)) {\n values <- netP[[netP.j]]\n if (netP.j %in% c(\"pathways\")) {\n values.new <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"prob\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"centr\")) {\n for (k in 1:length(values)) {\n values.new <- lapply(values, function(x) {\n values.new2 <- lapply(x, function(x) {\n values.new1 = as.vector(matrix(0, nrow = 1, ncol = group.num.max))\n values.new1[group.existing.index] <- x\n names(values.new1) <- group.max\n return(values.new1)\n })\n names(values.new2) <- names(x)\n return(values.new2)\n })\n names(values.new) <- names(values)\n }\n }\n netP[[netP.j]] <- values.new\n }\n object@netP <- netP\n\n # cat(\"Update slot object@idents...\", '\\n')\n idents <- factor(idents, levels = group.max)\n object@idents <- idents\n }\n\n return(object)\n}\n\n\n#' Subset CellChat object using a portion of cells\n#'\n#' @param object A CellChat object (either an object from a single dataset or a merged objects from multiple datasets)\n#' @param cells.use a char vector giving the cell barcodes to subset. If cells.use = NULL, USER must define `idents.use`\n#' @param idents.use a subset of cell groups used for analysis\n#' @param group.by cell group information; default is `object@idents`; otherwise it should be one of the column names of the meta slot\n#' @param invert whether invert the idents.use\n#' @param thresh threshold of the p-value for determining significant interaction. A parameter as an input of the function `computeCommunProbPathway`\n#' @importFrom methods slot new\n#'\n#' @return\n#' @export\n#'\nsubsetCellChat <- function(object, cells.use = NULL, idents.use = NULL, group.by = NULL, invert = FALSE, thresh = 0.05) {\n if (!is.null(idents.use)) {\n if (is.null(group.by)) {\n labels <- object@idents\n if (object@options$mode == \"merged\") {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n level.use0 <- levels(labels)\n level.use <- levels(labels)[levels(labels) %in% unique(labels)]\n\n if (invert) {\n level.use <- level.use[!(level.use %in% idents.use)]\n } else {\n level.use <- level.use[level.use %in% idents.use]\n }\n cells.use.index <- which(as.character(labels) %in% level.use)\n cells.use <- names(labels)[cells.use.index]\n } else if (!is.null(cells.use)) {\n labels <- object@idents\n if (object@options$mode == \"merged\") {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n level.use0 <- levels(labels)\n level.use <- levels(labels)[levels(labels) %in% unique(as.character(labels[cells.use]))]\n cells.use.index <- which(names(labels) %in% cells.use)\n } else {\n stop(\"USER should define either `cells.use` or `idents.use`!\")\n }\n cat(\"The subset of cell groups used for CellChat analysis are \", level.use, '\\n')\n\n if (nrow(object@data) > 0) {\n data.subset <- object@data[, cells.use.index]\n } else {\n data.subset <- matrix(0, nrow = 0, ncol = 0)\n }\n if (nrow(object@data.smooth) > 0) {\n data.smooth.subset <- object@data.smooth[, cells.use.index]\n } else {\n data.smooth.subset <- matrix(0, nrow = 0, ncol = 0)\n }\n data.signaling.subset <- object@data.signaling[, cells.use.index]\n\n meta.subset <- object@meta[cells.use.index, , drop = FALSE]\n\n\n if (object@options$mode == \"merged\") {\n idents <- object@idents[1:(length(object@idents)-1)]\n group.existing <- level.use0[level.use0 %in% level.use]\n group.existing.index <- which(level.use0 %in% level.use)\n net.subset <- vector(\"list\", length = length(object@net))\n netP.subset <- vector(\"list\", length = length(object@netP))\n idents.subset <- vector(\"list\", length = length(idents))\n names(net.subset) <- names(object@net)\n names(netP.subset) <- names(object@netP)\n names(idents.subset) <- names(object@idents[1:(length(object@idents)-1)])\n images.subset <- vector(\"list\", length = length(idents))\n names(images.subset) <- names(object@idents[1:(length(object@idents)-1)])\n\n for (i in 1:length(idents)) {\n cat(\"Update slots object@images, object@net, object@netP, object@idents in dataset \", names(object@idents)[i],'\\n')\n images <- object@images[[i]]\n for (images.j in names(images)) {\n values <- images[[images.j]]\n if (images.j %in% c(\"coordinates\")) {\n values.new <- values[cells.use.index, ]\n images[[images.j]] <- values.new\n }\n if (images.j %in% c(\"distance\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n images[[images.j]] <- values.new\n }\n }\n images.subset[[i]] <- images\n\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net[[i]]\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- values[group.existing.index, group.existing.index, , drop = FALSE]\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n net[[net.j]] <- values.new\n }\n # net[[net.j]] <- values.new\n }\n net.subset[[i]] <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n # netP <- object@netP[[i]]\n # for (netP.j in names(netP)) {\n # values <- netP[[netP.j]]\n # if (netP.j %in% c(\"pathways\")) {\n # values.new <- values\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"prob\")) {\n # values.new <- values[group.existing.index, group.existing.index, ]\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"centr\")) {\n # for (k in 1:length(values)) {\n # values.new <- lapply(values, function(x) {\n # values.new2 <- lapply(x, function(x) {\n # values.new1 <- x[group.existing.index]\n # names(values.new1) <- group.existing\n # return(values.new1)\n # })\n # names(values.new2) <- names(x)\n # return(values.new2)\n # })\n # names(values.new) <- names(values)\n # }\n # }\n # netP[[netP.j]] <- values.new\n # }\n netP = computeCommunProbPathway(net = net.subset[[i]], pairLR.use = object@LR[[i]]$LRsig, thresh = thresh)\n netP$centr = netAnalysis_computeCentrality(net = net.subset[[i]]$prob)\n netP.subset[[i]] <- netP\n idents.subset[[i]] <- idents[[i]][names(idents[[i]]) %in% cells.use]\n idents.subset[[i]] <- factor(idents.subset[[i]], levels = levels(idents[[i]])[levels(idents[[i]]) %in% level.use])\n }\n idents.subset$joint <- factor(object@idents$joint[cells.use.index], levels = level.use)\n\n } else {\n cat(\"Update slots object@images, object@net, object@netP in a single dataset...\", '\\n')\n\n group.existing <- level.use0[level.use0 %in% level.use]\n group.existing.index <- which(level.use0 %in% level.use)\n\n images <- object@images\n for (images.j in names(images)) {\n values <- images[[images.j]]\n if (images.j %in% c(\"coordinates\")) {\n values.new <- values[cells.use.index, ]\n images[[images.j]] <- values.new\n }\n if (images.j %in% c(\"distance\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n images[[images.j]] <- values.new\n }\n }\n images.subset <- images\n\n\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- values[group.existing.index, group.existing.index, , drop = FALSE]\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n net[[net.j]] <- values.new\n }\n }\n net.subset <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n # netP <- object@netP\n # for (netP.j in names(netP)) {\n # values <- netP[[netP.j]]\n # if (netP.j %in% c(\"pathways\")) {\n # values.new <- values\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"prob\")) {\n # values.new <- values[group.existing.index, group.existing.index, ]\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"centr\")) {\n # for (k in 1:length(values)) {\n # values.new <- lapply(values, function(x) {\n # values.new2 <- lapply(x, function(x) {\n # values.new1 <- x[group.existing.index]\n # names(values.new1) <- group.existing\n # return(values.new1)\n # })\n # names(values.new2) <- names(x)\n # return(values.new2)\n # })\n # names(values.new) <- names(values)\n # }\n # }\n # netP[[netP.j]] <- values.new\n # }\n netP = computeCommunProbPathway(net = net.subset, pairLR.use = object@LR$LRsig, thresh = thresh)\n netP$centr = netAnalysis_computeCentrality(net = net.subset$prob)\n netP.subset <- netP\n idents.subset <- object@idents[cells.use.index]\n idents.subset <- factor(idents.subset, levels = level.use)\n }\n\n\n object.subset <- methods::new(\n Class = \"CellChat\",\n data = data.subset,\n data.signaling = data.signaling.subset,\n data.smooth = data.smooth.subset,\n images = images.subset,\n net = net.subset,\n netP = netP.subset,\n meta = meta.subset,\n idents = idents.subset,\n var.features = object@var.features,\n LR = object@LR,\n DB = object@DB,\n options = object@options\n )\n return(object.subset)\n}\n\n\n"], ["/CellChat/R/database.R", "#' Show the description of CellChatDB databse\n#'\n#' @param CellChatDB CellChatDB databse\n#' @param nrow the number of rows in the plot\n#' @importFrom dplyr group_by summarise n %>%\n#'\n#' @return\n#' @export\n#'\nshowDatabaseCategory <- function(CellChatDB, nrow = 1) {\n interaction_input <- CellChatDB$interaction\n geneIfo <- CellChatDB$geneInfo\n df <- interaction_input %>% group_by(annotation) %>% summarise(value=n())\n #df$group <- factor(df$annotation, levels = unique(df$annotation))\n df$group <- factor(df$annotation, levels = c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\"))\n gg1 <- pieChart(df)\n binary <- (interaction_input$ligand %in% geneIfo$Symbol) & (interaction_input$receptor %in% geneIfo$Symbol)\n df <- data.frame(group = rep(\"Heterodimers\", dim(interaction_input)[1]),stringsAsFactors = FALSE)\n df$group[binary] <- rep(\"Others\",sum(binary),1)\n df <- df %>% group_by(group) %>% summarise(value=n())\n df$group <- factor(df$group, levels = c(\"Heterodimers\",\"Others\"))\n gg2 <- pieChart(df)\n\n kegg <- grepl(\"KEGG\", interaction_input$evidence)\n df <- data.frame(group = rep(\"Literature\", dim(interaction_input)[1]),stringsAsFactors = FALSE)\n df$group[kegg] <- rep(\"KEGG\",sum(kegg),1)\n df <- df %>% group_by(group) %>% summarise(value=n())\n df$group <- factor(df$group, levels = c(\"KEGG\",\"Literature\"))\n gg3 <- pieChart(df)\n\n gg <- cowplot::plot_grid(gg1, gg2, gg3, nrow = nrow, align = \"h\", rel_widths = c(1, 1,1))\n return(gg)\n}\n\n\n#' Plot pie chart\n#'\n#' @param df a dataframe\n#' @param label.size a character\n#' @param color.use the name of the variable in CellChatDB interaction_input\n#' @param title the title of plot\n#' @import ggplot2\n#' @importFrom scales percent\n#' @importFrom dplyr arrange desc mutate\n#' @importFrom ggrepel geom_text_repel\n#' @return\n#' @export\n#'\npieChart <- function(df, label.size = 2.5, color.use = NULL, title = \"\") {\n df %>% arrange(dplyr::desc(value)) %>%\n mutate(prop = scales::percent(value/sum(value))) -> df\n\n gg <- ggplot(df, aes(x=\"\", y=value, fill=group)) +\n geom_bar(stat=\"identity\", width=1) +\n coord_polar(\"y\", start=0)+theme_void() +\n ggrepel::geom_text_repel(aes(label = prop), size= label.size, show.legend = F, position = position_stack(vjust=0.5))\n # ggrepel::geom_text_repel(aes(label = prop), size= label.size, show.legend = F, nudge_x = 0)\n gg <- gg + theme(legend.position=\"bottom\", legend.direction = \"vertical\")\n\n if(!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values=color.use)\n # gg <- gg + scale_color_manual(color.use)\n }\n\n if (!is.null(title)) {\n gg <- gg + guides(fill = guide_legend(title = title))\n }\n gg\n}\n\n\n#' Subset the ligand-receptor interactions for given specific signals in CellChatDB\n#'\n#' @param signaling a character vector\n#' @param pairLR.use a dataframe containing ligand-receptor interactions\n#' @param key the keyword to match\n#' @param matching.exact whether perform exact matching\n#' @param pair.only whether only return ligand-receptor pairs without cofactors\n#' @importFrom future.apply future_sapply\n#' @importFrom dplyr select\n#' @return\n#' @export\nsearchPair <- function(signaling = c(), pairLR.use, key = c(\"pathway_name\",\"ligand\"), matching.exact = FALSE, pair.only = TRUE) {\n key <- match.arg(key)\n pairLR = future.apply::future_sapply(\n X = 1:length(signaling),\n FUN = function(x) {\n if (!matching.exact) {\n index <- grep(signaling[x], pairLR.use[[key]])\n } else {\n index <- which(pairLR.use[[key]] %in% signaling[x])\n }\n if (length(index) > 0) {\n if (pair.only) {\n pairLR <- dplyr::select(pairLR.use[index, ], interaction_name, pathway_name, ligand, receptor)\n } else {\n pairLR <- pairLR.use[index, ]\n }\n return(pairLR)\n } else {\n stop(cat(paste(\"Cannot find \", signaling[x], \".\", \"Please input a correct name!\"),'\\n'))\n }\n }\n )\n if (pair.only) {\n pairLR0 <- vector(\"list\", length(signaling))\n for (i in 1:length(signaling)) {\n pairLR0[[i]] <- matrix(unlist(pairLR[c(4*i-3, 4*i-2, 4*i-1, 4*i)]), ncol=4, byrow=F)\n }\n pairLR <- do.call(rbind, pairLR0)\n dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]][1:4]\n rownames(pairLR) <- pairLR[,1]\n } else {\n pairLR0 <- vector(\"list\", length(signaling))\n for (i in 1:length(signaling)) {\n pairLR0[[i]] <- matrix(unlist(pairLR[(i*ncol(pairLR.use)-(ncol(pairLR.use)-1)):(i*ncol(pairLR.use))]), ncol=ncol(pairLR.use), byrow=F)\n }\n pairLR <- do.call(rbind, pairLR0)\n dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]]\n rownames(pairLR) <- pairLR[,1]\n }\n return(as.data.frame(pairLR, stringsAsFactors = FALSE))\n}\n\n#' Subset CellChatDB databse by only including interactions of interest\n#'\n#' @param CellChatDB CellChatDB databse\n#' @param search a character vector, which is a subset of c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\"); Setting search = NULL & non_protein = FALSE will return all signaling except for \"Non-protein Signaling\".\n#'\n#' When `key` is a vector, the `search` should be a list with the size being `length(key)`, where each element is a character vector.\n#' @param key a character vector and each element should be one of the column names of the interaction_input from CellChatDB.\n#' @param non_protein whether to use the non-protein signaling for CellChat analysis. By default, non_protein = FALSE because most of non-protein signaling are the special synaptic signaling interactions that can only be used when inferring neuron-neuron communication.\n#'\n#' @return\n#' @export\n#'\nsubsetDB <- function(CellChatDB, search = c(), key = \"annotation\", non_protein = FALSE) {\n interaction_input <- CellChatDB$interaction\n if (is.null(search) & non_protein == FALSE & any(key == \"annotation\")) {\n search <- c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\")\n } else if (is.null(search) & non_protein == TRUE & any(key == \"annotation\")) {\n search <- c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\")\n }\n\n if (\"Non-protein Signaling\" %in% unlist(search)) {\n non_protein = TRUE\n message(\"The non-protein signaling is now included for CellChat analysis, which is usually used for neuron-neuron and metabolic communication!\")\n }\n if (non_protein == FALSE) {\n interaction_input <- subset(interaction_input, annotation != \"Non-protein Signaling\")\n }\n if (all(key %in% colnames(interaction_input)) == FALSE) {\n stop(\"Each element of the `key` should be one of the column names of the interaction_input from CellChatDB\")\n }\n if (length(key) == 1) {\n interaction_input <- interaction_input[interaction_input[[key]] %in% search, ]\n } else {\n if (!is.list(search)) {\n stop(\"When `key` is a vector, the `search` should be a list. \")\n }\n idx.use <- TRUE\n for (i in 1:length(key)) {\n idx.use <- idx.use & (interaction_input[[key[i]]] %in% search[[i]])\n }\n interaction_input <- interaction_input[idx.use, , drop = FALSE]\n }\n\n CellChatDB$interaction <- interaction_input\n return(CellChatDB)\n}\n\n\n\n#' Extract the genes involved in CellChatDB\n#'\n#' @param CellChatDB CellChatDB databse used in the analysis\n#'\n#' @return\n#' @export\n#' @importFrom dplyr select\n#'\nextractGene <- function(CellChatDB) {\n interaction_input <- CellChatDB$interaction\n complex_input <- CellChatDB$complex\n cofactor_input <- CellChatDB$cofactor\n geneIfo <- CellChatDB$geneInfo\n # check whether all gene names in complex_input and cofactor_input are official gene symbol in geneIfo\n checkGeneSymbol(geneSet = unlist(complex_input), geneIfo)\n checkGeneSymbol(geneSet = unlist(cofactor_input), geneIfo)\n\n geneL <- unique(interaction_input$ligand)\n geneR <- unique(interaction_input$receptor)\n geneLR <- c(geneL, geneR)\n checkGeneSymbol(geneSet = geneLR[geneLR %in% rownames(complex_input) == \"FALSE\"], geneIfo)\n\n geneL <- extractGeneSubset(geneL, complex_input, geneIfo)\n geneR <- extractGeneSubset(geneR, complex_input, geneIfo)\n geneLR <- c(geneL, geneR)\n\n cofactor <- c(interaction_input$agonist, interaction_input$antagonist, interaction_input$co_A_receptor, interaction_input$co_I_receptor)\n cofactor <- unique(cofactor[cofactor != \"\"])\n cofactorsubunits <- select(cofactor_input[match(cofactor, rownames(cofactor_input), nomatch=0),], starts_with(\"cofactor\"))\n cofactorsubunitsV <- unlist(cofactorsubunits)\n geneCofactor <- unique(cofactorsubunitsV[cofactorsubunitsV != \"\"])\n\n gene.use <- unique(c(geneLR, geneCofactor))\n return(gene.use)\n\n}\n\n\n#' Extract the gene name\n#'\n#' @param geneSet gene set\n#' @param complex_input complex in CellChatDB databse\n#' @param geneIfo official gene symbol\n#'\n#' @return\n#' @importFrom dplyr select starts_with\n#' @export\nextractGeneSubset <- function(geneSet, complex_input, geneIfo) {\n complex <- geneSet[which(geneSet %in% geneIfo$Symbol == \"FALSE\")]\n geneSet <- intersect(geneSet, geneIfo$Symbol)\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complex <- intersect(complex, rownames(complexsubunits))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n geneSet <- unique(c(geneSet, complexsubunitsV))\n return(geneSet)\n}\n\n\n#' Extract the signaling gene names from ligand-receptor pairs\n#'\n#' @param pairLR data frame must contain columns named `ligand` and `receptor`\n#' @param object a CellChat object\n#' @param complex_input complex in CellChatDB databse\n#' @param geneInfo official gene symbol\n#' @param combined whether combining the ligand genes and receptor genes\n#'\n#' @return\n#' @export\nextractGeneSubsetFromPair <- function(pairLR, object = NULL, complex_input = NULL, geneInfo = NULL, combined = TRUE) {\n if (!all(c(\"ligand\", \"receptor\") %in% colnames(pairLR))) {\n stop(\"The input data frame must contain columns named `ligand` and `receptor`\")\n }\n if (is.null(object)) {\n if (is.null(complex_input) | is.null(geneInfo)) {\n stop(\"Either `object` or `complex_input` and `geneInfo` should be provided!\")\n } else {\n complex <- complex_input\n }\n } else {\n complex <- object@DB$complex\n geneInfo <- object@DB$geneInfo\n }\n geneL <- unique(pairLR$ligand)\n geneR <- unique(pairLR$receptor)\n geneL <- extractGeneSubset(geneL, complex, geneInfo)\n geneR <- extractGeneSubset(geneR, complex, geneInfo)\n geneLR <- c(geneL, geneR)\n if (combined) {\n return(geneLR)\n } else {\n return(list(geneL = geneL, geneR = geneR))\n }\n}\n\n\n\n#' check the official Gene Symbol\n#'\n#' @param geneSet gene set to check\n#' @param geneIfo official Gene Symbol\n#' @return\n#' @export\n#'\ncheckGeneSymbol <- function(geneSet, geneIfo) {\n geneSet <- unique(geneSet[geneSet != \"\"])\n genes_notOfficial <- geneSet[geneSet %in% geneIfo$Symbol == \"FALSE\"]\n if (length(genes_notOfficial) > 0) {\n cat(\"Issue identified!! Please check the official Gene Symbol of the following genes: \", \"\\n\", genes_notOfficial, \"\\n\")\n }\n return(FALSE)\n}\n\n#' Extract L-R pairs associated with a given gene set\n#'\n#' @param geneSet a vector of genes\n#' @param db one of the CellChatDB databases (e.g., CellChatDB.human, CellChatDB.mouse...)\n#' @export\n#'\nextractLRfromGenes <- function(geneSet, db) {\n interaction_input <- db$interaction\n complex_input <- db$complex\n geneIfo <- db$geneInfo\n geneSet1 <- intersect(geneSet, geneIfo$Symbol)\n idx1 <- which(interaction_input$ligand %in% geneSet1)\n idx2 <- which(interaction_input$receptor %in% geneSet1)\n idx <- unique(c(idx1, idx2)); idx <- setdiff(idx,0)\n LR.use <- interaction_input[idx,,drop = FALSE]\n genes.use <- extractGeneSubsetFromPair(LR.use, complex_input = complex_input, geneInfo = geneIfo)\n return(list(LR.use = LR.use, genes.use=genes.use))\n}\n\n\n#' Update CellChatDB by integrating new L-R pairs from other resources or adding more information\n#'\n#' @param db a data frame of the customized ligand-receptor database with at least two columns named as `ligand` and `receptor`. We highly suggest users to provide a column of pathway information named `pathway_name` associated with each L-R pair.\n#' Other optional columns include `interaction_name` and `interaction_name_2`. The default columns of CellChatDB can be checked via `colnames(CellChatDB.human$interaction)`.\n#' @param gene_info a data frame with at least one column named as `Symbol`. \"When setting gene_info = NULL, the input `species_target` should be provided: either `human` or `mouse`.\n#' @param other_info a list consisting of other information including a dataframe named as `complex` and a dataframe named as `cofactor`. This additional information is not necessary. If other_info is provided, the `complex` and `cofactor` are dataframes with defined rownames.\n#' @param gene_info_columnNew a data frame with at least two columns named as `Symbol` and `AntibodyName`, which will add a new column named `AntibodyName` into `db$geneInfo`.\n#' @param trim.pathway whether to delete the interactions with missing pathway names when the column `pathway_name` is provided in `db`.\n#' @param merged whether merging the input database with the existing CellChatDB. setting merged = TRUE, the input `species_target` should be provided: either `human` or `mouse`.\n#' @param species_target the target species for output: either `human` or `mouse`.\n#' @return a list consisting of the customized L-R database for further CellChat analysis\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # integrating new L-R pairs from other resources or utilizing a custom database `db.user`\n#' db.new <- updateCellChatDB(db = db.user, gene_info = gene_info)\n#' db.new <- updateCellChatDB(db = db.user, gene_info = NULL, species_target = \"human\")\n#' # Alternatively, users can integrate the customized L-R pairs into the built-in CellChatDB\n#' db.new <- updateCellChatDB(db = db.user, merged = TRUE, species_target = \"human\")\n#' # Add new columns (e.g., AntibodyName) into gene_info\n#' db.new.human <- updateCellChatDB(db = CellChatDB.human$interaction, gene_info = CellChatDB.human$geneInfo, other_info=list(complex = CellChatDB.human$complex, cofactor = CellChatDB.human$cofactor),gene_info_columnNew = gene_info_columnNew)\n#'\n#' # Users can now use this new database in CellChat analysis\n#' cellchat@DB <- db.new\n#'}\nupdateCellChatDB <- function(db, gene_info = NULL, other_info = NULL, gene_info_columnNew = NULL, trim.pathway = FALSE, merged = FALSE, species_target = NULL) {\n db <- dplyr::mutate(db, across(everything(), as.character))\n if (all(c(\"ligand\",\"receptor\") %in% colnames(db)) == FALSE) {\n stop(\"The input `db` must contain at least two columns named as ligand,receptor\")\n }\n if (all(c(\"pathway_name\") %in% colnames(db)) == FALSE) {\n warning(\"The pathway_name associated with each L-R pair is not provided in `db`. We suggest to provide this information so that the versatile functionalities of CellChat can be fully used! \\n\")\n db$pathway_name <- rep(\"\", nrow(db))\n } else {\n pathway.missing <- which(db$pathway_name == \"\")\n if (length(pathway.missing) > 0) {\n if (trim.pathway) {\n cat(paste0(\"The pathway names of \", length(pathway.missing) ,\" interactions are missing and the corresponding interactions are now deleted. \\n\"))\n db <- db[-pathway.missing, , drop = FALSE]\n } else {\n warning(paste0(\"The pathway names of \", length(pathway.missing) ,\" interactions are missing and it may cause error in the downstream analysis. Setting `trim.pathway = TRUE` to avoid such possible errors. \\n\"))\n }\n }\n }\n if (all(c(\"interaction_name\") %in% colnames(db)) == FALSE) {\n db$interaction_name <- paste0(toupper(db$ligand), \"_\", toupper(db$receptor))\n }\n if (all(c(\"interaction_name_2\") %in% colnames(db)) == FALSE) {\n db$interaction_name_2 <- paste0(db$ligand, \" - \", db$receptor)\n }\n if (\"agonist\" %in% colnames(db) == FALSE) {\n db$agonist <- rep(\"\", nrow(db))\n }\n if (\"antagonist\" %in% colnames(db) == FALSE) {\n db$antagonist <- rep(\"\", nrow(db))\n }\n if (\"co_A_receptor\" %in% colnames(db) == FALSE) {\n db$co_A_receptor <- rep(\"\", nrow(db))\n }\n if (\"co_I_receptor\" %in% colnames(db) == FALSE) {\n db$co_I_receptor <- rep(\"\", nrow(db))\n }\n ## construct database\n idx.remove <- duplicated(db$interaction_name)\n if (sum(idx.remove) > 0) {\n warning(paste0(sum(idx.remove), \" duplicated interaction_names are identified and the corresponding interactions are now deleted. \\n\"))\n db <- db[-which(idx.remove), ]\n }\n\n # build the interaction file\n interaction_input <- db\n rownames(interaction_input) <- interaction_input$interaction_name\n cols.default <- c(\"interaction_name\",\"pathway_name\",\"ligand\",\"receptor\",\"agonist\",\"antagonist\",\"co_A_receptor\",\"co_I_receptor\",\"annotation\",\"interaction_name_2\")\n cols.common <- intersect(cols.default,colnames(interaction_input))\n cols.specific <- setdiff(colnames(interaction_input), cols.default)\n interaction_input <- dplyr::select(interaction_input, c(cols.common, cols.specific))\n\n # build the complex file\n if (!is.null(other_info)) {\n if (\"complex\" %in% names(other_info) == TRUE) {\n complex_input <- other_info$complex\n if (all(colnames(complex_input) %in% paste0(\"subunit_\", seq_len(100))) == FALSE) {\n stop(\"The colnames of the input `other_info$complex` should be `subunit_1`,`subunit_2`,...\")\n }\n } else {\n complex_input <- data.frame()\n }\n # build the cofactor file\n if (\"cofactor\" %in% names(other_info) == TRUE) {\n cofactor_input <- other_info$cofactor\n if (all(colnames(cofactor_input) %in% paste0(\"cofactor\", seq_len(100))) == FALSE) {\n stop(\"The colnames of the input `other_info$cofactor` should be `cofactor1`,`cofactor2`,...\")\n }\n } else {\n cofactor_input <- data.frame()\n }\n } else {\n complex_input <- data.frame()\n cofactor_input <- data.frame()\n }\n\n # build the geneInfo file\n if (!is.null(gene_info)) {\n if (\"Symbol\" %in% colnames(gene_info) == FALSE) {\n stop(\"The input `gene_info` must contain at least one column named as `Symbol`\")\n }\n } else {\n if (is.null(species_target)) {\n stop(\"When setting gene_info = NULL, the input `species_target` should be provided: either `human` or `mouse`. \")\n }\n if (species_target == \"human\") {\n gene_info <- CellChatDB.human$geneInfo\n } else if (species_target == \"mouse\") {\n gene_info <- CellChatDB.mouse$geneInfo\n }\n }\n geneInfo_input <- gene_info\n\n if (merged == TRUE) {\n if (is.null(species_target)) {\n stop(\"When setting merged = TRUE, the input `species_target` should be provided: either `human` or `mouse`. \")\n }\n if (species_target == \"human\") {\n db.cellchat <- CellChatDB.human\n cat(\"Starting to merge the input database with CellChatDB.human... \\n\")\n } else if (species_target == \"mouse\") {\n db.cellchat <- CellChatDB.mouse\n cat(\"Starting to merge the input database with CellChatDB.mouse... \\n\")\n }\n\n # build the interaction file\n interaction_input.cellchat <- db.cellchat$interaction\n interaction_input.cellchat$source.merged <- \"CellChatDB\"\n interaction_input$source.merged <- \"User\"\n cols.common <- intersect(colnames(interaction_input), colnames(interaction_input.cellchat))\n interaction_input <- interaction_input[, cols.common]\n interaction_input.cellchat <- interaction_input.cellchat[, cols.common]\n interaction_input.merged <- rbind(interaction_input.cellchat, interaction_input)\n idx.remove <- duplicated(interaction_input.merged$interaction_name)\n if (sum(idx.remove) > 0) {\n interaction_input.merged <- interaction_input.merged[-which(idx.remove), ]\n }\n\n # build the complex file\n complex_input.cellchat <- db.cellchat$complex\n num.subunit <- max(ncol(complex_input), ncol(complex_input.cellchat))\n if (ncol(complex_input) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(complex_input)))\n complex_input <- cbind(complex_input, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(complex_input)))))\n colnames(complex_input) <- paste0(\"subunit_\", seq_len(num.subunit))\n }\n if (ncol(complex_input.cellchat) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(complex_input.cellchat)))\n complex_input.cellchat <- cbind(complex_input.cellchat, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(complex_input.cellchat)))))\n colnames(complex_input.cellchat) <- paste0(\"subunit_\", seq_len(num.subunit))\n }\n complex_input.merged <- rbind(complex_input.cellchat, complex_input)\n idx.remove <- duplicated(rownames(complex_input.merged))\n if (sum(idx.remove) > 0) {\n complex_input.merged <- complex_input.merged[-which(idx.remove), ]\n }\n\n # build the cofactor file\n cofactor_input.cellchat <- db.cellchat$cofactor\n num.subunit <- max(ncol(cofactor_input), ncol(cofactor_input.cellchat))\n if (ncol(cofactor_input) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(cofactor_input)))\n cofactor_input <- cbind(cofactor_input, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(cofactor_input)))))\n colnames(cofactor_input) <- paste0(\"cofactor\", seq_len(num.subunit))\n }\n if (ncol(cofactor_input.cellchat) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(cofactor_input.cellchat)))\n cofactor_input.cellchat <- cbind(cofactor_input.cellchat, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(cofactor_input.cellchat)))))\n colnames(cofactor_input.cellchat) <- paste0(\"cofactor\", seq_len(num.subunit))\n }\n cofactor_input.merged <- rbind(cofactor_input.cellchat, cofactor_input)\n idx.remove <- duplicated(rownames(cofactor_input.merged))\n if (sum(idx.remove) > 0) {\n cofactor_input.merged <- cofactor_input.merged[-which(idx.remove), ]\n }\n\n interaction_input <- interaction_input.merged\n complex_input <- complex_input.merged\n cofactor_input <- cofactor_input.merged\n }\n\n if (!is.null(gene_info_columnNew)) {\n checkGeneSymbol(gene_info_columnNew$Symbol, geneInfo_input)\n idx <- match(gene_info_columnNew$Symbol, geneInfo_input$Symbol)\n geneInfo_input$AntibodyName <- NA\n geneInfo_input$AntibodyName[idx[!is.na(idx)]] <- gene_info_columnNew$AntibodyName[!is.na(idx)]\n }\n db.new <- list()\n db.new$interaction <- interaction_input\n db.new$complex <- complex_input\n db.new$cofactor <- cofactor_input\n db.new$geneInfo <- geneInfo_input\n\n return(db.new)\n}\n"], ["/CellChat/R/RcppExports.R", "# Generated by using Rcpp::compileAttributes() -> do not edit by hand\n# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393\n\nComputeSNN <- function(nn_ranked, prune) {\n .Call(`_CellChat_ComputeSNN`, nn_ranked, prune)\n}\n\n"], ["/CellChat/R/CellChat-package.R", "## usethis namespace: start\n#' @useDynLib CellChat, .registration = TRUE\n## usethis namespace: end\nNULL\n\n## usethis namespace: start\n#' @importFrom Rcpp sourceCpp\n## usethis namespace: end\nNULL\n"], ["/CellChat/R/data.R", "#' Ligand-receptor interactions in CellChat database for mouse\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.mouse\"\n\n#' Ligand-receptor interactions in CellChat database for human\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.human\"\n\n#' Mouse Protein-Protein interactions\n#'\n#' An adjacency matrix of the high confidence known experimental interactions\n#' between mouse proteins on STRINGdb.\n#'\n#' @format A square matrix where A_{ij}=1 if protein i interacts with protein j\n#' @source \\url{http://www.string-db.org/}\n\"PPI.mouse\"\n\n#' Ligand-receptor interactions in CellChat database for Zebrafish\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.zebrafish\"\n\n#' Human Protein-Protein interactions\n#'\n#' An adjacency matrix of the high confidence known experimental interactions\n#' between human proteins on STRINGdb.\n#'\n#' @format A square matrix where A_{ij}=1 if protein i interacts with protein j\n#' @source \\url{http://www.string-db.org/}\n\"PPI.human\"\n"]], "task_instance_info": {"created_time": "2025-08-21 00:57:36", "created_task_model": "DeepSeek-R1", "function_skeleton": "function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n reduction = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE) {}", "code_description": "This code segment functions to: Generate interactive visualizations of gene expression or ligand-receptor pair activity across cell groups within a dimensional reduction space, supporting both continuous color gradients and categorical binary representations while enabling multi-panel layouts with configurable parameters for data thresholds and visual styling."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\n[TASK_BEGIN]\nplotly_FeaturePlot <- function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n reduction = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE) {\n if (length(names(object@dr)) == 0) {\n stop(\"Please check `addReduction` to add a new reduced space into `object@dr`. \\n\")\n }\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please specify the dimensionality reduction to use. \\n\"))\n }\n }\n \n coordinates <- as.data.frame(coords)\n samples <- object@meta$samples\n if (ncol(coordinates) >= 2) {\n coordinates <- coordinates[, c(1,2)]\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n }\n \n data <- as.matrix(object@data)\n meta <- object@meta\n cell_labels <- object@idents\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = direction))(n.colors)\n })\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n } else {\n colormap <- color.heatmap\n }\n \n if (!is.null(features) & !is.null(signaling)) stop(\"Please don't input features or signaling simultaneously.\")\n if (!is.null(features) & !is.null(pairLR.use)) stop(\"Please don't input features or pairLR.use simultaneously.\")\n if (!is.null(signaling) & !is.null(pairLR.use)) stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n \n df <- data.frame(x = coordinates[, 1], y = coordinates[, 2],\n cell_labels = cell_labels[samples == sample.use])\n\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- CellChat::extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, \n enriched.only = enriched.only, thresh = thresh)\n feature.use <- res$geneLR\n } else if (!is.null(pairLR.use)) {\n pairLR.use.name <- pairLR.use$interaction_name\n LR.pair <- object@LR$LRsig[pairLR.use.name, c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- CellChat:::extractGeneSubset(geneL, object@DB$complex, object@DB$geneInfo)\n geneR <- CellChat:::extractGeneSubset(geneR, object@DB$complex, object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n } else {\n feature.use <- features\n }\n \n data.use <- data[feature.use, , drop = FALSE]\n if (!is.null(cutoff)) data.use[data.use <= cutoff] <- 0\n\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <- ggplot(df, aes(x, y)) + \n geom_point(aes(color = feature.data), size = point.size, alpha = alpha) +\n scale_color_gradientn(colors = colormap, na.value = \"grey90\") +\n ggtitle(feature.name) +\n theme_classic() +\n theme(axis.line = element_blank(), axis.ticks = element_blank(), \n axis.text = element_blank(), plot.title = element_text(hjust = 0.5))\n \n gg[[i]] <- plotly::ggplotly(g, height = 400) \n annotations[[i]] <- list(x = 0.5, y = 1, text = feature.name, \n xref = \"paper\", yref = \"paper\", showarrow = FALSE)\n }\n\n if (numFeature > 1) {\n plotly::subplot(gg, nrows = plot_nrows, margin = 0.02) %>% \n plotly::layout(annotations = annotations)\n } else {\n plotly::ggplotly(gg[[1]])\n }\n } else {\n if (is.null(color.use)) color.use <- ggPalette(4)\n if (!is.null(signaling)) {\n res <- CellChat::extractEnrichedLR(object, signaling = signaling)\n LR.pair <- object@LR$LRsig[res$interaction_name, c(\"ligand\", \"receptor\")]\n } else {\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\", \"receptor\")]\n }\n \n dataL <- CellChat:::computeExpr_LR(LR.pair$ligand, data, object@DB$complex)\n dataR <- CellChat:::computeExpr_LR(LR.pair$receptor, data, object@DB$complex)\n \n numFeature = nrow(LR.pair)\n gg <- vector(\"list\", numFeature)\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n idx1 <- dataL[i,] > cutoff\n idx2 <- dataR[i,] > cutoff\n group <- factor(dplyr::case_when(\n idx1 & idx2 ~ \"Both\",\n idx1 ~ LR.pair$ligand[i],\n idx2 ~ LR.pair$receptor[i],\n TRUE ~ \"None\"\n ), levels = c(LR.pair$ligand[i], LR.pair$receptor[i], \"Both\", \"None\"))\n \n df$feature.data <- group\n g <- ggplot(df, aes(x, y)) + \n geom_point(aes(color = feature.data), size = point.size, alpha = alpha) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n ggtitle(paste(LR.pair$ligand[i], LR.pair$receptor[i], sep = \"_\")) +\n theme_classic() +\n theme(axis.line = element_blank(), axis.ticks = element_blank(), \n axis.text = element_blank(), plot.title = element_text(hjust = 0.5))\n \n gg[[i]] <- plotly::ggplotly(g, height = 400)\n annotations[[i]] <- list(x = 0.5, y = 1, text = paste(LR.pair$ligand[i], LR.pair$receptor[i], sep = \"_\"), \n xref = \"paper\", yref = \"paper\", showarrow = FALSE)\n }\n\n if (numFeature > 1) {\n plotly::subplot(gg, nrows = plot_nrows, margin = 0.02) %>% \n plotly::layout(annotations = annotations)\n } else {\n plotly::ggplotly(gg[[1]])\n }\n }\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 00-59-13"}, "editdistance_info": {"edit_distance": 34.3816, "calculate_time": "2025-08-21 00:59:13", "true_code_clean": "function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n reduction = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE){\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(\"Please make sure `object@dr` contains a low-dimensional space of the data and specify the dimensionality reduction to use.\")\n }\n }\n samples <- object@meta$samples\n cell_labels <- object@idents\n data <- as.matrix(object@data)\n meta <- object@meta\n coords <- as.data.frame(coords)\n if (ncol(coords) >= 2) {\n coords <- coords[, c(1,2)]\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = -1))(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"\n }\n else {\n colormap <- color.heatmap\n }\n if (is.null(features) &\n is.null(signaling) & is.null(pairLR.use)) {\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)) {\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)) {\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)) {\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n df <- data.frame(x = coords[, 1], y = coords[, 2],\n cell_labels = cell_labels)\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n geneLR.return = TRUE,\n enriched.only = enriched.only,\n thresh = thresh\n )\n feature.use <- res$geneLR\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex,\n object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex,\n object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n }\n else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) >\n 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n }\n else if (length(intersect(feature.use, colnames(meta))) >\n 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[, feature.use, drop = FALSE])\n }\n else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \", cutoff, \"to the values...\",\n \"\\n\")\n data.use[data.use <= cutoff] <- 0\n }\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 0.95) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n }\n annotations <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_colour_gradientn(\n colours = colormap,\n guide = guide_colorbar(\n title = NULL,\n ticks = T,\n label = T,\n barwidth = 0.5\n ),\n na.value = \"grey90\"\n ) +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + ggtitle(feature.name) +\n theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n gg[[i]] <- g %>% plotly::ggplotly(height = 400)\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',annotations = annotations)\n }\n else {\n gg <- plotly::ggplotly(gg[[1]])\n }\n }\n else {\n set_individual_legend <- function(plt) {\n plt_build <- plotly::plotly_build(plt)\n len_legend <- length(plt_build$x$data)\n for (i in 1:len_legend) {\n plt_build$x$data[[i]]$legendgroup <- feature.name\n plt_build$x$data[[i]]$legendgrouptitle <- list(text=feature.name,font=list(size=12))\n }\n return(plt_build)\n }\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n enriched.only = enriched.only,\n thresh = thresh\n )\n LR.pair <- object@LR$LRsig[res$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL\n rownames(dataR) <- geneR\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \")\n }\n gg <- vector(\"list\", numFeature)\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 1) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n }\n annotations <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i,] > cutoff\n idx2 = dataR[i,] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\", ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i], geneR[i],\n \"Both\", \"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i], geneR[i], \"Both\",\n \"None\")\n if (length(setdiff(levels(group), unique(group))) >\n 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group),\n unique(group)))\n }\n df$feature.data <- group\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + guides(color = guide_legend(override.aes = list(size = legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n gg[[i]] <- g %>% plotly::ggplotly(\n type = 'scatter',\n mode='markers+text',\n ) %>% set_individual_legend()\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',\n annotations = annotations,\n legend = list(tracegroupgap = 10,title=list(text=''))\n )\n }\n else {\n gg <- plotly::ggplotly(gg[[1]],\n type = 'scatter',\n mode = 'markers') %>%\n plotly::layout(legend = list(title = list(text = '')))\n }\n }\n return(gg)\n }", "predict_code_clean": "plotly_FeaturePlot <- function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n reduction = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE) {\n if (length(names(object@dr)) == 0) {\n stop(\"Please check `addReduction` to add a new reduced space into `object@dr`. \\n\")\n }\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please specify the dimensionality reduction to use. \\n\"))\n }\n }\n coordinates <- as.data.frame(coords)\n samples <- object@meta$samples\n if (ncol(coordinates) >= 2) {\n coordinates <- coordinates[, c(1,2)]\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n }\n data <- as.matrix(object@data)\n meta <- object@meta\n cell_labels <- object@idents\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = direction))(n.colors)\n })\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"\n } else {\n colormap <- color.heatmap\n }\n if (!is.null(features) & !is.null(signaling)) stop(\"Please don't input features or signaling simultaneously.\")\n if (!is.null(features) & !is.null(pairLR.use)) stop(\"Please don't input features or pairLR.use simultaneously.\")\n if (!is.null(signaling) & !is.null(pairLR.use)) stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n df <- data.frame(x = coordinates[, 1], y = coordinates[, 2],\n cell_labels = cell_labels[samples == sample.use])\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- CellChat::extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, \n enriched.only = enriched.only, thresh = thresh)\n feature.use <- res$geneLR\n } else if (!is.null(pairLR.use)) {\n pairLR.use.name <- pairLR.use$interaction_name\n LR.pair <- object@LR$LRsig[pairLR.use.name, c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- CellChat:::extractGeneSubset(geneL, object@DB$complex, object@DB$geneInfo)\n geneR <- CellChat:::extractGeneSubset(geneR, object@DB$complex, object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n } else {\n feature.use <- features\n }\n data.use <- data[feature.use, , drop = FALSE]\n if (!is.null(cutoff)) data.use[data.use <= cutoff] <- 0\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n annotations <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <- ggplot(df, aes(x, y)) + \n geom_point(aes(color = feature.data), size = point.size, alpha = alpha) +\n scale_color_gradientn(colors = colormap, na.value = \"grey90\") +\n ggtitle(feature.name) +\n theme_classic() +\n theme(axis.line = element_blank(), axis.ticks = element_blank(), \n axis.text = element_blank(), plot.title = element_text(hjust = 0.5))\n gg[[i]] <- plotly::ggplotly(g, height = 400) \n annotations[[i]] <- list(x = 0.5, y = 1, text = feature.name, \n xref = \"paper\", yref = \"paper\", showarrow = FALSE)\n }\n if (numFeature > 1) {\n plotly::subplot(gg, nrows = plot_nrows, margin = 0.02) %>% \n plotly::layout(annotations = annotations)\n } else {\n plotly::ggplotly(gg[[1]])\n }\n } else {\n if (is.null(color.use)) color.use <- ggPalette(4)\n if (!is.null(signaling)) {\n res <- CellChat::extractEnrichedLR(object, signaling = signaling)\n LR.pair <- object@LR$LRsig[res$interaction_name, c(\"ligand\", \"receptor\")]\n } else {\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\", \"receptor\")]\n }\n dataL <- CellChat:::computeExpr_LR(LR.pair$ligand, data, object@DB$complex)\n dataR <- CellChat:::computeExpr_LR(LR.pair$receptor, data, object@DB$complex)\n numFeature = nrow(LR.pair)\n gg <- vector(\"list\", numFeature)\n annotations <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n idx1 <- dataL[i,] > cutoff\n idx2 <- dataR[i,] > cutoff\n group <- factor(dplyr::case_when(\n idx1 & idx2 ~ \"Both\",\n idx1 ~ LR.pair$ligand[i],\n idx2 ~ LR.pair$receptor[i],\n TRUE ~ \"None\"\n ), levels = c(LR.pair$ligand[i], LR.pair$receptor[i], \"Both\", \"None\"))\n df$feature.data <- group\n g <- ggplot(df, aes(x, y)) + \n geom_point(aes(color = feature.data), size = point.size, alpha = alpha) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n ggtitle(paste(LR.pair$ligand[i], LR.pair$receptor[i], sep = \"_\")) +\n theme_classic() +\n theme(axis.line = element_blank(), axis.ticks = element_blank(), \n axis.text = element_blank(), plot.title = element_text(hjust = 0.5))\n gg[[i]] <- plotly::ggplotly(g, height = 400)\n annotations[[i]] <- list(x = 0.5, y = 1, text = paste(LR.pair$ligand[i], LR.pair$receptor[i], sep = \"_\"), \n xref = \"paper\", yref = \"paper\", showarrow = FALSE)\n }\n if (numFeature > 1) {\n plotly::subplot(gg, nrows = plot_nrows, margin = 0.02) %>% \n plotly::layout(annotations = annotations)\n } else {\n plotly::ggplotly(gg[[1]])\n }\n }\n }"}} {"repo_name": "CellChat", "file_name": "/CellChat/R/visualization.R", "inference_info": {"prefix_code": "#' ggplot theme in CellChat\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#' @importFrom ggplot2 theme_classic element_rect theme element_blank element_line element_text\nCellChat_theme_opts <- function() {\n theme(strip.background = element_rect(colour = \"white\", fill = \"white\")) +\n theme_classic() +\n theme(panel.border = element_blank()) +\n theme(axis.line.x = element_line(color = \"black\")) +\n theme(axis.line.y = element_line(color = \"black\")) +\n theme(panel.grid.minor.x = element_blank(), panel.grid.minor.y = element_blank()) +\n theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_blank()) +\n theme(panel.background = element_rect(fill = \"white\")) +\n theme(legend.key = element_blank()) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))\n}\n\n\n#' Generate ggplot2 colors\n#'\n#' @param n number of colors to generate\n#' @importFrom grDevices hcl\n#' @export\n#'\nggPalette <- function(n) {\n hues = seq(15, 375, length = n + 1)\n grDevices::hcl(h = hues, l = 65, c = 100)[1:n]\n}\n\n#' Generate colors from a customed color palette\n#'\n#' @param n number of colors\n#'\n#' @return A color palette for plotting\n#' @importFrom grDevices colorRampPalette\n#'\n#' @export\n#'\nscPalette <- function(n) {\n colorSpace <- c('#E41A1C','#377EB8','#4DAF4A','#984EA3','#F29403','#F781BF','#BC9DCC','#A65628','#54B0E4','#222F75','#1B9E77','#B2DF8A',\n '#E3BE00','#FB9A99','#E7298A','#910241','#00CDD1','#A6CEE3','#CE1261','#5E4FA2','#8CA77B','#00441B','#DEDC00','#DCF0B9','#8DD3C7','#999999')\n if (n <= length(colorSpace)) {\n colors <- colorSpace[1:n]\n } else {\n colors <- grDevices::colorRampPalette(colorSpace)(n)\n }\n return(colors)\n}\n\n#' Visualize the inferred cell-cell communication network\n#'\n#' Automatically save plots in the current working directory.\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param top the fraction of interactions to show (0 < top <= 1)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max.individual the maximum weight of edge when plotting the individual L-R netwrok; defualt = max(net)\n#' @param edge.weight.max.aggregate the maximum weight of edge when plotting the aggregated signaling pathway network\n#' @param edge.width.max The maximum edge width for visualization\n#' @param layout \"hierarchy\", \"circle\" or \"chord\"\n#' @param height height of plot\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param pt.title font size of the text\n#' @param title.space the space between the title and plot\n#' @param vertex.label.cex The label size of vertex in the network\n#' @param out.format the format of output figures: svg, png and pdf\n#'\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the network mediated by ligand-receptor using \"circle\" or \"chord\"\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x, text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`. NB: some parameters might be not supported\n#' @importFrom svglite svglite\n#' @importFrom grDevices dev.off pdf\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#'\nnetVisual <- ", "suffix_code": "\n\n\n#' Visualize the inferred signaling network of signaling pathways by aggregating all L-R pairs\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param layout \"hierarchy\", \"circle\", \"chord\" or \"spatial\"\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param pt.title font size of the text\n#' @param title.space the space between the title and plot\n#' @param vertex.label.cex The label size of vertex in the network\n#'\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x,text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`,`netVisual_spatial`. NB: some parameters might be not supported\n#' @importFrom grDevices recordPlot\n#'\n#' @return an object of class \"recordedplot\" or ggplot\n#' @export\n#'\n#'\nnetVisual_aggregate <- function(object, signaling, signaling.name = NULL, color.use = NULL, thresh = 0.05, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"),\n pt.title = 12, title.space = 6, vertex.label.cex = 0.8,\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20,\n ...) {\n layout <- match.arg(layout)\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n\n if (layout == \"hierarchy\") {\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n if (is.null(edge.weight.max)) {\n edge.weight.max = max(prob.sum)\n }\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n } else if (layout == \"circle\") {\n prob.sum <- apply(prob, c(1,2), sum)\n # prob.sum <-(prob.sum-min(prob.sum))/(max(prob.sum)-min(prob.sum))\n gg <- netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n } else if (layout == \"spatial\") {\n prob.sum <- apply(prob, c(1,2), sum)\n if (vertex.weight == \"incoming\"){\n if (length(slot(object, \"netP\")$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n vertex.weight = object@netP$centr[[signaling]]$indeg\n } else if (vertex.weight == \"outgoing\"){\n if (length(slot(object, \"netP\")$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n vertex.weight = object@netP$centr[[signaling]]$outdeg\n }\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n\n } else if (layout == \"chord\") {\n prob.sum <- apply(prob, c(1,2), sum)\n gg <- netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y= legend.pos.y)\n }\n\n return(gg)\n\n}\n\n\n\n#' Visualize the inferred signaling network of individual L-R pairs\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param pairLR.use a char vector or a data frame consisting of one column named \"interaction_name\", defining the L-R pairs of interest\n#' @param color.use the character vector defining the color of each cell group\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the edge weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector.\n#'\n#' Default is a scale value being 1, indicating all vertex is plotted in the same size;\n#'\n#' Set `vertex.weight` as a vector to plot vertex in different size; setting `vertex.weight = NULL` will have vertex with different size that are portional to the number of cells in each cell group.\n#'\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex in the network\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param graphics.init whether do graphics initiation using par(...). If graphics.init=FALSE, USERS can use par() in a more fexible way\n#' @param layout \"hierarchy\", \"circle\" or \"chord\"\n#' @param height height of plot\n#' @param thresh threshold of the p-value for determining significant interaction\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n# #' @param vertex.size Deprecated. Use `vertex.weight`\n\n#' Parameters below are set for \"spatial\" diagram. Please also check the function `netVisual_spatial` for more parameters.\n#' @param alpha.image the transparency of individual spots\n#' @param point.size the size of spots\n#'\n#' Parameters below are set for \"chord\" diagram. Please also check the function `netVisual_chord_cell` for more parameters.\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the figures using \"circle\" or \"chord\"\n#'\n#' @param ... other parameters (e.g.,vertex.label.cex, vertex.label.color, alpha.edge, label.edge, edge.label.color, edge.label.cex, edge.curved, text.x, text.y)\n#' passing to `netVisual_hierarchy1`,`netVisual_hierarchy2`,`netVisual_circle`. NB: some parameters might be not supported\n#' @importFrom grDevices dev.off pdf\n#'\n#' @return an object of class \"recordedplot\"\n#' @export\n#'\n#'\nnetVisual_individual <- function(object, signaling, signaling.name = NULL, pairLR.use = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex = 0.8,\n weight.scale = TRUE, edge.weight.max = NULL, edge.width.max=8, graphics.init = TRUE,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, #from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n # if (!is.null(vertex.size)) {\n # warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n # }\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n if (!is.null(pairLR.use)) {\n if (is.data.frame(pairLR.use)) {\n pairLR.name <- intersect(pairLR.name, as.character(pairLR.use$interaction_name))\n } else {\n pairLR.name <- intersect(pairLR.name, as.character(pairLR.use))\n }\n\n if (length(pairLR.name) == 0) {\n stop(\"There is no significant communication for the input L-R pairs!\")\n }\n }\n\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n\n # prob <-(prob-min(prob))/(max(prob)-min(prob))\n if (is.null(edge.weight.max)) {\n edge.weight.max = max(prob)\n }\n\n if (layout == \"hierarchy\") {\n if (graphics.init) {\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n }\n\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i,...)\n }\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n\n } else if (layout == \"circle\") {\n # par(mfrow=c(nRow,1))\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n gg[[i]] <- netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n } else if (layout == \"spatial\") {\n # par(mfrow=c(nRow,1))\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n gg[[i]] <- netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n } else if (layout == \"chord\") {\n if (graphics.init) {\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n }\n\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n gg[[i]] <- netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y)\n }\n }\n return(gg)\n}\n\n\n\n#' Hierarchy plot of cell-cell communications sending to cell groups in vertex.receiver\n#'\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net a weighted matrix defining the signaling network\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether rescale the edge weights\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.dist the distance between labels and dot position\n#' @param space.v the space between different columns in the plot\n#' @param space.h the space between different rows in the plot\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param alpha.edge the transprency of edge\n#' @param label.edge whether label edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_\n#' @importFrom grDevices adjustcolor recordPlot\n#' @importFrom shape Arrows\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_hierarchy1 <- function(net, vertex.receiver, color.use = NULL, title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight=20, vertex.weight.max = NULL, vertex.size.max = NULL,\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6,\n label.dist = 2.8, space.v = 1.5, space.h = 1.6, shape= NULL, label.edge=FALSE,edge.curved=0, margin=0.2,\n vertex.label.cex=0.6,vertex.label.color= \"black\",arrow.width=1,arrow.size = 0.2,edge.label.color='black',edge.label.cex=0.5, vertex.size = NULL){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n cells.level <- rownames(net)\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n if (is.null(color.use)) {\n color.use <- scPalette(nrow(net))\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+6\n\n m <- length(vertex.receiver)\n net2 <- net\n reorder.row <- c(vertex.receiver, setdiff(1:nrow(net),vertex.receiver))\n net2 <- net2[reorder.row,vertex.receiver]\n # Expand out to symmetric (M+N)x(M+N) matrix\n m1 <- nrow(net2); n1 <- ncol(net2)\n net3 <- rbind(cbind(matrix(0, m1, m1), net2), matrix(0, n1, m1+n1))\n\n row.names(net3) <- c(row.names(net)[vertex.receiver], row.names(net)[setdiff(1:m1,vertex.receiver)], rep(\"\",m))\n colnames(net3) <- row.names(net3)\n color.use3 <- c(color.use[vertex.receiver], color.use[setdiff(1:m1,vertex.receiver)], rep(\"#FFFFFF\",length(vertex.receiver)))\n color.use3.frame <- c(color.use[vertex.receiver], color.use[setdiff(1:m1,vertex.receiver)], color.use[vertex.receiver])\n\n if (length(vertex.weight) != 1) {\n vertex.weight = c(vertex.weight[vertex.receiver], vertex.weight[setdiff(1:m1,vertex.receiver)],vertex.weight[vertex.receiver])\n }\n if (is.null(shape)) {\n shape <- c(rep(\"circle\",m), rep(\"circle\", m1-m), rep(\"circle\",m))\n }\n\n g <- graph_from_adjacency_matrix(net3, mode = \"directed\", weighted = T)\n edge.start <- ends(g, es=E(g), names=FALSE)\n coords <- matrix(NA, nrow(net3), 2)\n coords[1:m,1] <- 0; coords[(m+1):m1,1] <- space.h; coords[(m1+1):nrow(net3),1] <- space.h/2;\n coords[1:m,2] <- seq(space.v, 0, by = -space.v/(m-1)); coords[(m+1):m1,2] <- seq(space.v, 0, by = -space.v/(m1-m-1));coords[(m1+1):nrow(net3),2] <- seq(space.v, 0, by = -space.v/(n1-1));\n coords_scale<-coords\n\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use3[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use3.frame[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n E(g)$label<-E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n # E(g)$width<-0.3+edge.max.width/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n E(g)$width<- 0.3+E(g)$weight/edge.weight.max*edge.width.max\n }else{\n E(g)$width<-0.3+edge.width.max*E(g)$weight\n }\n\n E(g)$arrow.width<-arrow.width\n E(g)$arrow.size<-arrow.size\n E(g)$label.color<-edge.label.color\n E(g)$label.cex<-edge.label.cex\n E(g)$color<-adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n\n label.dist <- c(rep(space.h*label.dist,m), rep(space.h*label.dist, m1-m),rep(0, nrow(net3)-m1))\n label.locs <- c(rep(-pi, m), rep(0, m1-m),rep(-pi, nrow(net3)-m1))\n # text.pos <- cbind(c(-space.h/1.5, space.h/10, space.h/1.2), space.v-space.v/10)\n text.pos <- cbind(c(-space.h/1.5, space.h/22, space.h/1.5), space.v-space.v/7)\n igraph::add.vertex.shape(\"fcircle\", clip=igraph::igraph.shape.noclip,plot=mycircle, parameters=list(vertex.frame.color=1, vertex.frame.width=1))\n plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin,rescale=T,vertex.shape=\"fcircle\", vertex.frame.width = c(rep(1,m1), rep(2,nrow(net3)-m1)),\n vertex.label.degree=label.locs, vertex.label.dist=label.dist, vertex.label.family=\"Helvetica\")\n text(text.pos, c(\"Source\",\"Target\",\"Source\"), cex = 0.8, col = c(\"#c51b7d\",\"#c51b7d\",\"#2f6661\"))\n arrow.pos1 <- c(-space.h/1.5, space.v-space.v/4, space.h/100000, space.v-space.v/4)\n arrow.pos2 <- c(space.h/1.5, space.v-space.v/4, space.h/20, space.v-space.v/4)\n shape::Arrows(arrow.pos1[1], arrow.pos1[2], arrow.pos1[3], arrow.pos1[4], col = \"#c51b7d\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n shape::Arrows(arrow.pos2[1], arrow.pos2[2], arrow.pos2[3], arrow.pos2[4], col = \"#2f6661\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n if (!is.null(title.name)) {\n title.pos = c(space.h/8, space.v)\n text(title.pos[1],title.pos[2],paste0(title.name, \" signaling network\"), cex = 1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Hierarchy plot of cell-cell communication sending to cell groups not in vertex.receiver\n#'\n#' This function loads the significant interactions as a weighted matrix, and colors\n#' represent different types of cells as a structure. The width of edges represent the strength of the communication.\n#'\n#' @param net a weighted matrix defining the signaling network\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether rescale the edge weights\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.dist the distance between labels and dot position\n#' @param space.v the space between different columns in the plot\n#' @param space.h the space between different rows in the plot\n#' @param label.edge Whether or not shows the label of edges (number of connections between different cell types)\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_\n#' @importFrom grDevices adjustcolor recordPlot\n#' @importFrom shape Arrows\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_hierarchy2 <-function(net, vertex.receiver, color.use = NULL, title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight=20, vertex.weight.max = NULL, vertex.size.max = NULL,\n edge.weight.max = NULL, edge.width.max=8,alpha.edge = 0.6,\n label.dist = 2.8, space.v = 1.5, space.h = 1.6, shape= NULL, label.edge=FALSE,edge.curved=0, margin=0.2,\n vertex.label.cex=0.6,vertex.label.color= \"black\",arrow.width=1,arrow.size = 0.2,edge.label.color='black',edge.label.cex=0.5, vertex.size = NULL){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- levels(object@idents)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- levels(object@idents)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- levels(object@idents)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n\n if (is.null(color.use)) {\n color.use <- scPalette(nrow(net))\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+6\n\n m <- length(vertex.receiver)\n m0 <- nrow(net)-length(vertex.receiver)\n net2 <- net\n reorder.row <- c(setdiff(1:nrow(net),vertex.receiver), vertex.receiver)\n net2 <- net2[reorder.row,vertex.receiver]\n # Expand out to symmetric (M+N)x(M+N) matrix\n m1 <- nrow(net2); n1 <- ncol(net2)\n net3 <- rbind(cbind(matrix(0, m1, m1), net2), matrix(0, n1, m1+n1))\n row.names(net3) <- c(row.names(net)[setdiff(1:m1,vertex.receiver)],row.names(net)[vertex.receiver], rep(\"\",m))\n colnames(net3) <- row.names(net3)\n color.use3 <- c(color.use[setdiff(1:m1,vertex.receiver)],color.use[vertex.receiver], rep(\"#FFFFFF\",length(vertex.receiver)))\n color.use3.frame <- c(color.use[setdiff(1:m1,vertex.receiver)], color.use[vertex.receiver], color.use[vertex.receiver])\n\n\n if (length(vertex.weight) != 1) {\n vertex.weight = c(vertex.weight[setdiff(1:m1,vertex.receiver)], vertex.weight[vertex.receiver], vertex.weight[vertex.receiver])\n }\n if (is.null(shape)) {\n shape <- rep(\"circle\",nrow(net3))\n }\n\n g <- graph_from_adjacency_matrix(net3, mode = \"directed\", weighted = T)\n edge.start <- ends(g, es=igraph::E(g), names=FALSE)\n coords <- matrix(NA, nrow(net3), 2)\n coords[1:m0,1] <- 0; coords[(m0+1):m1,1] <- space.h; coords[(m1+1):nrow(net3),1] <- space.h/2;\n coords[1:m0,2] <- seq(space.v, 0, by = -space.v/(m0-1)); coords[(m0+1):m1,2] <- seq(space.v, 0, by = -space.v/(m1-m0-1));coords[(m1+1):nrow(net3),2] <- seq(space.v, 0, by = -space.v/(n1-1));\n coords_scale<-coords\n\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use3[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use3.frame[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n # E(g)$width<-0.3+edge.max.width/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n igraph::E(g)$color<-adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n\n label.dist <- c(rep(space.h*label.dist,m), rep(space.h*label.dist, m1-m),rep(0, nrow(net3)-m1))\n label.locs <- c(rep(-pi, m0), rep(0, m1-m0),rep(-pi, nrow(net3)-m1))\n #text.pos <- cbind(c(-space.h/1.5, space.h/10, space.h/1.2), space.v-space.v/10)\n text.pos <- cbind(c(-space.h/1.5, space.h/22, space.h/1.5), space.v-space.v/7)\n igraph::add.vertex.shape(\"fcircle\", clip=igraph::igraph.shape.noclip,plot=mycircle, parameters=list(vertex.frame.color=1, vertex.frame.width=1))\n plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin,rescale=T,vertex.shape=\"fcircle\", vertex.frame.width = c(rep(1,m1), rep(2,nrow(net3)-m1)),\n vertex.label.degree=label.locs, vertex.label.dist=label.dist, vertex.label.family=\"Helvetica\")\n text(text.pos, c(\"Source\",\"Target\",\"Source\"), cex = 0.8, col = c(\"#c51b7d\",\"#2f6661\",\"#2f6661\"))\n\n arrow.pos1 <- c(-space.h/1.5, space.v-space.v/4, space.h/100000, space.v-space.v/4)\n arrow.pos2 <- c(space.h/1.5, space.v-space.v/4, space.h/20, space.v-space.v/4)\n shape::Arrows(arrow.pos1[1], arrow.pos1[2], arrow.pos1[3], arrow.pos1[4], col = \"#c51b7d\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n shape::Arrows(arrow.pos2[1], arrow.pos2[2], arrow.pos2[3], arrow.pos2[4], col = \"#2f6661\",arr.lwd = 0.0001,arr.length = 0.2, lwd = 0.8,arr.type=\"triangle\")\n\n if (!is.null(title.name)) {\n title.pos = c(space.h/8, space.v)\n text(title.pos[1],title.pos[2],paste0(title.name, \" signaling network\"), cex = 1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Circle plot of cell-cell communication network\n#'\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net A weighted matrix representing the connections\n#' @param color.use Colors represent different cell groups\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.edge Whether or not shows the label of edges\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param layout The layout specification. It must be a call to a layout\n#' specification function.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param text.x,text.y the x- and y-coordinates to add the text\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n#' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_ in_circle\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_circle <-function(net, color.use = NULL,title.name = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex=1,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6, label.edge = FALSE,edge.label.color='black',edge.label.cex=0.8,\n edge.curved=0.2,shape='circle',layout=in_circle(), margin=0.2, vertex.size = NULL,\n arrow.width=1,arrow.size = 0.2,\n text.x = 0, text.y = 1.5){\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use)) | (!is.null(idents.use)) ) {\n if (is.null(rownames(net))) {\n stop(\"The input weighted matrix should have rownames!\")\n }\n cells.level <- rownames(net)\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n df.net <- filter(df.net, (source %in% idents.use) | (target %in% idents.use))\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (is.null(color.use)) {\n color.use = scPalette(nrow(net))\n names(color.use) <- rownames(net)\n } else {\n if (is.null(names(color.use))) {\n stop(\"The input `color.use` should be a named vector! \\n\")\n }\n }\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx.isolate <- intersect(idx1, idx2)\n if (length(idx.isolate) > 0) {\n net <- net[-idx.isolate, ]\n net <- net[, -idx.isolate]\n color.use = color.use[-idx.isolate]\n if (length(unique(vertex.weight)) > 1) {\n vertex.weight <- vertex.weight[-idx.isolate]\n }\n }\n }\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edge.start <- igraph::ends(g, es=igraph::E(g), names=FALSE)\n coords<-layout_(g,layout)\n if(nrow(coords)!=1){\n coords_scale=scale(coords)\n }else{\n coords_scale<-coords\n }\n\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n\n loop.angle<-ifelse(coords_scale[igraph::V(g),1]>0,-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]),pi-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]))\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n #E(g)$width<-0.3+edge.width.max/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n igraph::E(g)$color<- grDevices::adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n igraph::E(g)$loop.angle <- rep(0, length(igraph::E(g)))\n\n if(sum(edge.start[,2]==edge.start[,1])!=0){\n igraph::E(g)$loop.angle[which(edge.start[,2]==edge.start[,1])]<-loop.angle[edge.start[which(edge.start[,2]==edge.start[,1]),1]]\n }\n radian.rescale <- function(x, start=0, direction=1) {\n c.rotate <- function(x) (x + start) %% (2 * pi) * direction\n c.rotate(scales::rescale(x, c(0, 2 * pi), range(x)))\n }\n label.locs <- radian.rescale(x=1:length(igraph::V(g)), direction=-1, start=0)\n label.dist <- vertex.weight/max(vertex.weight)+2\n plot(g,edge.curved=edge.curved,vertex.shape=shape,layout=coords_scale,margin=margin, vertex.label.dist=label.dist,\n vertex.label.degree=label.locs, vertex.label.family=\"Helvetica\", edge.label.family=\"Helvetica\") # \"sans\"\n if (!is.null(title.name)) {\n text(text.x,text.y,title.name, cex = 1.1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n\n#' generate circle symbol\n#'\n#' @param coords coordinates of points\n#' @param v vetex\n#' @param params parameters\n#' @importFrom graphics symbols\n#' @return\nmycircle <- function(coords, v=NULL, params) {\n vertex.color <- params(\"vertex\", \"color\")\n if (length(vertex.color) != 1 && !is.null(v)) {\n vertex.color <- vertex.color[v]\n }\n vertex.size <- 1/200 * params(\"vertex\", \"size\")\n if (length(vertex.size) != 1 && !is.null(v)) {\n vertex.size <- vertex.size[v]\n }\n vertex.frame.color <- params(\"vertex\", \"frame.color\")\n if (length(vertex.frame.color) != 1 && !is.null(v)) {\n vertex.frame.color <- vertex.frame.color[v]\n }\n vertex.frame.width <- params(\"vertex\", \"frame.width\")\n if (length(vertex.frame.width) != 1 && !is.null(v)) {\n vertex.frame.width <- vertex.frame.width[v]\n }\n\n mapply(coords[,1], coords[,2], vertex.color, vertex.frame.color,\n vertex.size, vertex.frame.width,\n FUN=function(x, y, bg, fg, size, lwd) {\n symbols(x=x, y=y, bg=bg, fg=fg, lwd=lwd,\n circles=size, add=TRUE, inches=FALSE)\n })\n}\n\n\n#' Spatial plot of cell-cell communication network\n#'\n#' Autocrine interactions are omitted on this plot. Group centroids may be not accurate for some data due to complex geometry.\n#' The width of edges represent the strength of the communication.\n#'\n#' @param net A weighted matrix representing the connections\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param meta a data frame with at least two columns named `labels` and `samples`.\n#' `meta$labels` is a vector giving the group label of each cell/spot. `meta$samples` is a factor vector defining the sample labels of each dataset. The length should be the same as the number of rows in `coordinates`.\n#' @param sample.use the sample used for visualization, which should be the element in `meta$samples`.\n#' @param color.use Colors represent different cell groups\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param idents.use a vector giving the index or the name of cell groups of interest.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param remove.loop whether remove the self-loop in the communication network. Default: TRUE\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param alpha.edge the transprency of edge\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param arrow.angle The width of arrows\n#' @param alpha.image the transparency of individual spots\n# #' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n#' @param point.size the size of spots\n#' @param legend.size the size of legend\n#' @importFrom igraph graph_from_adjacency_matrix get.edgelist ends E V\n#' @import ggplot2\n#' @importFrom ggnetwork geom_nodetext_repel\n#' @return an object of ggplot\n#' @export\nnetVisual_spatial <-function(net, coordinates, meta, sample.use = NULL, color.use = NULL,title.name = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL, remove.isolate = FALSE, remove.loop = TRUE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = NULL, vertex.label.cex = 5,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, edge.curved=0.2, alpha.edge = 0.6, arrow.angle = 5, arrow.size = 0.2, alpha.image = 0.15, point.size = 1.5, legend.size = 5){\n cells.level <- rownames(net)\n labels <- meta$labels\n samples <- meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n num_cluster <- length(cells.level)\n node_coords <- matrix(0, nrow = num_cluster, ncol = 2)\n for (i in c(1:num_cluster)) {\n node_coords[i,1] <- median(coordinates[as.character(labels) == cells.level[i], 1])\n node_coords[i,2] <- median(coordinates[as.character(labels) == cells.level[i], 2])\n }\n rownames(node_coords) <- cells.level\n\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n options(warn = -1)\n thresh <- stats::quantile(net, probs = 1-top)\n net[net < thresh] <- 0\n\n if ((!is.null(sources.use)) | (!is.null(targets.use)) | (!is.null(idents.use)) ) {\n if (is.null(rownames(net))) {\n stop(\"The input weighted matrix should have rownames!\")\n }\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n df.net <- filter(df.net, (source %in% idents.use) | (target %in% idents.use))\n }\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n\n if (remove.loop) {\n diag(net) <- 0\n }\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n node_coords <- node_coords[-idx, ]\n cells.level <- cells.level[-idx]\n }\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edgelist <- get.edgelist(g)\n # loop_curve = c()\n # for (i in c(1:nrow(edgelist))) {\n # if (edgelist[i,1] == edgelist[i,2]){\n # loop_curve = c(loop_curve ,i)\n # }\n # }\n # edgelist <- edgelist[-loop_curve,]\n\n edges <- data.frame(node_coords[edgelist[,1],,drop =FALSE], node_coords[edgelist[,2],,drop =FALSE])\n colnames(edges) <- c(\"X1\",\"Y1\",\"X2\",\"Y2\")\n node_coords = data.frame(node_coords)\n node_idents = factor(cells.level, levels = cells.level)\n node_family = data.frame(node_coords,node_idents)\n if (is.null(color.use)) {\n color.use = scPalette(length(igraph::V(g)))\n names(color.use) <- cells.level\n }\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n # width of edge\n if (weight.scale == TRUE) {\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n gg <- ggplot(data=node_family,aes(X1, X2)) +\n geom_curve(aes(x=X1, y=Y1, xend = X2, yend = Y2), data=edges, size = igraph::E(g)$width, curvature = edge.curved, alpha = alpha.edge, arrow = arrow(angle = arrow.angle, type = \"closed\",length = unit(arrow.size, \"inches\")),colour=color.use[edgelist[,1]]) +\n geom_point(aes(X1, X2,colour = node_idents), data=node_family, size = vertex.weight,show.legend = TRUE) +scale_color_manual(values = color.use) +\n guides(color = guide_legend(override.aes = list(size=legend.size))) +\n xlab(NULL) + ylab(NULL) +\n coord_fixed() + theme(aspect.ratio = 1)+ theme(legend.key = element_blank()) +\n theme(panel.background = element_blank(),axis.ticks = element_blank(), panel.border = element_blank(),axis.text=element_blank(),legend.title = element_blank())\n\n gg <- gg + geom_point(aes(x_cent, y_cent), data = coordinates,colour = color.use[labels],alpha = alpha.image, size = point.size, show.legend = FALSE)\n gg <- gg + scale_y_reverse()\n if (vertex.label.cex > 0){\n gg <- gg + ggnetwork::geom_nodetext_repel(aes(label = node_idents), color=\"black\", size = vertex.label.cex)\n }\n if (!is.null(title.name)){\n gg <- gg + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0))\n }\n\n gg\n return(gg)\n\n}\n\n\n\n\n\n\n#' Circle plot showing differential cell-cell communication network between two datasets\n#'\n#' The width of edges represent the relative number of interactions or interaction strength.\n#' Red (or blue) colored edges represent increased (or decreased) signaling in the second dataset compared to the first one.\n#'\n#' @param object A merged CellChat objects\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param color.use Colors represent different cell groups\n#' @param color.edge Colors for indicating whether the signaling is increased (`color.edge[1]`) or decreased (`color.edge[2]`)\n#' @param title.name the name of the title\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param top the fraction of interactions to show\n#' @param weight.scale whether scale the weight\n#' @param vertex.weight The weight of vertex: either a scale value or a vector\n#' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight)\n#' @param vertex.size.max the maximum vertex size for visualization\n#' @param vertex.label.cex The label size of vertex\n#' @param vertex.label.color The color of label for vertex\n#' @param edge.weight.max the maximum weight of edge; defualt = max(net)\n#' @param edge.width.max The maximum edge width for visualization\n#' @param label.edge Whether or not shows the label of edges\n#' @param alpha.edge the transprency of edge\n#' @param edge.label.color The color for single arrow\n#' @param edge.label.cex The size of label for arrows\n#' @param edge.curved Specifies whether to draw curved edges, or not.\n#' This can be a logical or a numeric vector or scalar.\n#' First the vector is replicated to have the same length as the number of\n#' edges in the graph. Then it is interpreted for each edge separately.\n#' A numeric value specifies the curvature of the edge; zero curvature means\n#' straight edges, negative values means the edge bends clockwise, positive\n#' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero\n#' @param shape The shape of the vertex, currently “circle”, “square”,\n#' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see\n#' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the\n#' plot.igraph command. “none” does not draw the vertices at all, although\n#' vertex label are plotted (if given). See shapes for details about vertex\n#' shapes and vertex.shape.pie for using pie charts as vertices.\n#' @param layout The layout specification. It must be a call to a layout\n#' specification function.\n#' @param margin The amount of empty space below, over, at the left and right\n#' of the plot, it is a numeric vector of length four. Usually values between\n#' 0 and 0.5 are meaningful, but negative values are also possible, that will\n#' make the plot zoom in to a part of the graph. If it is shorter than four\n#' then it is recycled.\n#' @param arrow.width The width of arrows\n#' @param arrow.size the size of arrow\n# #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use`\n# #' @param vertex.size Deprecated. Use `vertex.weight`\n#' @importFrom igraph graph_from_adjacency_matrix ends E V layout_ in_circle\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\nnetVisual_diffInteraction <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\", \"count.merged\", \"weight.merged\"), color.use = NULL, color.edge = c('#b2182b','#2166ac'), title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1,\n weight.scale = FALSE, vertex.weight = 20, vertex.weight.max = NULL, vertex.size.max = 15, vertex.label.cex=1,vertex.label.color= \"black\",\n edge.weight.max = NULL, edge.width.max=8, alpha.edge = 0.6, label.edge = FALSE,edge.label.color='black',edge.label.cex=0.8,\n edge.curved=0.2,shape='circle',layout=in_circle(), margin=0.2,\n arrow.width=1,arrow.size = 0.2){\n options(warn = -1)\n measure <- match.arg(measure)\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n if (measure %in% c(\"count\", \"count.merged\")) {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure %in% c(\"weight\", \"weight.merged\")) {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n net <- net.diff\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- rownames(net.diff)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n net[is.na(net)] <- 0\n }\n\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n idx <- intersect(idx1, idx2)\n net <- net[-idx, ]\n net <- net[, -idx]\n }\n\n net[abs(net) < stats::quantile(abs(net), probs = 1-top, na.rm= T)] <- 0\n\n g <- graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n edge.start <- igraph::ends(g, es=igraph::E(g), names=FALSE)\n coords<-layout_(g,layout)\n if(nrow(coords)!=1){\n coords_scale=scale(coords)\n }else{\n coords_scale<-coords\n }\n if (is.null(color.use)) {\n color.use = scPalette(length(igraph::V(g)))\n }\n if (is.null(vertex.weight.max)) {\n vertex.weight.max <- max(vertex.weight)\n }\n vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5\n\n loop.angle<-ifelse(coords_scale[igraph::V(g),1]>0,-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]),pi-atan(coords_scale[igraph::V(g),2]/coords_scale[igraph::V(g),1]))\n igraph::V(g)$size<-vertex.weight\n igraph::V(g)$color<-color.use[igraph::V(g)]\n igraph::V(g)$frame.color <- color.use[igraph::V(g)]\n igraph::V(g)$label.color <- vertex.label.color\n igraph::V(g)$label.cex<-vertex.label.cex\n if(label.edge){\n igraph::E(g)$label<-igraph::E(g)$weight\n igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1)\n }\n igraph::E(g)$arrow.width<-arrow.width\n igraph::E(g)$arrow.size<-arrow.size\n igraph::E(g)$label.color<-edge.label.color\n igraph::E(g)$label.cex<-edge.label.cex\n #igraph::E(g)$color<- grDevices::adjustcolor(igraph::V(g)$color[edge.start[,1]],alpha.edge)\n igraph::E(g)$color <- ifelse(igraph::E(g)$weight > 0, color.edge[1],color.edge[2])\n igraph::E(g)$color <- grDevices::adjustcolor(igraph::E(g)$color, alpha.edge)\n\n igraph::E(g)$weight <- abs(igraph::E(g)$weight)\n\n if (is.null(edge.weight.max)) {\n edge.weight.max <- max(igraph::E(g)$weight)\n }\n if (weight.scale == TRUE) {\n #E(g)$width<-0.3+edge.width.max/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight))\n igraph::E(g)$width<- 0.3+igraph::E(g)$weight/edge.weight.max*edge.width.max\n }else{\n igraph::E(g)$width<-0.3+edge.width.max*igraph::E(g)$weight\n }\n\n igraph::E(g)$loop.angle <- 0\n if(sum(edge.start[,2]==edge.start[,1])!=0){\n igraph::E(g)$loop.angle[which(edge.start[,2]==edge.start[,1])]<-loop.angle[edge.start[which(edge.start[,2]==edge.start[,1]),1]]\n }\n radian.rescale <- function(x, start=0, direction=1) {\n c.rotate <- function(x) (x + start) %% (2 * pi) * direction\n c.rotate(scales::rescale(x, c(0, 2 * pi), range(x)))\n }\n label.locs <- radian.rescale(x=1:length(igraph::V(g)), direction=-1, start=0)\n label.dist <- vertex.weight/max(vertex.weight)+2\n plot(g,edge.curved=edge.curved,vertex.shape=shape,layout=coords_scale,margin=margin, vertex.label.dist=label.dist,\n vertex.label.degree=label.locs, vertex.label.family=\"Helvetica\", edge.label.family=\"Helvetica\") # \"sans\"\n if (!is.null(title.name)) {\n text(0,1.5,title.name, cex = 1.1)\n }\n # https://www.andrewheiss.com/blog/2016/12/08/save-base-graphics-as-pseudo-objects-in-r/\n # grid.echo()\n # gg <- grid.grab()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Visualization of network using heatmap\n#'\n#' This heatmap can be used to 1) show differential number of interactions or interaction strength in the cell-cell communication network between two datasets;\n#' 2) the number of interactions or interaction strength in a single dataset;\n#' 3) the inferred cell-cell communication network in a single dataset, defined by `signaling`. Please see @Details below for detailed explanations of this heatmap plot.\n#'\n#' When show differential number of interactions or interaction strength in the cell-cell communication network between two datasets, the width of edges represent the relative number of interactions or interaction strength.\n#' Red (or blue) colored edges represent increased (or decreased) signaling in the second dataset compared to the first one.\n#'\n#' The top colored bar plot represents the sum of absolute values displayed in each column of the heatmap. The right colored bar plot represents the sum of absolute values in each row.\n#'\n#'\n#' @param object A merged CellChat object or a single CellChat object\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param signaling a character vector giving the name of signaling networks in a single CellChat object\n#' @param slot.name the slot name of object. Set is to be \"netP\" if input signaling is a pathway name; Set is to be \"net\" if input signaling is a ligand-receptor pair\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap A vector of two colors corresponding to max/min values, or a color name in brewer.pal only when the data in the heatmap do not contain negative values.\n#' By default, color.heatmap = c('#2166ac','#b2182b') when taking a merged CellChat object as input; color.heatmap = \"Reds\" when taking a single CellChat object as input.\n#' @param title.name the name of the title\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param remove.isolate whether remove the isolate nodes in the communication network\n#' @param row.show,col.show a vector giving the index or the name of row or columns to show in the heatmap\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation anno_barplot rowAnnotation\n#' @return an object of ComplexHeatmap\n#' @export\nnetVisual_heatmap <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\"), signaling = NULL, slot.name = c(\"netP\", \"net\"), color.use = NULL, color.heatmap = NULL,\n title.name = NULL, width = NULL, height = NULL, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE,\n sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, row.show = NULL, col.show = NULL){\n if (!is.null(measure)) {\n measure <- match.arg(measure)\n }\n slot.name <- match.arg(slot.name)\n if (class(object@net[[1]]) == \"list\") {\n message(\"Do heatmap based on a merged object \\n\")\n if (is.null(color.heatmap)) {\n color.heatmap <- c('#2166ac','#b2182b')\n }\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n legend.name = \"Relative values\"\n } else {\n message(\"Do heatmap based on a single object \\n\")\n if (is.null(color.heatmap)) {\n color.heatmap <- \"Reds\"\n }\n if (!is.null(signaling)) {\n prob <- slot(object, slot.name)$prob\n if (slot.name == \"net\") {\n prob[object@net$pval > thresh] <- 0\n }\n net.diff <- prob[,,signaling]\n if (is.null(title.name)) {\n title.name = paste0(signaling, \" signaling network\")\n }\n legend.name <- \"Communication Prob.\"\n } else if (!is.null(measure)) {\n net.diff <- object@net[[measure]]\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Interaction strength\"\n }\n }\n legend.name <- title.name\n }\n }\n\n net <- net.diff\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n cells.level <- rownames(net.diff)\n df.net$source <- factor(df.net$source, levels = cells.level)\n df.net$target <- factor(df.net$target, levels = cells.level)\n df.net$value[is.na(df.net$value)] <- 0\n net <- tapply(df.net[[\"value\"]], list(df.net[[\"source\"]], df.net[[\"target\"]]), sum)\n }\n net[is.na(net)] <- 0\n\n if (is.null(color.use)) {\n color.use <- scPalette(ncol(net))\n }\n names(color.use) <- colnames(net)\n color.use.row <- color.use\n color.use.col <- color.use\n if (remove.isolate) {\n idx1 <- which(Matrix::rowSums(net) == 0)\n idx2 <- which(Matrix::colSums(net) == 0)\n #idx <- intersect(idx1, idx2)\n # if (length(idx) > 0) {\n # net <- net[-idx, ]\n # net <- net[, -idx]\n # }\n if (length(idx1) > 0) {\n net <- net[-idx1, ]\n color.use.row <- color.use.row[-idx1]\n }\n if (length(idx2) > 0) {\n net <- net[, -idx2]\n color.use.col <- color.use.col[-idx2]\n }\n }\n\n mat <- net\n if (!is.null(row.show)) {\n mat <- mat[row.show, , drop=FALSE]\n color.use.row <- color.use.row[row.show]\n }\n if (!is.null(col.show)) {\n mat <- mat[ ,col.show, drop=FALSE]\n color.use.col <- color.use.col[col.show]\n }\n\n\n if (min(mat) < 0) {\n color.heatmap.use = colorRamp3(c(min(mat), 0, max(mat)), c(color.heatmap[1], \"#f7f7f7\", color.heatmap[2]))\n colorbar.break <- c(round(min(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",min(mat, na.rm = T)))+1), 0, round(max(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",max(mat, na.rm = T)))+1))\n # color.heatmap.use = colorRamp3(c(seq(min(mat), -(max(mat)-min(max(mat)))/9, length.out = 4), 0, seq((max(mat)-min(max(mat)))/9, max(mat), length.out = 4)), RColorBrewer::brewer.pal(n = 9, name = color.heatmap))\n } else {\n if (length(color.heatmap) == 3) {\n color.heatmap.use = colorRamp3(c(0, min(mat), max(mat)), color.heatmap)\n } else if (length(color.heatmap) == 2) {\n color.heatmap.use = colorRamp3(c(min(mat), max(mat)), color.heatmap)\n } else if (length(color.heatmap) == 1) {\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n }\n colorbar.break <- c(round(min(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",min(mat, na.rm = T)))+1), round(max(mat, na.rm = T), digits = nchar(sub(\".*\\\\.(0*).*\",\"\\\\1\",max(mat, na.rm = T)))+1))\n }\n # col_fun(as.vector(mat))\n\n df.col<- data.frame(group = colnames(mat)); rownames(df.col) <- colnames(mat)\n df.row<- data.frame(group = rownames(mat)); rownames(df.row) <- rownames(mat)\n col_annotation <- HeatmapAnnotation(df = df.col, col = list(group = color.use.col),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n row_annotation <- HeatmapAnnotation(df = df.row, col = list(group = color.use.row), which = \"row\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ha1 = rowAnnotation(Strength = anno_barplot(rowSums(abs(mat)), border = FALSE,gp = gpar(fill = color.use.row, col=color.use.row)), show_annotation_name = FALSE)\n ha2 = HeatmapAnnotation(Strength = anno_barplot(colSums(abs(mat)), border = FALSE,gp = gpar(fill = color.use.col, col=color.use.col)), show_annotation_name = FALSE)\n\n if (sum(abs(mat) > 0) == 1) {\n color.heatmap.use = c(\"white\", color.heatmap.use)\n } else {\n mat[mat == 0] <- NA\n }\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = legend.name,\n bottom_annotation = col_annotation, left_annotation =row_annotation, top_annotation = ha2, right_annotation = ha1,\n cluster_rows = cluster.rows,cluster_columns = cluster.rows,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n # width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = title.name,column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 90,\n row_title = \"Sources (Sender)\",row_title_gp = gpar(fontsize = font.size.title),row_title_rot = 90,\n heatmap_legend_param = list(title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, #at = colorbar.break,\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n # draw(ht1)\n return(ht1)\n}\n\n\n#' Visualization of (differential) number of interactions\n#'\n#' @param object A merged CellChat object or a single CellChat object\n#' @param comparison a numerical vector giving the datasets for comparison in object.list; e.g., comparison = c(1,2)\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param invert.source,invert.target retain the complementary set\n#' @param signaling a character vector giving the name of signaling networks in a single CellChat object\n#' @param slot.name the slot name of object. Set is to be \"netP\" if input signaling is a pathway name; Set is to be \"net\" if input signaling is a ligand-receptor pair\n#' @param color.use the character vector defining the color of each cell group\n#' @param title.name the name of the title\n#' @param x.lab.rot do rotation for the x-ticklabels\n#' @param ... Parameters passing to `barplot_internal`\n#' @importFrom methods slot\n#' @return an object of ggplot\n#' @export\nnetVisual_barplot <- function(object, comparison = c(1,2), measure = c(\"count\", \"weight\"), sources.use = NULL, targets.use = NULL, invert.source = FALSE, invert.target = FALSE,signaling = NULL, slot.name = c(\"netP\", \"net\"), color.use = NULL,\n title.name = NULL,x.lab.rot = FALSE,...){\n if (!is.null(measure)) {\n measure <- match.arg(measure)\n }\n slot.name <- match.arg(slot.name)\n if (is.list(object@net[[1]])) {\n message(\"Show differential number of interactions based on a merged object \\n\")\n obj1 <- object@net[[comparison[1]]][[measure]]\n obj2 <- object@net[[comparison[2]]][[measure]]\n net.diff <- obj2 - obj1\n\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Differential number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Differential interaction strength\"\n }\n }\n } else {\n message(\"Show number of interactions based on a single object \\n\")\n if (!is.null(signaling)) {\n net.diff <- slot(object, slot.name)$prob[,,signaling]\n if (is.null(title.name)) {\n title.name = paste0(signaling, \" signaling network\")\n }\n } else if (!is.null(measure)) {\n net.diff <- object@net[[measure]]\n if (measure == \"count\") {\n if (is.null(title.name)) {\n title.name = \"Number of interactions\"\n }\n } else if (measure == \"weight\") {\n if (is.null(title.name)) {\n title.name = \"Interaction strength\"\n }\n }\n }\n }\n\n net <- net.diff\n cells.level <- rownames(net.diff)\n\n if ((!is.null(sources.use)) | (!is.null(targets.use))) {\n df.net <- reshape2::melt(net, value.name = \"value\")\n colnames(df.net)[1:2] <- c(\"source\",\"target\")\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- rownames(net.diff)[sources.use]\n }\n if (invert.source == TRUE) {\n sources.use <- setdiff(rownames(net.diff), sources.use)\n }\n df.net <- subset(df.net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- rownames(net.diff)[targets.use]\n }\n if (invert.target == TRUE) {\n targets.use <- setdiff(rownames(net.diff), targets.use)\n }\n df.net <- subset(df.net, target %in% targets.use)\n }\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n }\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(cells.level))\n }\n names(color.use) <- cells.level\n color.use <- color.use[cells.level %in% unique(df.net$target)]\n\n gg <- barplot_internal(df.net, x = \"target\", y = \"value\", fill = \"target\", color.use = color.use, title.name = title.name,x.lab.rot = x.lab.rot,...)\n\n return(gg)\n\n}\n\n\n#' Show all the significant interactions (L-R pairs) from some cell groups to other cell groups\n#'\n#' The dot color and size represent the calculated communication probability and p-values.\n#'\n#' @param object CellChat object\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest and the order of L-R on y-axis\n#' @param sort.by.source,sort.by.target,sort.by.source.priority set the order of interacting cell pairs on x-axis; please check examples for details\n#' @param color.heatmap A character string or vector indicating the colormap option to use. It can be the avaibale color palette in viridis_pal() or brewer.pal()\n#' @param direction Sets the order of colors in the scale. If 1, the default colors are used. If -1, the order of colors is reversed.\n#' @param n.colors number of basic colors to generate from color palette\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param comparison a numerical vector giving the datasets for comparison in the merged object; e.g., comparison = c(1,2)\n#' @param group a numerical vector giving the group information of different datasets; e.g., group = c(1,2,2)\n#' @param remove.isolate whether to remove the entire empty columns, i.e., communication between certain cell groups\n#' @param max.dataset a scale, keeping the communications with highest probability in max.dataset (i.e., certrain condition)\n#' @param min.dataset a scale, keeping the communications with lowest probability in min.dataset (i.e., certrain condition)\n#' @param min.quantile,max.quantile minimum and maximum quantile cutoff values for the colorbar, may specify quantile in [0,1]\n#' @param line.on whether to add vertical line when doing comparison analysis for the merged object\n#' @param line.size size of vertical line if added\n#' @param color.text.use whether to color the xtick labels according to the dataset origin when doing comparison analysis\n#' @param color.text the colors for xtick labels according to the dataset origin when doing comparison analysis\n#' @param dot.size.min,dot.size.max Size of smallest and largest points\n#' @param title.name main title of the plot\n#' @param font.size,font.size.title font size of all the text and the title name\n#' @param show.legend whether to show legend\n#' @param grid.on,color.grid whether to add grid\n#' @param angle.x,vjust.x,hjust.x parameters for adjusting the rotation of xtick labels\n#' @param return.data whether to return the data.frame for replotting\n#'\n#' @return\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # show all the significant interactions (L-R pairs) from some cell groups (defined by 'sources.use') to other cell groups (defined by 'targets.use')\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), remove.isolate = FALSE)\n#'\n#' # show all the significant interactions (L-R pairs) associated with certain signaling pathways\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), signaling = c(\"CCL\",\"CXCL\"))\n#'\n#' # show all the significant interactions (L-R pairs) based on user's input (defined by `pairLR.use`; the order of L-R is also based on user's input)\n#' pairLR.use <- extractEnrichedLR(cellchat, signaling = c(\"CCL\",\"CXCL\",\"FGF\"))\n#' netVisual_bubble(cellchat, sources.use = c(3,4), targets.use = c(5:8), pairLR.use = pairLR.use, remove.isolate = TRUE)\n#'\n#' # set the order of interacting cell pairs on x-axis\n#' # (1) Default: first sort cell pairs based on the appearance of sources in levels(object@idents), and then based on the appearance of targets in levels(object@idents)\n#' # (2) sort cell pairs based on the targets.use defined by users\n#' netVisual_bubble(cellchat, targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.target = T)\n#' # (3) sort cell pairs based on the sources.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T)\n#' # (4) sort cell pairs based on the sources.use and then targets.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T, sort.by.target = T)\n#' # (5) sort cell pairs based on the targets.use and then sources.use defined by users\n#' netVisual_bubble(cellchat, sources.use = c(\"FBN1+ FIB\",\"APOE+ FIB\",\"Inflam. FIB\"), targets.use = c(\"LC\",\"Inflam. DC\",\"cDC2\",\"CD40LG+ TC\"), pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T, sort.by.target = T, sort.by.source.priority = FALSE)\n#'\n#'# show all the increased interactions in the second dataset compared to the first dataset\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:8), remove.isolate = TRUE, max.dataset = 2)\n#'\n#'# show all the decreased interactions in the second dataset compared to the first dataset\n#' netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:8), remove.isolate = TRUE, max.dataset = 1)\n#'}\nnetVisual_bubble <- function(object, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR.use = NULL, sort.by.source = FALSE, sort.by.target = FALSE, sort.by.source.priority = TRUE, color.heatmap = c(\"Spectral\",\"viridis\"), n.colors = 10, direction = -1, thresh = 0.05,\n comparison = NULL, group = NULL, remove.isolate = FALSE, max.dataset = NULL, min.dataset = NULL,\n min.quantile = 0, max.quantile = 1, line.on = TRUE, line.size = 0.2, color.text.use = TRUE, color.text = NULL, dot.size.min = NULL, dot.size.max = NULL,\n title.name = NULL, font.size = 10, font.size.title = 10, show.legend = TRUE,\n grid.on = TRUE, color.grid = \"grey90\", angle.x = 90, vjust.x = NULL, hjust.x = NULL,\n return.data = FALSE){\n color.heatmap <- match.arg(color.heatmap)\n if (is.list(object@net[[1]])) {\n message(\"Comparing communications on a merged object \\n\")\n } else {\n message(\"Comparing communications on a single object \\n\")\n }\n if (is.null(vjust.x) | is.null(hjust.x)) {\n angle=c(0, 45, 90)\n hjust=c(0, 1, 1)\n vjust=c(0, 1, 0.5)\n vjust.x = vjust[angle == angle.x]\n hjust.x = hjust[angle == angle.x]\n }\n if (length(color.heatmap) == 1) {\n color.use <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n scales::viridis_pal(option = color.heatmap, direction = -1)(n.colors)\n })\n } else {\n color.use <- color.heatmap\n }\n if (direction == -1) {\n color.use <- rev(color.use)\n }\n\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n pairLR.use$pathway_name <- as.character(pairLR.use$pathway_name)\n } else if (\"interaction_name\" %in% colnames(pairLR.use)) {\n pairLR.use$interaction_name <- as.character(pairLR.use$interaction_name)\n }\n }\n\n if (is.null(comparison)) {\n cells.level <- levels(object@idents)\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n df.net <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.net$source.target <- paste(df.net$source, df.net$target, sep = \" -> \")\n source.target <- paste(rep(sources.use, each = length(targets.use)), targets.use, sep = \" -> \")\n source.target.isolate <- setdiff(source.target, unique(df.net$source.target))\n if (length(source.target.isolate) > 0) {\n df.net.isolate <- as.data.frame(matrix(NA, nrow = length(source.target.isolate), ncol = ncol(df.net)))\n colnames(df.net.isolate) <- colnames(df.net)\n df.net.isolate$source.target <- source.target.isolate\n df.net.isolate$interaction_name_2 <- df.net$interaction_name_2[1]\n df.net.isolate$pval <- 1\n a <- stringr::str_split(df.net.isolate$source.target, \" -> \", simplify = T)\n df.net.isolate$source <- as.character(a[, 1])\n df.net.isolate$target <- as.character(a[, 2])\n df.net <- rbind(df.net, df.net.isolate)\n }\n\n df.net$pval[df.net$pval > 0.05] = 1\n df.net$pval[df.net$pval > 0.01 & df.net$pval <= 0.05] = 2\n df.net$pval[df.net$pval <= 0.01] = 3\n df.net$prob[df.net$prob == 0] <- NA\n df.net$prob.original <- df.net$prob\n df.net$prob <- -1/log(df.net$prob)\n\n idx1 <- which(is.infinite(df.net$prob) | df.net$prob < 0)\n if (sum(idx1) > 0) {\n values.assign <- seq(max(df.net$prob, na.rm = T)*1.1, max(df.net$prob, na.rm = T)*1.5, length.out = length(idx1))\n position <- sort(prob.original[idx1], index.return = TRUE)$ix\n df.net$prob[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n # rownames(df.net) <- df.net$interaction_name_2\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n group.names <- paste(rep(levels(df.net$source), each = length(levels(df.net$target))), levels(df.net$target), sep = \" -> \")\n\n df.net$interaction_name_2 <- as.character(df.net$interaction_name_2)\n df.net <- with(df.net, df.net[order(interaction_name_2),])\n df.net$interaction_name_2 <- factor(df.net$interaction_name_2, levels = unique(df.net$interaction_name_2))\n cells.order <- group.names\n df.net$source.target <- factor(df.net$source.target, levels = cells.order)\n df <- df.net\n } else {\n dataset.name <- names(object@net)\n df.net.all <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.all <- data.frame()\n for (ii in 1:length(comparison)) {\n cells.level <- levels(object@idents[[comparison[ii]]])\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n\n df.net <- df.net.all[[comparison[ii]]]\n df.net$interaction_name_2 <- as.character(df.net$interaction_name_2)\n df.net$source.target <- paste(df.net$source, df.net$target, sep = \" -> \")\n source.target <- paste(rep(sources.use, each = length(targets.use)), targets.use, sep = \" -> \")\n source.target.isolate <- setdiff(source.target, unique(df.net$source.target))\n if (length(source.target.isolate) > 0) {\n df.net.isolate <- as.data.frame(matrix(NA, nrow = length(source.target.isolate), ncol = ncol(df.net)))\n colnames(df.net.isolate) <- colnames(df.net)\n df.net.isolate$source.target <- source.target.isolate\n df.net.isolate$interaction_name_2 <- df.net$interaction_name_2[1]\n df.net.isolate$pval <- 1\n a <- stringr::str_split(df.net.isolate$source.target, \" -> \", simplify = T)\n df.net.isolate$source <- as.character(a[, 1])\n df.net.isolate$target <- as.character(a[, 2])\n df.net <- rbind(df.net, df.net.isolate)\n }\n\n df.net$source <- factor(df.net$source, levels = cells.level[cells.level %in% unique(df.net$source)])\n df.net$target <- factor(df.net$target, levels = cells.level[cells.level %in% unique(df.net$target)])\n group.names <- paste(rep(levels(df.net$source), each = length(levels(df.net$target))), levels(df.net$target), sep = \" -> \")\n group.names0 <- group.names\n group.names <- paste0(group.names0, \" (\", dataset.name[comparison[ii]], \")\")\n\n if (nrow(df.net) > 0) {\n df.net$pval[df.net$pval > 0.05] = 1\n df.net$pval[df.net$pval > 0.01 & df.net$pval <= 0.05] = 2\n df.net$pval[df.net$pval <= 0.01] = 3\n df.net$prob[df.net$prob == 0] <- NA\n df.net$prob.original <- df.net$prob\n df.net$prob <- -1/log(df.net$prob)\n } else {\n df.net <- as.data.frame(matrix(NA, nrow = length(group.names), ncol = 5))\n colnames(df.net) <- c(\"interaction_name_2\",\"source.target\",\"prob\",\"pval\",\"prob.original\")\n df.net$source.target <- group.names0\n }\n # df.net$group.names <- sub(paste0(' \\\\(',dataset.name[comparison[ii]],'\\\\)'),'',as.character(df.net$source.target))\n df.net$group.names <- as.character(df.net$source.target)\n df.net$source.target <- paste0(df.net$source.target, \" (\", dataset.name[comparison[ii]], \")\")\n df.net$dataset <- dataset.name[comparison[ii]]\n df.all <- rbind(df.all, df.net)\n }\n if (nrow(df.all) == 0) {\n stop(\"No interactions are detected. Please consider changing the cell groups for analysis. \")\n }\n\n idx1 <- which(is.infinite(df.all$prob) | df.all$prob < 0)\n if (sum(idx1) > 0) {\n values.assign <- seq(max(df.all$prob, na.rm = T)*1.1, max(df.all$prob, na.rm = T)*1.5, length.out = length(idx1))\n position <- sort(df.all$prob.original[idx1], index.return = TRUE)$ix\n df.all$prob[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n\n df.all$interaction_name_2[is.na(df.all$interaction_name_2)] <- df.all$interaction_name_2[!is.na(df.all$interaction_name_2)][1]\n\n df <- df.all\n df <- with(df, df[order(interaction_name_2),])\n df$interaction_name_2 <- factor(df$interaction_name_2, levels = unique(df$interaction_name_2))\n\n cells.order <- c()\n dataset.name.order <- c()\n for (i in 1:length(group.names0)) {\n for (j in 1:length(comparison)) {\n cells.order <- c(cells.order, paste0(group.names0[i], \" (\", dataset.name[comparison[j]], \")\"))\n dataset.name.order <- c(dataset.name.order, dataset.name[comparison[j]])\n }\n }\n df$source.target <- factor(df$source.target, levels = cells.order)\n }\n\n min.cutoff <- quantile(df$prob, min.quantile,na.rm= T)\n max.cutoff <- quantile(df$prob, max.quantile,na.rm= T)\n df$prob[df$prob < min.cutoff] <- min.cutoff\n df$prob[df$prob > max.cutoff] <- max.cutoff\n\n\n if (remove.isolate) {\n df <- df[!is.na(df$prob), ]\n line.on <- FALSE\n }\n if (!is.null(max.dataset)) {\n # line.on <- FALSE\n # df <- df[!is.na(df$prob),]\n signaling <- as.character(unique(df$interaction_name_2))\n for (i in signaling) {\n df.i <- df[df$interaction_name_2 == i, ,drop = FALSE]\n cell <- as.character(unique(df.i$group.names))\n for (j in cell) {\n df.i.j <- df.i[df.i$group.names == j, , drop = FALSE]\n values <- df.i.j$prob\n idx.max <- which(values == max(values, na.rm = T))\n idx.min <- which(values == min(values, na.rm = T))\n #idx.na <- c(which(is.na(values)), which(!(dataset.name[comparison] %in% df.i.j$dataset)))\n dataset.na <- c(df.i.j$dataset[is.na(values)], setdiff(dataset.name[comparison], df.i.j$dataset))\n if (length(idx.max) > 0) {\n if (all(!(df.i.j$dataset[idx.max] %in% dataset.name[max.dataset]))) {\n df.i.j$prob <- NA\n } else if (all((idx.max != idx.min) & !is.null(min.dataset))) {\n if (all(!(df.i.j$dataset[idx.min] %in% dataset.name[min.dataset]))) {\n df.i.j$prob <- NA\n } else if (length(dataset.na) > 0 & sum(!(dataset.name[min.dataset] %in% dataset.na)) > 0) {\n df.i.j$prob <- NA\n }\n }\n }\n df.i[df.i$group.names == j, \"prob\"] <- df.i.j$prob\n }\n df[df$interaction_name_2 == i, \"prob\"] <- df.i$prob\n }\n #df <- df[!is.na(df$prob), ]\n }\n if (remove.isolate) {\n df <- df[!is.na(df$prob), ]\n line.on <- FALSE\n }\n if (nrow(df) == 0) {\n stop(\"No interactions are detected. Please consider changing the cell groups for analysis. \")\n }\n # Re-order y-axis\n if (!is.null(pairLR.use)) {\n interaction_name_2.order <- intersect(object@DB$interaction[pairLR.use$interaction_name, ]$interaction_name_2, unique(df$interaction_name_2))\n df$interaction_name_2 <- factor(df$interaction_name_2, levels = interaction_name_2.order)\n }\n\n # Re-order x-axis\n df$source.target = droplevels(df$source.target, exclude = setdiff(levels(df$source.target),unique(df$source.target)))\n if (sort.by.target & !sort.by.source) {\n if (!is.null(targets.use)) {\n df$target <- factor(df$target, levels = intersect(targets.use, df$target))\n df <- with(df, df[order(target, source),])\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n if (sort.by.source & !sort.by.target) {\n if (!is.null(sources.use)) {\n df$source <- factor(df$source, levels = intersect(sources.use, df$source))\n df <- with(df, df[order(source, target),])\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n if (sort.by.source & sort.by.target) {\n if (!is.null(sources.use)) {\n df$source <- factor(df$source, levels = intersect(sources.use, df$source))\n if (!is.null(targets.use)) {\n df$target <- factor(df$target, levels = intersect(targets.use, df$target))\n }\n if (sort.by.source.priority) {\n df <- with(df, df[order(source, target),])\n } else {\n df <- with(df, df[order(target, source),])\n }\n\n source.target.order <- unique(as.character(df$source.target))\n df$source.target <- factor(df$source.target, levels = source.target.order)\n }\n }\n\n g <- ggplot(df, aes(x = source.target, y = interaction_name_2, color = prob, size = pval)) +\n geom_point(pch = 16) +\n theme_linedraw() + theme(panel.grid.major = element_blank()) +\n theme(axis.text.x = element_text(angle = angle.x, hjust= hjust.x, vjust = vjust.x),\n axis.title.x = element_blank(),\n axis.title.y = element_blank()) +\n scale_x_discrete(position = \"bottom\")\n\n values <- c(1,2,3); names(values) <- c(\"p > 0.05\", \"0.01 < p < 0.05\",\"p < 0.01\")\n if (is.null(dot.size.max)) {\n dot.size.max = max(df$pval)\n }\n if (is.null(dot.size.min)) {\n dot.size.min = min(df$pval)\n }\n g <- g + scale_radius(range = c(dot.size.min, dot.size.max), breaks = sort(unique(df$pval)),labels = names(values)[values %in% sort(unique(df$pval))], name = \"p-value\")\n #g <- g + scale_radius(range = c(1,3), breaks = values,labels = names(values), name = \"p-value\")\n if (min(df$prob, na.rm = T) != max(df$prob, na.rm = T)) {\n g <- g + scale_colour_gradientn(colors = colorRampPalette(color.use)(99), na.value = \"white\", limits=c(quantile(df$prob, 0,na.rm= T), quantile(df$prob, 1,na.rm= T)),\n breaks = c(quantile(df$prob, 0,na.rm= T), quantile(df$prob, 1,na.rm= T)), labels = c(\"min\",\"max\")) +\n guides(color = guide_colourbar(barwidth = 0.5, title = \"Commun. Prob.\"))\n } else {\n g <- g + scale_colour_gradientn(colors = colorRampPalette(color.use)(99), na.value = \"white\") +\n guides(color = guide_colourbar(barwidth = 0.5, title = \"Commun. Prob.\"))\n }\n\n g <- g + theme(text = element_text(size = font.size),plot.title = element_text(size=font.size.title)) +\n theme(legend.title = element_text(size = 8), legend.text = element_text(size = 6))\n\n if (grid.on) {\n if (length(unique(df$source.target)) > 1) {\n g <- g + geom_vline(xintercept=seq(1.5, length(unique(df$source.target))-0.5, 1),lwd=0.1,colour=color.grid)\n }\n if (length(unique(df$interaction_name_2)) > 1) {\n g <- g + geom_hline(yintercept=seq(1.5, length(unique(df$interaction_name_2))-0.5, 1),lwd=0.1,colour=color.grid)\n }\n }\n if (!is.null(title.name)) {\n g <- g + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5))\n }\n\n if (!is.null(comparison)) {\n if (line.on) {\n xintercept = seq(0.5+length(dataset.name[comparison]), length(group.names0)*length(dataset.name[comparison]), by = length(dataset.name[comparison]))\n g <- g + geom_vline(xintercept = xintercept, linetype=\"dashed\", color = \"grey60\", size = line.size)\n }\n if (color.text.use) {\n if (is.null(group)) {\n group <- 1:length(comparison)\n names(group) <- dataset.name[comparison]\n }\n if (is.null(color.text)) {\n color <- ggPalette(length(unique(group)))\n } else {\n color <- color.text\n }\n names(color) <- names(group[!duplicated(group)])\n color <- color[group]\n #names(color) <- dataset.name[comparison]\n dataset.name.order <- levels(df$source.target)\n dataset.name.order <- stringr::str_match(dataset.name.order, \"\\\\(.*\\\\)\")\n dataset.name.order <- stringr::str_sub(dataset.name.order, 2, stringr::str_length(dataset.name.order)-1)\n xtick.color <- color[dataset.name.order]\n g <- g + theme(axis.text.x = element_text(colour = xtick.color))\n }\n }\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (return.data) {\n return(list(communication = df, gg.obj = g))\n } else {\n return(g)\n }\n\n}\n\n\n\n\n#' Chord diagram for visualizing cell-cell communication for a signaling pathway\n#'\n#' Names of cell states will be displayed in this chord diagram\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the name of signaling networks\n#' @param net a weighted matrix or a data frame with three columns defining the cell-cell communication network\n#' @param slot.name the slot name of object: slot.name = \"net\" when visualizing cell-cell communication network per each ligand-receptor pair associated with a given signaling pathway;\n#' slot.name = \"netP\" when visualizing cell-cell communication network at the level of signaling pathways\n#' @param color.use colors for the cell groups\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param remove.isolate whether remove sectors without any links\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param nCol number of columns when displaying the figures\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param ... other parameters passing to chordDiagram\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_cell <- function(object, signaling = NULL, net = NULL, slot.name = \"netP\",\n color.use = NULL,group = NULL,cell.order = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n remove.isolate = FALSE, link.visible = TRUE, scale = FALSE, directional = 1,link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20, nCol = NULL,\n thresh = 0.05,...){\n\n if (!is.null(signaling)) {\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n net <- object@net\n\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n\n prob <- prob[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n }\n\n if (slot.name == \"netP\") {\n message(\"Plot the aggregated cell-cell communication network at the signaling pathway level\")\n net <- apply(prob, c(1,2), sum)\n if (is.null(title.name)) {\n title.name <- paste0(signaling, \" signaling pathway network\")\n }\n # par(mfrow = c(1,1), xpd=TRUE)\n # par(mar = c(5, 4, 4, 2))\n gg <- netVisual_chord_cell_internal(net, color.use = color.use, group = group, cell.order = cell.order, sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap, big.gap = big.gap,annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y, ...)\n } else if (slot.name == \"net\") {\n message(\"Plot the cell-cell communication network per each ligand-receptor pair associated with a given signaling pathway\")\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n # layout(matrix(1:length(pairLR.name.use), ncol = nCol))\n # par(xpd=TRUE)\n # par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE, mar = c(5, 4, 4, 2) +0.1)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n gg <- vector(\"list\", length(pairLR.name.use))\n for (i in 1:length(pairLR.name.use)) {\n #par(mar = c(5, 4, 4, 2))\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n gg[[i]] <- netVisual_chord_cell_internal(net, color.use = color.use, group = group,cell.order = cell.order,sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap,big.gap = big.gap, annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y, ...)\n }\n }\n\n } else if (!is.null(net)) {\n gg <- netVisual_chord_cell_internal(net, color.use = color.use, group = group,cell.order = cell.order,sources.use = sources.use, targets.use = targets.use,\n lab.cex = lab.cex,small.gap = small.gap, big.gap = big.gap,annotationTrackHeight = annotationTrackHeight,\n remove.isolate = remove.isolate, link.visible = link.visible, scale = scale, directional = directional,link.target.prop = link.target.prop, reduce = reduce,\n transparency = transparency, link.border = link.border,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y, ...)\n } else {\n stop(\"Please assign values to either `signaling` or `net`\")\n }\n\n return(gg)\n}\n\n\n#' Chord diagram for visualizing cell-cell communication from a weighted adjacency matrix or a data frame\n#'\n#' Names of cell states/groups will be displayed in this chord diagram\n#'\n#' @param net a weighted matrix or a data frame with three columns defining the cell-cell communication network\n#' @param color.use colors for the cell groups\n#' @param group A named group labels for making multiple-group Chord diagrams. The sector names should be used as the names in the vector.\n#' The order of group controls the sector orders and if group is set as a factor, the order of levels controls the order of groups.\n#' @param cell.order a char vector defining the cell type orders (sector orders)\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param remove.isolate whether remove sectors without any links\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name of the plot\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param ... other parameters passing to chordDiagram\n#' @importFrom circlize circos.clear chordDiagram circos.track circos.text get.cell.meta.data\n#' @importFrom grDevices recordPlot\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_cell_internal <- function(net, color.use = NULL, group = NULL, cell.order = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n remove.isolate = FALSE, link.visible = TRUE, scale = FALSE, directional = 1, link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, show.legend = FALSE, legend.pos.x = 20, legend.pos.y = 20,...){\n if (inherits(x = net, what = c(\"matrix\", \"Matrix\"))) {\n cell.levels <- union(rownames(net), colnames(net))\n net <- reshape2::melt(net, value.name = \"prob\")\n colnames(net)[1:2] <- c(\"source\",\"target\")\n } else if (is.data.frame(net)) {\n if (all(c(\"source\",\"target\", \"prob\") %in% colnames(net)) == FALSE) {\n stop(\"The input data frame must contain three columns named as source, target, prob\")\n }\n cell.levels <- as.character(union(net$source,net$target))\n }\n if (!is.null(cell.order)) {\n cell.levels <- cell.order\n }\n net$source <- as.character(net$source)\n net$target <- as.character(net$target)\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cell.levels[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cell.levels[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n }\n # remove the interactions with zero values\n net <- subset(net, prob > 0)\n if(dim(net)[1]<=0){message(\"No interaction between those cells\")}\n # create a fake data if keeping the cell types (i.e., sectors) without any interactions\n if (!remove.isolate) {\n cells.removed <- setdiff(cell.levels, as.character(union(net$source,net$target)))\n if (length(cells.removed) > 0) {\n net.fake <- data.frame(cells.removed, cells.removed, 1e-10*sample(length(cells.removed), length(cells.removed)))\n colnames(net.fake) <- colnames(net)\n net <- rbind(net, net.fake)\n link.visible <- net[, 1:2]\n link.visible$plot <- FALSE\n if(nrow(net) > nrow(net.fake)){\n link.visible$plot[1:(nrow(net) - nrow(net.fake))] <- TRUE\n }\n # directional <- net[, 1:2]\n # directional$plot <- 0\n # directional$plot[1:(nrow(net) - nrow(net.fake))] <- 1\n # link.arr.type = \"big.arrow\"\n # message(\"Set scale = TRUE when remove.isolate = FALSE\")\n scale = TRUE\n }\n }\n\n df <- net\n cells.use <- union(df$source,df$target)\n\n # define grid order\n order.sector <- cell.levels[cell.levels %in% cells.use]\n\n # define grid color\n if (is.null(color.use)){\n color.use = scPalette(length(cell.levels))\n names(color.use) <- cell.levels\n } else if (is.null(names(color.use))) {\n names(color.use) <- cell.levels\n }\n grid.col <- color.use[order.sector]\n names(grid.col) <- order.sector\n\n # set grouping information\n if (!is.null(group)) {\n group <- group[names(group) %in% order.sector]\n }\n\n # define edge color\n edge.color <- color.use[as.character(df$source)]\n\n if (directional == 0 | directional == 2) {\n link.arr.type = \"triangle\"\n } else {\n link.arr.type = \"big.arrow\"\n }\n\n circos.clear()\n chordDiagram(df,\n order = order.sector,\n col = edge.color,\n grid.col = grid.col,\n transparency = transparency,\n link.border = link.border,\n directional = directional,\n direction.type = c(\"diffHeight\",\"arrows\"),\n link.arr.type = link.arr.type, # link.border = \"white\",\n annotationTrack = \"grid\",\n annotationTrackHeight = annotationTrackHeight,\n preAllocateTracks = list(track.height = max(strwidth(order.sector))),\n small.gap = small.gap,\n big.gap = big.gap,\n link.visible = link.visible,\n scale = scale,\n group = group,\n link.target.prop = link.target.prop,\n reduce = reduce,\n ...)\n circos.track(track.index = 1, panel.fun = function(x, y) {\n xlim = get.cell.meta.data(\"xlim\")\n xplot = get.cell.meta.data(\"xplot\")\n ylim = get.cell.meta.data(\"ylim\")\n sector.name = get.cell.meta.data(\"sector.index\")\n circos.text(mean(xlim), ylim[1], sector.name, facing = \"clockwise\", niceFacing = TRUE, adj = c(0, 0.5),cex = lab.cex)\n }, bg.border = NA)\n\n # https://jokergoo.github.io/circlize_book/book/legends.html\n if (show.legend) {\n lgd <- ComplexHeatmap::Legend(at = names(grid.col), type = \"grid\", legend_gp = grid::gpar(fill = grid.col), title = \"Cell State\")\n ComplexHeatmap::draw(lgd, x = unit(1, \"npc\")-unit(legend.pos.x, \"mm\"), y = unit(legend.pos.y, \"mm\"), just = c(\"right\", \"bottom\"))\n }\n\n if(!is.null(title.name)){\n # title(title.name, cex = 1)\n text(-0, 1.02, title.name, cex=1)\n }\n circos.clear()\n gg <- recordPlot()\n return(gg)\n}\n\n\n#' Chord diagram for visualizing cell-cell communication for a set of ligands/receptors or signaling pathways\n#'\n#' Names of ligands/receptors or signaling pathways will be displayed in this chord diagram\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object: slot.name = \"net\" when visualizing links at the level of ligands/receptors; slot.name = \"netP\" when visualizing links at the level of signaling pathways\n#' @param signaling a character vector giving the name of signaling networks\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param net A data frame consisting of the interactions of interest.\n#' net should have at least three columns: \"source\",\"target\" and \"interaction_name\" when visualizing links at the level of ligands/receptors;\n#' \"source\",\"target\" and \"pathway_name\" when visualizing links at the level of signaling pathway; \"interaction_name\" and \"pathway_name\" must be the matched names in CellChatDB$interaction.\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param color.use colors for the cell groups\n#' @param lab.cex font size for the text\n#' @param small.gap Small gap between sectors.\n#' @param big.gap Gap between the different sets of sectors, which are defined in the `group` parameter\n#' @param annotationTrackHeight annotationTrack Height\n#' @param link.visible whether plot the link. The value is logical, if it is set to FALSE, the corresponding link will not plotted, but the space is still ocuppied. The format is a matrix with names or a data frame with three columns\n#' @param scale scale each sector to same width; default = FALSE; however, it is set to be TRUE when remove.isolate = TRUE\n#' @param link.target.prop If the Chord diagram is directional, for each source sector, whether to draw bars that shows the proportion of target sectors.\n#' @param reduce if the ratio of the width of certain grid compared to the whole circle is less than this value, the grid is removed on the plot. Set it to value less than zero if you want to keep all tiny grid.\n#' @param directional Whether links have directions. 1 means the direction is from the first column in df to the second column, -1 is the reverse, 0 is no direction, and 2 for two directional.\n#' @param transparency Transparency of link colors\n#' @param link.border border for links, single scalar or a matrix with names or a data frame with three columns\n#' @param title.name title name of the plot\n#' @param show.legend whether show the figure legend\n#' @param legend.pos.x,legend.pos.y adjust the legend position\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param ... other parameters to chordDiagram\n#' @importFrom circlize circos.clear chordDiagram circos.track circos.text get.cell.meta.data\n#' @importFrom dplyr select %>% group_by summarize\n#' @importFrom grDevices recordPlot\n#' @importFrom stringr str_split\n#' @return an object of class \"recordedplot\"\n#' @export\n\nnetVisual_chord_gene <- function(object, slot.name = \"net\", color.use = NULL,\n signaling = NULL, pairLR.use = NULL, net = NULL,\n sources.use = NULL, targets.use = NULL,\n lab.cex = 0.8,small.gap = 1, big.gap = 10, annotationTrackHeight = c(0.03),\n link.visible = TRUE, scale = FALSE, directional = 1, link.target.prop = TRUE, reduce = -1,\n transparency = 0.4, link.border = NA,\n title.name = NULL, legend.pos.x = 20, legend.pos.y = 20, show.legend = TRUE,\n thresh = 0.05,\n ...){\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use) | sum(c(\"interaction_name\",\"pathway_name\") %in% colnames(pairLR.use) == 0)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n message(\"slot.name is set to be 'netP' when pairLR.use contains signaling pathways\")\n slot.name = \"netP\"\n }\n }\n\n if (!is.null(pairLR.use) & !is.null(signaling)) {\n stop(\"Please do not assign values to 'signaling' when using 'pairLR.use'\")\n }\n\n if (is.null(net)) {\n prob <- slot(object, \"net\")$prob\n pval <- slot(object, \"net\")$pval\n prob[pval > thresh] <- 0\n net <- reshape2::melt(prob, value.name = \"prob\")\n colnames(net)[1:3] <- c(\"source\",\"target\",\"interaction_name\")\n cols.default <- c(\"interaction_name_2\", \"pathway_name\", \"ligand\", \"receptor\" ,\"annotation\",\"evidence\")\n cols.common <- intersect(cols.default,colnames(object@LR$LRsig))\n pairLR = dplyr::select(object@LR$LRsig, cols.common)\n idx <- match(net$interaction_name, rownames(pairLR))\n temp <- pairLR[idx,]\n net <- cbind(net, temp)\n }\n\n if (!is.null(signaling)) {\n pairLR.use <- data.frame()\n for (i in 1:length(signaling)) {\n pairLR.use.i <- searchPair(signaling = signaling[i], pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.use <- rbind(pairLR.use, pairLR.use.i)\n }\n }\n\n if (!is.null(pairLR.use)){\n if (\"interaction_name\" %in% colnames(pairLR.use)) {\n net <- subset(net,interaction_name %in% pairLR.use$interaction_name)\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n net <- subset(net, pathway_name %in% as.character(pairLR.use$pathway_name))\n }\n }\n\n if (slot.name == \"netP\") {\n net <- dplyr::select(net, c(\"source\",\"target\",\"pathway_name\",\"prob\"))\n net$source_target <- paste(net$source, net$target, sep = \"sourceTotarget\")\n net <- net %>% dplyr::group_by(source_target, pathway_name) %>% dplyr::summarize(prob = sum(prob))\n a <- stringr::str_split(net$source_target, \"sourceTotarget\", simplify = T)\n net$source <- as.character(a[, 1])\n net$target <- as.character(a[, 2])\n net$ligand <- net$pathway_name\n net$receptor <- \" \"\n }\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- levels(object@idents)[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n } else {\n sources.use <- levels(object@idents)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- levels(object@idents)[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n } else {\n targets.use <- levels(object@idents)\n }\n # remove the interactions with zero values\n df <- subset(net, prob > 0)\n\n if (nrow(df) == 0) {\n stop(\"No signaling links are inferred! \")\n }\n\n if (length(unique(net$ligand)) == 1) {\n message(\"You may try the function `netVisual_chord_cell` for visualizing individual signaling pathway\")\n }\n\n df$id <- 1:nrow(df)\n # deal with duplicated sector names\n ligand.uni <- unique(df$ligand)\n for (i in 1:length(ligand.uni)) {\n df.i <- df[df$ligand == ligand.uni[i], ]\n source.uni <- unique(df.i$source)\n for (j in 1:length(source.uni)) {\n df.i.j <- df.i[df.i$source == source.uni[j], ]\n df.i.j$ligand <- paste0(df.i.j$ligand, paste(rep(' ',j-1),collapse = ''))\n df$ligand[df$id %in% df.i.j$id] <- df.i.j$ligand\n }\n }\n receptor.uni <- unique(df$receptor)\n for (i in 1:length(receptor.uni)) {\n df.i <- df[df$receptor == receptor.uni[i], ]\n target.uni <- unique(df.i$target)\n for (j in 1:length(target.uni)) {\n df.i.j <- df.i[df.i$target == target.uni[j], ]\n df.i.j$receptor <- paste0(df.i.j$receptor, paste(rep(' ',j-1),collapse = ''))\n df$receptor[df$id %in% df.i.j$id] <- df.i.j$receptor\n }\n }\n\n cell.order.sources <- levels(object@idents)[levels(object@idents) %in% sources.use]\n cell.order.targets <- levels(object@idents)[levels(object@idents) %in% targets.use]\n\n df$source <- factor(df$source, levels = cell.order.sources)\n df$target <- factor(df$target, levels = cell.order.targets)\n # df.ordered.source <- df[with(df, order(source, target, -prob)), ]\n # df.ordered.target <- df[with(df, order(target, source, -prob)), ]\n df.ordered.source <- df[with(df, order(source, -prob)), ]\n df.ordered.target <- df[with(df, order(target, -prob)), ]\n\n order.source <- unique(df.ordered.source[ ,c('ligand','source')])\n order.target <- unique(df.ordered.target[ ,c('receptor','target')])\n\n # define sector order\n order.sector <- c(order.source$ligand, order.target$receptor)\n\n # define cell type color\n if (is.null(color.use)){\n color.use = scPalette(nlevels(object@idents))\n names(color.use) <- levels(object@idents)\n color.use <- color.use[levels(object@idents) %in% as.character(union(df$source,df$target))]\n } else if (is.null(names(color.use))) {\n names(color.use) <- levels(object@idents)\n color.use <- color.use[levels(object@idents) %in% as.character(union(df$source,df$target))]\n }\n\n # define edge color\n edge.color <- color.use[as.character(df.ordered.source$source)]\n names(edge.color) <- as.character(df.ordered.source$source)\n\n # define grid colors\n grid.col.ligand <- color.use[as.character(order.source$source)]\n names(grid.col.ligand) <- as.character(order.source$source)\n grid.col.receptor <- color.use[as.character(order.target$target)]\n names(grid.col.receptor) <- as.character(order.target$target)\n grid.col <- c(as.character(grid.col.ligand), as.character(grid.col.receptor))\n names(grid.col) <- order.sector\n\n df.plot <- df.ordered.source[ ,c('ligand','receptor','prob')]\n\n if (directional == 2) {\n link.arr.type = \"triangle\"\n } else {\n link.arr.type = \"big.arrow\"\n }\n circos.clear()\n chordDiagram(df.plot,\n order = order.sector,\n col = edge.color,\n grid.col = grid.col,\n transparency = transparency,\n link.border = link.border,\n directional = directional,\n direction.type = c(\"diffHeight\",\"arrows\"),\n link.arr.type = link.arr.type,\n annotationTrack = \"grid\",\n annotationTrackHeight = annotationTrackHeight,\n preAllocateTracks = list(track.height = max(strwidth(order.sector))),\n small.gap = small.gap,\n big.gap = big.gap,\n link.visible = link.visible,\n scale = scale,\n link.target.prop = link.target.prop,\n reduce = reduce,\n ...)\n\n circos.track(track.index = 1, panel.fun = function(x, y) {\n xlim = get.cell.meta.data(\"xlim\")\n xplot = get.cell.meta.data(\"xplot\")\n ylim = get.cell.meta.data(\"ylim\")\n sector.name = get.cell.meta.data(\"sector.index\")\n circos.text(mean(xlim), ylim[1], sector.name, facing = \"clockwise\", niceFacing = TRUE, adj = c(0, 0.5),cex = lab.cex)\n }, bg.border = NA)\n\n # https://jokergoo.github.io/circlize_book/book/legends.html\n if (show.legend) {\n lgd <- ComplexHeatmap::Legend(at = names(color.use), type = \"grid\", legend_gp = grid::gpar(fill = color.use), title = \"Cell State\")\n ComplexHeatmap::draw(lgd, x = unit(1, \"npc\")-unit(legend.pos.x, \"mm\"), y = unit(legend.pos.y, \"mm\"), just = c(\"right\", \"bottom\"))\n }\n\n circos.clear()\n if(!is.null(title.name)){\n text(-0, 1.02, title.name, cex=1)\n }\n gg <- recordPlot()\n return(gg)\n}\n\n\n\n\n#' River plot showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways\n#'\n#' River (alluvial) plot shows the correspondence between the inferred latent patterns and cell groups as well as ligand-receptor pairs or signaling pathways.\n#'\n#' The thickness of the flow indicates the contribution of the cell group or signaling pathway to each latent pattern. The height of each pattern is proportional to the number of its associated cell groups or signaling pathways.\n#'\n#' Outgoing patterns reveal how the sender cells coordinate with each other as well as how they coordinate with certain signaling pathways to drive communication.\n#'\n#' Incoming patterns show how the target cells coordinate with each other as well as how they coordinate with certain signaling pathways to respond to incoming signaling.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object: “netP” or “net”. Use “netP” to analyze cell-cell communication at the level of signaling pathways, and “net” to analyze cell-cell communication at the level of ligand-receptor pairs.\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param cutoff the threshold for filtering out weak links\n#' @param sources.use a vector giving the index or the name of source cell groups of interest\n#' @param targets.use a vector giving the index or the name of target cell groups of interest\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.use.pattern the character vector defining the color of each pattern\n#' @param color.use.signaling the character vector defining the color of each signaling\n#' @param do.order whether reorder the cell groups or signaling according to their similarity\n#' @param main.title the title of plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom methods slot\n#' @importFrom stats cutree dist hclust\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @import ggalluvial\n# #' @importFrom ggalluvial geom_stratum geom_flow to_lodes_form\n#' @importFrom ggplot2 geom_text scale_x_discrete scale_fill_manual theme ggtitle\n#' @importFrom cowplot plot_grid ggdraw draw_label\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_river <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = 0.5,\n sources.use = NULL, targets.use = NULL, signaling = NULL,\n color.use = NULL, color.use.pattern = NULL, color.use.signaling = \"grey50\",\n do.order = FALSE, main.title = NULL,\n font.size = 2.5, font.size.title = 12){\n message(\"Please make sure you have load `library(ggalluvial)` when running this function\")\n requireNamespace(\"ggalluvial\")\n # suppressMessages(require(ggalluvial))\n res.pattern <- methods::slot(object, slot.name)$pattern[[pattern]]\n data1 = res.pattern$pattern$cell\n data2 = res.pattern$pattern$signaling\n if (is.null(color.use.pattern)) {\n nPatterns <- length(unique(data1$Pattern))\n if (pattern == \"outgoing\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(1,nPatterns*2, by = 2)]\n } else if (pattern == \"incoming\") {\n color.use.pattern = ggPalette(nPatterns*2)[seq(2,nPatterns*2, by = 2)]\n }\n }\n if (is.null(main.title)) {\n if (pattern == \"outgoing\") {\n main.title = \"Outgoing communication patterns of secreting cells\"\n } else if (pattern == \"incoming\") {\n main.title = \"Incoming communication patterns of target cells\"\n }\n }\n\n if (is.null(data2)) {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n if (is.null(color.use)) {\n color.use <- scPalette(nCellGroup)\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n gg <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10))+\n ggtitle(main.title)\n\n } else {\n data1$Contribution[data1$Contribution < cutoff] <- 0\n plot.data <- data1\n nPatterns<-length(unique(plot.data$Pattern))\n nCellGroup<-length(unique(plot.data$CellGroup))\n cells.level = levels(object@idents)\n if (is.null(color.use)) {\n color.use <- scPalette(length(cells.level))[cells.level %in% unique(plot.data$CellGroup)]\n }\n if (is.null(color.use.pattern)){\n color.use.pattern <- ggPalette(nPatterns)\n }\n if (!is.null(sources.use)) {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% sources.use)\n }\n if (!is.null(targets.use)) {\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n plot.data <- subset(plot.data, CellGroup %in% targets.use)\n }\n ## connect cell groups with patterns\n plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Pattern\"]]), sum)\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n color.use <- color.use[order.name]\n }\n color.use.all <- c(color.use, color.use.pattern)\n StatStratum <- ggalluvial::StatStratum\n gg1 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"CellGroup\", \"Pattern\")),y=Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"backward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) +\n scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Patterns\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size=10)) +\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n ## connect patterns with signaling\n data2$Contribution[data2$Contribution < cutoff] <- 0\n plot.data <- data2\n nPatterns<-length(unique(plot.data$Pattern))\n nSignaling<-length(unique(plot.data$Signaling))\n if (length(color.use.signaling) == 1) {\n color.use.all <- c(color.use.pattern, rep(color.use.signaling, nSignaling))\n } else {\n color.use.all <- c(color.use.pattern, color.use.signaling)\n }\n\n if (!is.null(signaling)) {\n plot.data <- plot.data[plot.data$Signaling %in% signaling, ]\n }\n\n plot.data.long <- ggalluvial::to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n if (do.order) {\n mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"Signaling\"]], plot.data[[\"Pattern\"]]), sum)\n mat[is.na(mat)] <- 0; mat <- mat[-which(rowSums(mat) == 0), ]\n d <- dist(as.matrix(mat))\n hc <- hclust(d, \"ave\")\n k <- length(unique(grep(\"Pattern\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n cluster <- hc %>% cutree(k)\n order.name <- order(cluster)\n plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(colnames(mat),names(cluster)[order.name]))\n }\n\n gg2 <- ggplot(plot.data.long,aes(x = factor(x, levels = c(\"Pattern\", \"Signaling\")),y= Contribution,\n stratum = stratum, alluvium = connection,\n fill = stratum, label = stratum)) +\n geom_flow(width = 1/3,aes.flow = \"forward\") +\n geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n geom_text(stat = \"stratum\", size = font.size) + # 2.5\n scale_x_discrete(limits = c(), labels=c(\"Patterns\", \"Signaling\")) +\n scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n theme_bw()+\n theme(legend.position = \"none\",\n axis.title = element_blank(),\n axis.text.y= element_blank(),\n panel.grid.major = element_blank(),\n panel.grid.minor = element_blank(),\n panel.border = element_blank(),\n axis.ticks = element_blank(),axis.text=element_text(size= 10))+\n theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n ## connect cell groups with signaling\n # data1 = data1[data1$Contribution > 0,]\n # data2 = data2[data2$Contribution > 0,]\n\n # data3 = merge(data1, data2, by.x=\"Pattern\", by.y=\"Pattern\")\n # data3$Contribution <- data3$Contribution.x * data3$Contribution.y\n # data3 <- data3[,colnames(data3) %in% c(\"CellGroup\",\"Signaling\",\"Contribution\")]\n\n # plot.data <- data3\n # nSignaling<-length(unique(plot.data$Signaling))\n # nCellGroup<-length(unique(plot.data$CellGroup))\n #\n # if (length(color.use.signaling) == 1) {\n # color.use.signaling <- rep(color.use.signaling, nSignaling)\n # }\n #\n #\n # ## connect cell groups with patterns\n # plot.data.long <- to_lodes_form(plot.data, axes = 1:2, id = \"connection\")\n # if (do.order) {\n # mat = tapply(plot.data[[\"Contribution\"]], list(plot.data[[\"CellGroup\"]], plot.data[[\"Signaling\"]]), sum)\n # d <- dist(as.matrix(mat))\n # hc <- hclust(d, \"ave\")\n # k <- length(unique(grep(\"Signaling\", plot.data.long$stratum[plot.data.long$Contribution != 0], value = T)))\n # cluster <- hc %>% cutree(k)\n # order.name <- order(cluster)\n # plot.data.long$stratum <- factor(plot.data.long$stratum, levels = c(names(cluster)[order.name], colnames(mat)))\n # color.use <- color.use[order.name]\n # }\n # color.use.all <- c(color.use, color.use.signaling)\n\n # gg3 <- ggplot(plot.data.long, aes(x = factor(x, levels = c(\"CellGroup\", \"Signaling\")),y=Contribution,\n # stratum = stratum, alluvium = connection,\n # fill = stratum, label = stratum)) +\n # geom_flow(width = 1/3,aes.flow = \"forward\") +\n # geom_stratum(width=1/3,size=0.1,color=\"black\", alpha = 0.8, linetype = 1) +\n # geom_text(stat = \"stratum\", size = 2.5) +\n # scale_x_discrete(limits = c(), labels=c(\"Cell groups\", \"Signaling\")) +\n # scale_fill_manual(values = alpha(color.use.all, alpha = 0.8), drop = FALSE) +\n # theme_bw()+\n # theme(legend.position = \"none\",\n # axis.title = element_blank(),\n # axis.text.y= element_blank(),\n # panel.grid.major = element_blank(),\n # panel.grid.minor = element_blank(),\n # panel.border = element_blank(),\n # axis.ticks = element_blank(),axis.text=element_text(size=10)) +\n # theme(plot.margin = unit(c(0, 0, 0, 0), \"cm\"))\n\n\n gg <- cowplot::plot_grid(gg1, gg2,align = \"h\", nrow = 1)\n title <- cowplot::ggdraw() + cowplot::draw_label(main.title,size = font.size.title)\n gg <- cowplot::plot_grid(title, gg, ncol=1, rel_heights=c(0.1, 1))\n }\n return(gg)\n}\n\n#' Dot plots showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways\n#'\n#' Using a contribution score of each cell group to each signaling pathway computed by multiplying W by H obtained from `identifyCommunicationPatterns`, we constructed a dot plot in which the dot size is proportion to the contribution score to show association between cell group and their enriched signaling pathways.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param cutoff the threshold for filtering out weak links. Default is 1/R where R is the number of latent patterns. We set the elements in W and H to be zero if they are less than `cutoff`.\n#' @param color.use the character vector defining the color of each cell group\n#' @param pathway.show the character vector defining the signaling to show\n#' @param group.show the character vector defining the cell group to show\n#' @param shape the shape of the symbol: 21 for circle and 22 for square\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param main.title the title of plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom methods slot\n#' @import ggplot2\n#' @importFrom dplyr group_by top_n\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_dot <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), cutoff = NULL, color.use = NULL,\n pathway.show = NULL, group.show = NULL,\n shape = 21, dot.size = c(1, 3), dot.alpha = 1, main.title = NULL,\n font.size = 10, font.size.title = 12){\n pattern <- match.arg(pattern)\n patternSignaling <- methods::slot(object, slot.name)$pattern[[pattern]]\n data1 = patternSignaling$pattern$cell\n data2 = patternSignaling$pattern$signaling\n data = patternSignaling$data\n if (is.null(main.title)) {\n if (pattern == \"outgoing\") {\n main.title = \"Outgoing communication patterns of secreting cells\"\n } else if (pattern == \"incoming\") {\n main.title = \"Incoming communication patterns of target cells\"\n }\n }\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(data1$CellGroup))\n }\n if (is.null(cutoff)) {\n cutoff <- 1/length(unique(data1$Pattern))\n }\n options(warn = -1)\n data1$Contribution[data1$Contribution < cutoff] <- 0\n data2$Contribution[data2$Contribution < cutoff] <- 0\n data3 = merge(data1, data2, by.x=\"Pattern\", by.y=\"Pattern\")\n data3$Contribution <- data3$Contribution.x * data3$Contribution.y\n data3 <- data3[,colnames(data3) %in% c(\"CellGroup\",\"Signaling\",\"Contribution\")]\n if (!is.null(pathway.show)) {\n data3 <- data3[data3$Signaling %in% pathway.show, ]\n pathway.add <- pathway.show[which(pathway.show %in% data3$Signaling == 0)]\n if (length(pathway.add) > 1) {\n data.add <- expand.grid(CellGroup = levels(data1$CellGroup), Signaling = pathway.add)\n data.add$Contribution <- 0\n data3 <- rbind(data3, data.add)\n }\n data3$Signaling <- factor(data3$Signaling, levels = pathway.show)\n }\n if (!is.null(group.show)) {\n data3$CellGroup <- as.character(data3$CellGroup)\n data3 <- data3[data3$CellGroup %in% group.show, ]\n data3$CellGroup <- factor(data3$CellGroup, levels = group.show)\n }\n\n data <- as.data.frame(as.table(data));\n data <- data[data[,3] != 0, ]\n data12 <- paste0(data[,1],data[,2])\n data312 <- paste0(data3[,1],data3[,2])\n idx1 <- which(match(data312, data12, nomatch = 0) ==0)\n data3$Contribution[idx1] <- 0\n data3$id <- data312\n data3 <- data3 %>% group_by(id) %>% top_n(1, Contribution)\n\n data3$Contribution[which(data3$Contribution == 0)] <- NA\n\n df <- data3\n gg <- ggplot(data = df, aes(x = Signaling, y = CellGroup)) +\n geom_point(aes(size = Contribution, fill = CellGroup, colour = CellGroup), shape = shape) +\n scale_size_continuous(range = dot.size) +\n theme_linedraw() +\n scale_x_discrete(position = \"bottom\") +\n ggtitle(main.title) +\n theme(plot.title = element_text(hjust = 0.5)) +\n theme(text = element_text(size = font.size),plot.title = element_text(size=font.size.title, face=\"plain\"),\n axis.text.x = element_text(angle = 45, hjust=1),\n axis.text.y = element_text(angle = 0, hjust=1),\n axis.title.x = element_blank(),\n axis.title.y = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25)) +\n theme(panel.grid.major = element_line(colour=\"grey90\", size = (0.1)))\n gg <- gg + scale_y_discrete(limits = rev(levels(data3$CellGroup)))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE, na.value = \"white\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, na.value = \"white\")\n gg <- gg + guides(colour=\"none\") + guides(fill=\"none\")\n gg <- gg + theme(legend.title = element_text(size = 10), legend.text = element_text(size = 8))\n gg\n return(gg)\n}\n\n\n#' 2D visualization of the learned manifold of signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param pathway.labeled a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param pathway.remove.show whether show the removed signaling names\n#' @param color.use defining the color for each cell group\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embedding <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), color.use = NULL, pathway.labeled = NULL, top.label = 1, pathway.remove = NULL, pathway.remove.show = TRUE, dot.size = c(2, 6), label.size = 2, dot.alpha = 0.5,\n xlabel = \"Dim 1\", ylabel = \"Dim 2\", title = NULL,\n font.size = 10, font.size.title = 12, do.label = T, show.legend = T, show.axes = T) {\n type <- match.arg(type)\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n Groups <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n prob <- methods::slot(object, slot.name)$prob\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n }\n\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(dimnames(prob)[[3]] %in% pathway.remove)\n prob <- prob[ , , -pathway.remove.idx]\n }\n\n prob_sum <- apply(prob, 3, sum)\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum), labels = as.character(unlist(dimnames(prob)[3])), Groups = as.factor(Groups))\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(Groups)))\n }\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.,fill = Groups, colour = Groups), shape = 21) +\n CellChat_theme_opts() +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\"))+\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE)\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n if (do.label) {\n if (is.null(pathway.labeled)) {\n if (top.label < 1) {\n if (length(comparison) == 2) {\n g.t <- rankSimilarity(object, slot.name = slot.name, type = type, comparison1 = comparison)\n pathway.labeled <- as.character(g.t$data$name[(nrow(g.t$data)-ceiling(top.label * nrow(g.t$data))+1):nrow(g.t$data) ])\n data.label <- df[df$labels %in% pathway.labeled, , drop = FALSE]\n }\n } else {\n data.label <- df\n }\n\n } else {\n data.label <- df[df$labels %in% pathway.labeled, , drop = FALSE]\n }\n gg <- gg + ggrepel::geom_text_repel(data = data.label, mapping = aes(label = labels, colour = Groups), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n\n # gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = Groups), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (length(pathway.remove) > 0 & pathway.remove.show) {\n gg <- gg + annotate(geom = 'text', label = paste(\"Isolate pathways: \", paste(pathway.remove, collapse = ', ')), x = -Inf, y = Inf, hjust = 0, vjust = 1, size = label.size,fontface=\"italic\")\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n gg\n}\n\n\n#' Zoom into the 2D visualization of the learned manifold learning of the signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param color.use defining the color for each cell group\n#' @param nCol the number of columns of the plot\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom cowplot plot_grid\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingZoomIn <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), color.use = NULL, pathway.remove = NULL, nCol = 1, dot.size = c(2, 6), label.size = 2.8, dot.alpha = 0.5,\n xlabel = NULL, ylabel = NULL, do.label = T, show.legend = F, show.axes = T) {\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n prob <- methods::slot(object, slot.name)$prob\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n }\n\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(dimnames(prob)[[3]] %in% pathway.remove)\n prob <- prob[ , , -pathway.remove.idx]\n }\n\n prob_sum <- apply(prob, 3, sum)\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum), labels = as.character(unlist(dimnames(prob)[3])), clusters = as.factor(clusters))\n\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n\n # zoom into each cluster and do labels\n ggAll <- vector(\"list\", length(unique(clusters)))\n for (i in 1:length(unique(clusters))) {\n clusterID = i\n title <- paste0(\"Group \", clusterID)\n df2 <- df[df$clusters %in% clusterID,]\n gg <- ggplot(data = df2, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.), shape = 21, colour = alpha(color.use[clusterID], alpha = 1), fill = alpha(color.use[clusterID], alpha = dot.alpha)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size=12))+\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels), colour = color.use[clusterID], size = label.size, segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n ggAll[[i]] <- gg\n }\n gg.combined <- cowplot::plot_grid(plotlist = ggAll, ncol = nCol)\n\n gg.combined\n\n}\n\n\n\n#' 2D visualization of the joint manifold learning of signaling networks from two datasets\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object\n#' @param pathway.labeled a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param pathway.remove.show whether show the removed signaling names\n#' @param color.use defining the color for each cell group\n#' @param point.shape a numeric vector giving the point shapes. By default point.shape <- c(21, 0, 24, 23, 25, 10, 12), see available shapes at http://www.sthda.com/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingPairwise <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, color.use = NULL, point.shape = NULL, pathway.labeled = NULL, top.label = 1, pathway.remove = NULL, pathway.remove.show = TRUE, dot.size = c(2, 6), label.size = 2.5, dot.alpha = 0.5,\n xlabel = \"Dim 1\", ylabel = \"Dim 2\", title = NULL,do.label = T, show.legend = T, show.axes = T) {\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"2D visualization of signaling networks from datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n object.names <- setdiff(names(methods::slot(object, slot.name)), \"similarity\")[comparison]\n prob <- list()\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n prob[[i]] = object.net$prob\n }\n\n if (is.null(point.shape)) {\n point.shape <- c(21, 0, 24, 23, 25, 10, 12)\n }\n\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove <- sub(\"--.*\", \"\", pathway.remove)\n }\n\n if (length(pathway.remove) > 0) {\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n pathway.remove.idx <- which(paste0(dimnames(probi)[[3]],\"--\",object.names[i]) %in% pathway.remove)\n # pathway.remove.idx <- which(dimnames(probi)[[3]] %in% pathway.remove)\n if (length(pathway.remove.idx) > 0) {\n probi <- probi[ , , -pathway.remove.idx]\n }\n prob[[i]] <- probi\n }\n }\n prob_sum.each <- list()\n signalingAll <- c()\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n prob_sum.each[[i]] <- apply(probi, 3, sum)\n signalingAll <- c(signalingAll, paste0(names(prob_sum.each[[i]]),\"--\",object.names[i]))\n }\n prob_sum <- unlist(prob_sum.each)\n names(prob_sum) <- signalingAll\n\n group <- sub(\".*--\", \"\", names(prob_sum))\n labels = sub(\"--.*\", \"\", names(prob_sum))\n\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum),\n labels = as.character(labels), clusters = as.factor(clusters), group = factor(group, levels = unique(group)))\n # color dots (light inside color and dark border) based on clustering and no labels\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Commun.Prob.,fill = clusters, colour = clusters, shape = group)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) +\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) #+ scale_alpha(group, range = c(0.1, 1))\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n gg <- gg + scale_shape_manual(values = point.shape[1:length(prob)])\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = clusters, alpha=group), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n }\n\n if (length(pathway.remove) > 0 & pathway.remove.show) {\n gg <- gg + annotate(geom = 'text', label = paste(\"Isolate pathways: \", paste(pathway.remove, collapse = ', ')), x = -Inf, y = Inf, hjust = 0, vjust = 1, size = label.size,fontface=\"italic\")\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n gg\n}\n\n\n\n#' Zoom into the 2D visualization of the joint manifold learning of signaling networks from two datasets\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object\n#' @param pathway.remove a character vector defining the signaling to remove\n#' @param color.use defining the color for each cell group\n#' @param nCol number of columns in the plot\n#' @param point.shape a numeric vector giving the point shapes. By default point.shape <- c(21, 0, 24, 23, 25, 10, 12), see available shapes at http://www.sthda.com/english/wiki/r-plot-pch-symbols-the-different-point-shapes-available-in-r\n#' @param dot.size a range defining the size of the symbol\n#' @param dot.alpha transparency\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param label.size font size of the text\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetVisual_embeddingPairwiseZoomIn <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, color.use = NULL, nCol = 1, point.shape = NULL, pathway.remove = NULL, dot.size = c(2, 6), label.size = 2.8, dot.alpha = 0.5,\n xlabel = NULL, ylabel = NULL, do.label = T, show.legend = F, show.axes = T) {\n\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"2D visualization of signaling networks from datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n clusters <- methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]]\n object.names <- setdiff(names(methods::slot(object, slot.name)), \"similarity\")[comparison]\n prob <- list()\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n prob[[i]] = object.net$prob\n }\n\n if (is.null(point.shape)) {\n point.shape <- c(21, 0, 24, 23, 25, 10, 12)\n }\n\n if (is.null(pathway.remove)) {\n similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove <- sub(\"--.*\", \"\", pathway.remove)\n }\n\n if (length(pathway.remove) > 0) {\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n pathway.remove.idx <- which(paste0(dimnames(probi)[[3]],\"--\",object.names[i]) %in% pathway.remove)\n # pathway.remove.idx <- which(dimnames(probi)[[3]] %in% pathway.remove)\n if (length(pathway.remove.idx) > 0) {\n probi <- probi[ , , -pathway.remove.idx]\n }\n prob[[i]] <- probi\n }\n }\n\n prob_sum.each <- list()\n signalingAll <- c()\n for (i in 1:length(prob)) {\n probi <- prob[[i]]\n prob_sum.each[[i]] <- apply(probi, 3, sum)\n signalingAll <- c(signalingAll, paste0(names(prob_sum.each[[i]]),\"--\",object.names[i]))\n }\n prob_sum <- unlist(prob_sum.each)\n names(prob_sum) <- signalingAll\n\n group <- sub(\".*--\", \"\", names(prob_sum))\n labels = sub(\"--.*\", \"\", names(prob_sum))\n\n df <- data.frame(x = Y[,1], y = Y[, 2], Commun.Prob. = prob_sum/max(prob_sum),\n labels = as.character(labels), clusters = as.factor(clusters), group = factor(group, levels = unique(group)))\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(clusters)))\n }\n\n # zoom into each cluster and do labels\n ggAll <- vector(\"list\", length(unique(clusters)))\n for (i in 1:length(unique(clusters))) {\n clusterID = i\n title <- paste0(\"Cluster \", clusterID)\n df2 <- df[df$clusters %in% clusterID,]\n gg <- ggplot(data = df2, aes(x, y)) +\n geom_point(aes(size = Commun.Prob., shape = group),fill = alpha(color.use[clusterID], alpha = dot.alpha), colour = alpha(color.use[clusterID], alpha = 1)) +\n CellChat_theme_opts() +\n theme(text = element_text(size = 10), legend.key.height = grid::unit(0.15, \"in\"))+\n guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) +\n scale_size_continuous(limits = c(0,1), range = dot.size, breaks = c(0.1,0.5,0.9)) +\n theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n idx <- match(unique(df2$group), levels(df$group), nomatch = 0)\n gg <- gg + scale_shape_manual(values= point.shape[idx])\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels), colour = color.use[clusterID], size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5) + scale_alpha_discrete(range = c(1, 0.6))\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n ggAll[[i]] <- gg\n }\n gg.combined <- cowplot::plot_grid(plotlist = ggAll, ncol = nCol)\n\n gg.combined\n\n}\n\n\n#' A Seurat wrapper function for plotting gene expression using violin plot, dot plot or bar plot\n#'\n#' This function create a Seurat object from an input CellChat object, and then plot gene expression distribution using a modified violin plot or dot plot based on Seurat's function or a bar plot.\n#' Please check \\code{\\link{StackedVlnPlot}},\\code{\\link{dotPlot}} and \\code{\\link{barPlot}}for detailed description of the arguments.\n#'\n#' USER can extract the signaling genes related to the inferred L-R pairs or signaling pathway using \\code{\\link{extractEnrichedLR}}, and then plot gene expression using Seurat package.\n#'\n#' @param object CellChat object\n#' @param features Features to plot gene expression\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param type violin plot or dot plot\n#' @param color.use defining the color for each cell group\n#' @param group.by Name of one metadata columns to group (color) cells. Default is the defined cell groups in CellChat object\n#' @param ... other arguments passing to either VlnPlot or DotPlot from Seurat package\n#' @return\n#' @export\n#'\n#' @examples\n\nplotGeneExpression <- function(object, features = NULL, signaling = NULL, enriched.only = TRUE, type = c(\"violin\", \"dot\",\"bar\"), color.use = NULL, group.by = NULL, ...) {\n type <- match.arg(type)\n meta <- object@meta\n if (is.list(object@idents)) {\n meta$group.cellchat <- object@idents$joint\n } else {\n meta$group.cellchat <- object@idents\n }\n if (!identical(rownames(meta), colnames(object@data.signaling))) {\n cat(\"The cell barcodes in 'meta' is \", head(rownames(meta)),'\\n')\n warning(\"The cell barcodes in 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of 'mata'!\")\n rownames(meta) <- colnames(object@data.signaling)\n }\n\n w10x <- Seurat::CreateSeuratObject(counts = object@data.signaling, meta.data = meta)\n if (is.null(group.by)) {\n group.by <- \"group.cellchat\"\n }\n Seurat::Idents(w10x) <- group.by\n if (!is.null(features) & !is.null(signaling)) {\n warning(\"`features` will be used when inputing both `features` and `signaling`!\")\n }\n if (!is.null(features)) {\n feature.use <- features\n } else if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, enriched.only = enriched.only)\n feature.use <- res$geneLR\n }\n if (type == \"violin\") {\n gg <- StackedVlnPlot(w10x, features = feature.use, color.use = color.use, ...)\n } else if (type == \"dot\") {\n gg <- dotPlot(w10x, features = feature.use, color.use = color.use, ...)\n } else if (type == \"bar\") {\n gg <- barPlot(w10x, features = feature.use, color.use = color.use, ...)\n }\n return(gg)\n}\n\n\n#' Dot plot\n#'\n#'The size of the dot encodes the percentage of cells within a class, while the color encodes the AverageExpression level across all cells within a class\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param rotation whether rotate the plot\n#' @param colormap RColorbrewer palette to use (check available palette using RColorBrewer::display.brewer.all()). default will use customed color palette\n#' @param color.direction Sets the order of colours in the scale. If 1, the default, colours are as output by RColorBrewer::brewer.pal(). If -1, the order of colours is reversed.\n#' @param color.use defining the color for each condition/dataset\n#' @param idents Which classes to include in the plot (default is all)\n#' @param group.by Name of one or more metadata columns to group (color) cells by\n#' (for example, orig.ident); pass 'ident' to group by identity class\n#' @param split.by Name of a metadata column to split plot by;\n#' @param legend.width legend width\n#' @param scale whther show x-axis text\n#' @param col.min Minimum scaled average expression threshold (everything smaller will be set to this)\n#' @param col.max Maximum scaled average expression threshold (everything larger will be set to this)\n#' @param dot.scale Scale the size of the points, similar to cex\n#' @param assay Name of assay to use, defaults to the active assay\n#' @param angle.x angle for x-axis text rotation\n#' @param hjust.x adjust x axis text\n#' @param angle.y angle for y-axis text rotation\n#' @param hjust.y adjust y axis text\n#' @param show.legend whether show the legend\n#' @param ... Extra parameters passed to DotPlot from Seurat package\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\ndotPlot <- function(object, features, rotation = TRUE, colormap = \"OrRd\", color.direction = 1, color.use = c(\"#F8766D\",\"#00BFC4\"), scale = TRUE, col.min = -2.5, col.max = 2.5, dot.scale = 6, assay = \"RNA\",\n idents = NULL, group.by = NULL, split.by = NULL, legend.width = 0.5,\n angle.x = 45, hjust.x = 1, angle.y = 0, hjust.y = 0.5, show.legend = TRUE, ...) {\n\n gg <- Seurat::DotPlot(object, features = features, assay = assay, cols = color.use,\n scale = scale, col.min = col.min, col.max = col.max, dot.scale = dot.scale,\n idents = idents, group.by = group.by, split.by = split.by,...)\n gg <- gg + theme(axis.title.x=element_blank(), axis.title.y=element_blank()) +\n theme(axis.text.x = element_text(size = 10), axis.text.y = element_text(size = 10), axis.line = element_line(colour = 'black')) +\n theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))+\n theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x), axis.text.y = element_text(angle = angle.y, hjust = hjust.y))\n\n gg <- gg + theme(legend.title = element_text(size = 10), legend.text = element_text(size = 8))\n if (is.null(split.by)) {\n gg <- gg + guides(color = guide_colorbar(barwidth = legend.width, title = \"Scaled expression\"),size = guide_legend(title = 'Percent expressed'))\n }\n\n if (rotation) {\n gg <- gg + coord_flip()\n }\n if (!is.null(colormap)) {\n if (is.null(split.by)) {\n gg <- gg + scale_color_distiller(palette = colormap, direction = color.direction, guide = guide_colorbar(title = \"Scaled Expression\", ticks = T, label = T, barwidth = legend.width), na.value = \"lightgrey\")\n }\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n return(gg)\n}\n\n\n\n#' Stacked Violin plot\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param color.use defining the color for each cell group\n#' @param colors.ggplot whether use ggplot color scheme; default: colors.ggplot = FALSE\n#' @param split.by Name of a metadata column to split plot by;\n#' @param idents Which classes to include in the plot (default is all)\n#' @param show.text.y whther show y-axis text\n#' @param line.size line width in the violin plot\n#' @param pt.size size of the dots\n#' @param plot.margin adjust the white space between each plot\n#' @param angle.x angle for x-axis text rotation\n#' @param vjust.x adjust x axis text\n#' @param hjust.x adjust x axis text\n#' @param ... Extra parameters passed to VlnPlot from Seurat package\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\n#' @importFrom patchwork wrap_plots\n# #' @importFrom Seurat VlnPlot\nStackedVlnPlot<- function(object, features, idents = NULL, split.by = NULL,\n color.use = NULL, colors.ggplot = FALSE,\n angle.x = 90, vjust.x = NULL, hjust.x = NULL, show.text.y = TRUE, line.size = NULL,\n pt.size = 0,\n plot.margin = margin(0, 0, 0, 0, \"cm\"),\n ...) {\n options(warn=-1)\n if (is.null(color.use)) {\n numCluster <- length(levels(Seurat::Idents(object)))\n if (colors.ggplot) {\n color.use <- NULL\n } else {\n color.use <- scPalette(numCluster)\n }\n }\n if (is.null(vjust.x) | is.null(hjust.x)) {\n angle=c(0, 45, 90)\n hjust=c(0, 1, 1)\n vjust=c(0, 1, 0.5)\n vjust.x = vjust[angle == angle.x]\n hjust.x = hjust[angle == angle.x]\n }\n\n plot_list<- purrr::map(features, function(x) modify_vlnplot(object = object, features = x, idents = idents, split.by = split.by, cols = color.use, pt.size = pt.size,\n show.text.y = show.text.y, line.size = line.size, ...))\n\n # Add back x-axis title to bottom plot. patchwork is going to support this?\n plot_list[[length(plot_list)]]<- plot_list[[length(plot_list)]] +\n theme(axis.text.x=element_text(), axis.ticks.x = element_line()) +\n theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x, vjust = vjust.x)) +\n theme(axis.text.x = element_text(size = 10))\n\n p<- patchwork::wrap_plots(plotlist = plot_list, ncol = 1)\n return(p)\n}\n\n#' modified vlnplot\n#' @param object Seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param split.by Name of a metadata column to split plot by;\n#' @param idents Which classes to include in the plot (default is all)\n#' @param cols defining the color for each cell group\n#' @param show.text.y whther show y-axis text\n#' @param line.size line width in the violin plot\n#' @param pt.size size of the dots\n#' @param plot.margin adjust the white space between each plot\n#' @param ... pass any arguments to VlnPlot in Seurat\n#' @import ggplot2\n# #' @importFrom Seurat VlnPlot\n#'\nmodify_vlnplot<- function(object,\n features,\n idents = NULL,\n split.by = NULL,\n cols = NULL,\n show.text.y = TRUE,\n line.size = NULL,\n pt.size = 0,\n plot.margin = margin(0, 0, 0, 0, \"cm\"),\n ...) {\n options(warn=-1)\n p<- Seurat::VlnPlot(object, features = features, cols = cols, pt.size = pt.size, idents = idents, split.by = split.by, ... ) +\n xlab(\"\") + ylab(features) + ggtitle(\"\")\n p <- p + theme(text = element_text(size = 10)) + theme(axis.line = element_line(size=line.size)) +\n theme(axis.text.x = element_text(size = 10), axis.text.y = element_text(size = 8), axis.line.x = element_line(colour = 'black', size=line.size),axis.line.y = element_line(colour = 'black', size= line.size))\n # theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5))\n p <- p + theme(legend.position = \"none\",\n plot.title= element_blank(),\n axis.title.x = element_blank(),\n axis.text.x = element_blank(),\n axis.ticks.x = element_blank(),\n axis.title.y = element_text(size = rel(1), angle = 0),\n axis.text.y = element_text(size = rel(1)),\n plot.margin = plot.margin ) +\n theme(axis.text.y = element_text(size = 8))\n\n p <- p + scale_y_continuous(labels = function(x) {\n idx0 = which(x == 0)\n if (length(idx0) > 0) {\n if (idx0 > 1) {\n c(rep(x = \"\", times = idx0-1), \"0\",rep(x = \"\", times = length(x) -2-idx0), x[length(x) - 1], \"\")\n } else {\n c(\"0\", rep(x = \"\", times = length(x)-3), x[length(x) - 1], \"\")\n }\n } else {\n c(as.character(min(x)), rep(x = \"\", times = length(x)-3), x[length(x) - 1], \"\")\n }\n })\n # #c(rep(x = \"\", times = length(x)-2), x[length(x) - 1], \"\"))\n\n p <- p + theme(element_line(size=line.size))\n\n if (!show.text.y) {\n p <- p + theme(axis.ticks.y=element_blank(), axis.text.y=element_blank())\n }\n return(p)\n}\n\n#' extract the max value of the y axis\n#' @param p ggplot object\n#' @importFrom ggplot2 ggplot_build\nextract_max<- function(p){\n ymax<- max(ggplot_build(p)$layout$panel_scales_y[[1]]$range$range)\n return(signif(ymax,2))\n}\n\n\n#' Bar plot for average gene expression\n#'\n#' Please check \\code{\\link{barplot_internal}}for detailed description of the arguments.\n#'\n#' @param object seurat object\n#' @param features Features to plot (gene expression, metrics)\n#' @param color.use defining the color for each condition/dataset\n#' @param group.by Name of one or more metadata columns to group (color) cells by\n#' (for example, orig.ident); pass 'ident' to group by identity class\n#' @param method methods for computing the average gene expression per cell group. By default = \"truncatedMean\", where a value should be assigned to 'trim;\n#' @param trim the fraction (0 to 0.5) of observations to be trimmed from each end of x before the mean is computed.\n#' @param split.by Name of a metadata column to split plot by;\n#' @param assay Name of assay to use, defaults to the active assay\n#' @param x.lab.rot whether do rotation for the x.tick.label\n#' @param ncol number of columns to show in the plot\n#' @param ... Extra parameters passed to barplot_internal\n#' @return ggplot2 object\n#' @export\n#'\n#' @examples\n#' @import ggplot2\nbarPlot <- function(object, features, group.by = NULL, split.by = NULL, color.use = NULL, method = c(\"truncatedMean\", \"triMean\",\"median\"),trim = 0.1, assay = \"RNA\",\n x.lab.rot = FALSE, ncol = 1, ...) {\n method <- match.arg(method)\n if (is.null(group.by)) {\n labels = Seurat::Idents(object)\n } else {\n labels = object@meta.data[,group.by]\n }\n FunMean <- switch(method,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n triMean = triMean,\n median = function(x) median(x, na.rm = TRUE))\n if (packageVersion(\"Seurat\") < \"5.0.0\") {\n data.all <- object[[assay]]@data\n } else {\n data.all <- object[[assay]]$data\n }\n if (!is.null(split.by)) {\n group = object@meta.data[,split.by]\n group.levels <- levels(group)\n df <- data.frame()\n for (i in 1:length(group.levels)) {\n data = data.all[, group == group.levels[i], drop = FALSE]\n labels.use <- labels[group == group.levels[i]]\n dataavg <- aggregate(t(data[features, ]), list(labels.use) , FUN = FunMean)\n dataavg <- t(dataavg[,-1])\n colnames(dataavg) <- levels(labels.use)\n dataavg <- as.data.frame(dataavg)\n dataavg$gene = rownames(dataavg)\n df1 = reshape2::melt(dataavg, id.vars = c(\"gene\"))\n colnames(df1) <- c(\"gene\",\"labels\",\"value\")\n df1$condition = group.levels[i]\n df = rbind(df, df1)\n }\n df$labels <- factor(df$labels, levels = levels(labels))\n df$condition <- factor(df$condition, levels = group.levels)\n\n } else {\n data = data.all\n dataavg <- aggregate(t(data[features, ]), list(labels) , FUN = FunMean)\n dataavg <- t(dataavg[,-1])\n colnames(dataavg) <- levels(labels)\n dataavg$gene = rownames(dataavg)\n df1 = reshape2::melt(dataavg, id.vars = c(\"gene\"))\n colnames(df1) <- c(\"gene\",\"labels\",\"value\")\n df1$condition = df1[,\"labels\"]\n df = df1\n }\n gg <- list()\n for (i in 1:length(features)) {\n if (i < length(features)) {\n df.use = subset(df, gene == features[i])\n gg[[i]] <- barplot_internal(df.use, x = \"labels\", y = \"value\", fill = \"condition\",color.use = color.use,ylabel = features[i],remove.xtick = TRUE,x.lab.rot = x.lab.rot,...)\n }else {\n gg[[i]] <- barplot_internal(df.use, x = \"labels\", y = \"value\", fill = \"condition\",color.use = color.use,ylabel = features[i],remove.xtick = FALSE,x.lab.rot = x.lab.rot,...)\n }\n }\n\n p<- patchwork::wrap_plots(plotlist = gg, ncol = ncol)+ patchwork::plot_layout(guides = \"collect\")\n return(p)\n\n}\n\n#' Bar plot for dataframe\n#'\n#' @param df a dataframe\n#' @param x Name of one column to show on the x-axis\n#' @param y Name of one column to show on the y-axis\n#' @param fill Name of one column to compare the values\n#' @param color.use defining the color of bar plot;\n#' @param percent.y whether showing y-values as percentage\n#' @param width bar width\n#' @param legend.title Name of legend\n#' @param xlabel Name of x label\n#' @param ylabel Name of y label\n#' @param remove.xtick whether remove x tick\n#' @param title.name Name of the main title\n#' @param stat.add whether adding statistical test\n#' @param stat.method,label.x parameters for ggpubr::stat_compare_means\n#' @param show.legend Whether show the legend\n#' @param x.lab.rot Whether rorate the xtick labels\n#' @param size.text font size\n\n#' @import ggplot2\n#' @importFrom ggpubr stat_compare_means\n#'\n#' @return ggplot2 object\n#' @export\nbarplot_internal <- function(df, x = \"cellType\", y = \"value\", fill = \"condition\", legend.title = NULL, width=0.6, title.name = NULL,\n xlabel = NULL, ylabel = NULL, color.use = NULL,remove.xtick = FALSE,\n stat.add = FALSE, stat.method = \"wilcox.test\", percent.y = FALSE, label.x = 1.5,\n show.legend = TRUE, x.lab.rot = FALSE, size.text = 10) {\n\n gg <- ggplot(df, aes_string(x=x, y=y, fill = fill, color = fill)) + geom_bar(stat=\"identity\", width=width, position=position_dodge()) +\n theme_classic() + scale_x_discrete(limits = (levels(df$x))) + theme(axis.text.x = element_text(angle = 45, hjust = 1,size=10))\n\n gg <- gg + ylab(ylabel) + xlab(xlabel) + theme_classic() +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = size.text), axis.text = element_text(colour=\"black\"))\n if (!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values = alpha(color.use, alpha = 1), drop = FALSE)\n gg <- gg + scale_color_manual(values = alpha(color.use, alpha = 1), drop = FALSE) + guides(colour = FALSE)\n }\n if (stat.add) {\n gg <- gg + ggpubr::stat_compare_means(mapping = aes_string(group = fill), method = stat.method, label.x = label.x,\n label = \"p.format\", size = 3)\n }\n # if (show.mean) {\n # gg <- gg + stat_summary(fun.y=mean, geom=\"point\", shape=20, size=10, color=\"red\", fill=\"red\")\n # }\n if (remove.xtick) {\n gg <- gg + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.title.x=element_blank())\n }\n if (percent.y) {\n gg <- gg + scale_y_continuous(labels = scales::percent_format(accuracy = 1))\n }\n if (is.null(legend.title)) {\n gg <- gg + theme(legend.title = element_blank())\n } else {\n gg <- gg + guides(fill=guide_legend(legend.title))\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n if (x.lab.rot) {\n gg <- gg + theme(axis.text.x = element_text(angle = 45, hjust = 1, size=size.text))\n }\n gg\n return(gg)\n}\n\n\n########################################\n# spatial plot #\n########################################\n#' Visualize spatial cell groups\n#'\n#' This function takes a CellChat object as input, and then plot cell groups of interest.\n#'\n#' @param object cellchat object\n#' @param color.use defining the color for each cell group\n#' @param group.by Name of one metadata columns to group (color) cells. Default is the defined cell groups in CellChat object\n#' @param sample.use the sample name used for visualization, which should be the element in `object@meta$samples`.\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups\n#' @param idents.use a vector giving the index or the name of cell groups of interest\n#' @param alpha the transparency of individual spot\n#' @param shape.by the shape of individual spot\n#' @param title.name title name\n#' @param point.size the size of spots\n#' @param legend.size the size of legend\n#' @param legend.text.size the text size on the legend\n#' @param legend.position legend position\n#' @param ncol number of columns of the legend text\n#' @param byrow arrange the legend text byrow or not\n#' @return\n#' @export\n#'\n#' @examples\nspatialDimPlot <- function(object, color.use = NULL, group.by = NULL, sample.use = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL,\n alpha = 1, shape.by = 16, title.name = NULL, point.size = 2.4,\n legend.size = 5, legend.text.size = 8, legend.position = \"right\", ncol = 1, byrow = FALSE){\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[,group.by]\n labels <- factor(labels)\n }\n cells.level <- levels(labels)\n\n coordinates <- object@images$coordinates\n samples <- object@meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n\n if (is.null(sources.use) & is.null(targets.use)){\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n } else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use, \"Others\"))\n\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use, targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n\n gg <- ggplot(data = coordinates,aes(x=x_cent,y=y_cent,colour = labels))+\n geom_point(alpha = alpha, size = point.size, shape=shape.by) +\n scale_color_manual(values = color.use, na.value = \"grey90\") + theme(legend.position = legend.position) +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size)) + # , legend.key.size = unit(0.4, \"inches\")\n guides(color = guide_legend(override.aes = list(size=legend.size), ncol = ncol, byrow = byrow)) +\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n coord_fixed() + theme(aspect.ratio = 1)+ theme(legend.key = element_blank())\n gg <- gg + scale_y_reverse()\n\n if (!is.null(title.name)){\n gg <- gg + ggtitle(title.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))\n }\n return(gg)\n\n}\n\n\n#' A spatial feature plots\n#'\n#' This function takes a CellChat object as input, and then plot gene expression distribution over spots/cells on the image.\n#'\n#' @param object cellchat object\n#' @param features a char vector containing features to visualize. `features` can be genes or column names of `object@meta`.\n#' @param signaling signalling names to visualize\n#' @param pairLR.use a data frame consisting of one column named \"interaction_name\", defining the L-R pairs of interest\n#' @param sample.use the sample used for visualization, which should be the element in `object@meta$samples`.\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param do.group set `do.group = TRUE` when only showing enriched signaling based on cell group-level communication; set `do.group = FALSE` when only showing enriched signaling based on individual cell-level communication\n#' @param thresh threshold of the p-value for determining significant interaction when visualizing links at the level of ligands/receptors;\n#' @param color.heatmap A character string or vector indicating the colormap option to use. It can be the avaibale color palette in brewer.pal() or viridis_pal() (e.g., \"Spectral\",\"viridis\")\n#' @param n.colors,direction n.colors: number of basic colors to generate from color palette; direction: Sets the order of colors in the scale. If 1, the default colors are used. If -1, the order of colors is reversed.\n#' @param do.binary,cutoff whether binarizing the expression using a given cutoff\n#' @param color.use defining the color for cells/spots expressing ligand only, expressing receptor only, expressing both ligand & receptor and cells/spots without expression of given ligands and receptors\n#' @param alpha the transparency of individual spot\n#' @param point.size the size of cell slot\n#' @param shape.by the shape of individual spot\n#' @param legend.size the size of legend\n#' @param legend.text.size the text size on the legend\n#' @param ncol number of columns if plotting multiple plots\n#' @param show.legend whether show each figure legend\n#' @param show.legend.combined whether show the figure legend for the last plot\n#' @return\n#' @export\n#'\n#' @examples\n\nspatialFeaturePlot <- function(object, features = NULL, signaling = NULL, pairLR.use = NULL, sample.use = NULL, enriched.only = TRUE,thresh = 0.05, do.group = TRUE,\n color.heatmap = \"Spectral\", n.colors = 8, direction = -1,\n do.binary = FALSE, cutoff = NULL, color.use = NULL, alpha = 1,\n point.size = 0.8, legend.size = 3, legend.text.size = 8, shape.by = 16, ncol = NULL,\n show.legend = TRUE, show.legend.combined = FALSE){\n data <- object@data\n meta <- object@meta\n coords <- object@images$coordinates\n samples <- meta$samples\n if (ncol(coords) == 2) {\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coords = coords\n coords[,1] = temp_coords[,2]\n coords[,2] = temp_coords[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n scales::viridis_pal(option = color.heatmap, direction = -1)(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n } else {\n colormap <- color.heatmap\n }\n\n if (is.null(features) & is.null(signaling) & is.null(pairLR.use)){\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)){\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)){\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)){\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n\n df <- data.frame(x = coords[, 1], y = coords[, 2])\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, geneLR.return = TRUE, enriched.only = enriched.only, thresh = thresh)\n feature.use <- res$geneLR\n } else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n } else {\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(paste0('There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.'))\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\",\"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex, object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex, object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n } else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) > 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n } else if (length(intersect(feature.use, colnames(meta))) > 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[ ,feature.use, drop = FALSE])\n } else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \",cutoff,\"to the values...\", '\\n')\n data.use[data.use <= cutoff] <- 0\n }\n\n\n if (is.null(ncol)) {\n if (length(feature.use) > 9) {\n ncol <- 4\n } else {\n ncol <- min(length(feature.use), 4)\n }\n }\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i, ]\n g <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = feature.data), alpha = alpha, size=point.size, shape=shape.by) +\n scale_colour_gradientn(colours = colormap, guide = guide_colorbar(title = NULL, ticks = T, label = T, barwidth = 0.5), na.value = \"grey90\") +\n theme(legend.position = \"right\") +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size), legend.key.size = unit(0.15, \"inches\")) + # , legend.key.size = unit(0.4, \"inches\")\n ggtitle(feature.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))+\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n theme(legend.key = element_blank())\n g <- g + coord_fixed() + theme(aspect.ratio = 1) + scale_y_reverse()\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (show.legend.combined & i == numFeature) {\n g <- g + theme(legend.position = \"right\", legend.key.height = grid::unit(0.15, \"in\"), legend.key.width = grid::unit(0.5, \"in\"), legend.title = element_blank(),legend.key = element_blank())\n }\n gg[[i]] <- g\n }\n if (ncol > 1) {\n gg <- patchwork::wrap_plots(gg, ncol = ncol)\n } else {\n gg <- gg[[1]]\n }\n\n } else {\n\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(object, signaling = signaling, enriched.only = enriched.only, thresh = thresh)\n # gene.pair = searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n # LR.pair <- gene.pair[res$interaction_name, c(\"ligand\",\"receptor\")]\n LR.pair <- object@LR$LRsig[res$interaction_name, c(\"ligand\",\"receptor\")]\n } else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n } else {\n pairLR.use.name <- pairLR.use$interaction_name[pairLR.use$interaction_name %in% dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[,,pairLR.use.name, drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum > 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in% signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(paste0('There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.'))\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name, c(\"ligand\",\"receptor\")]\n } else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n # compute the expression of ligand or receptor\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL; rownames(dataR) <- geneR;\n # data.use <- matrix(0, nrow = nrow(dataL)*2, ncol = ncol(dataL))\n # data.use[seq_len(nrow(data.use)) %% 2 == 1, ] <- dataL\n # data.use[seq_len(nrow(data.use)) %% 2 == 0, ] <- dataR\n # rownames(data.use)[seq_len(nrow(data.use)) %% 2 == 1] <- geneL\n # rownames(data.use)[seq_len(nrow(data.use)) %% 2 == 0] <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n if (is.null(ncol)) {\n if (length(feature.use) > 9) {\n ncol <- 4\n } else {\n ncol <- min(length(feature.use), 4)\n }\n }\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \" )\n }\n gg <- vector(\"list\", numFeature)\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i, ] > cutoff\n idx2 = dataR[i, ] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\",ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i],geneR[i],\"Both\",\"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i],geneR[i],\"Both\",\"None\")\n\n if (length(setdiff(levels(group), unique(group))) > 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group), unique(group)))\n }\n\n df$feature.data <- group\n g <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = feature.data), alpha = alpha, size=point.size, shape=shape.by) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") +\n theme(legend.title = element_blank(), legend.text = element_text(size = legend.text.size), legend.key.size = unit(0.15, \"inches\")) + # , legend.key.size = unit(0.4, \"inches\")\n guides(color = guide_legend(override.aes = list(size=legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(hjust = 0.5, vjust = 0, size = 10))+\n theme(panel.background = element_blank(),axis.ticks = element_blank(), axis.text = element_blank()) + xlab(NULL) + ylab(NULL) +\n theme(legend.key = element_blank())\n g <- g + coord_fixed() + theme(aspect.ratio = 1) + scale_y_reverse()\n if (!show.legend) {\n g <- g + theme(legend.position = \"none\")\n }\n if (show.legend.combined & i == numFeature) {\n g <- g + theme(legend.position = \"right\", legend.key.height = grid::unit(0.15, \"in\"), legend.key.width = grid::unit(0.5, \"in\"), legend.title = element_blank(),legend.key = element_blank())\n }\n gg[[i]] <- g\n }\n if (ncol > 1) {\n gg <- patchwork::wrap_plots(gg, ncol = ncol)\n } else {\n gg <- gg[[1]]\n }\n\n }\n return(gg)\n}\n", "middle_code": "function(object, signaling, signaling.name = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max.individual = NULL, edge.weight.max.aggregate = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, pt.title = 12, title.space = 6, vertex.label.cex = 0.8,from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n out.format = c(\"svg\",\"png\"),\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n if (is.null(edge.weight.max.individual)) {\n edge.weight.max.individual = max(prob)\n }\n prob.sum <- apply(prob, c(1,2), sum)\n if (is.null(edge.weight.max.aggregate)) {\n edge.weight.max.aggregate = max(prob.sum)\n }\n if (layout == \"hierarchy\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_individual.svg\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_individual.png\"), width = 8, height = nRow*height, units = \"in\",res = 300)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_individual.pdf\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_aggregate.svg\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_aggregate.png\"), width = 7, height = 1*height, units = \"in\",res = 300)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_aggregate.pdf\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n } else if (layout == \"circle\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"spatial\") {\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"chord\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n }\n}", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "r", "sub_task_type": null}, "context_code": [["/CellChat/R/analysis.R", "\n#' Compute and visualize the contribution of each ligand-receptor pair in the overall signaling pathways\n#'\n#' @param object CellChat object\n#' @param signaling a signaling pathway name\n#' @param signaling.name alternative signaling pathway name to show on the plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param width the width of individual bar\n#' @param vertex.receiver a numeric vector giving the index of the cell groups as targets in the first hierarchy plot\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param return.data whether return the data.frame consisting of the predicted L-R pairs and their contribution\n#' @param x.rotation rotation of x-label\n#' @param title the title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @importFrom dplyr select\n#' @importFrom ggplot2 ggplot geom_bar aes coord_flip scale_x_discrete element_text theme ggtitle\n#' @importFrom cowplot ggdraw draw_label plot_grid\n#'\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_contribution <- function(object, signaling, signaling.name = NULL, sources.use = NULL, targets.use = NULL,\n width = 0.1, vertex.receiver = NULL, thresh = 0.05, return.data = FALSE,\n x.rotation = 0, title = \"Contribution of each L-R pair\",\n font.size = 10, font.size.title = 10) {\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pair.name.use = select(object@DB$interaction[rownames(pairLR),],\"interaction_name_2\")\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n\n\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n\n prob <- prob[,,pairLR.name.use]\n\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n dimnames(prob)[3] <- pairLR.name.use\n }\n prob <-(prob-min(prob))/(max(prob)-min(prob))\n\n if (is.null(vertex.receiver)) {\n pSum <- apply(prob, 3, sum)\n pSum.max <- sum(prob)\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n y.lim <- max(pSum)\n\n pair.name <- unlist(dimnames(prob)[3])\n pair.name <- factor(pair.name, levels = unique(pair.name))\n if (!is.null(pairLR.name.use)) {\n pair.name <- pair.name.use[as.character(pair.name),1]\n pair.name <- factor(pair.name, levels = unique(pair.name))\n }\n mat <- pSum\n df1 <- data.frame(name = pair.name, contribution = mat)\n if(nrow(df1) < 10) {\n df2 <- data.frame(name = as.character(1:(10-nrow(df1))), contribution = rep(0, 10-nrow(df1)))\n df <- rbind(df1, df2)\n } else {\n df <- df1\n }\n df <- df[order(df$contribution, decreasing = TRUE), ]\n # df$name <- factor(df$name, levels = unique(df$name))\n df$name <- factor(df$name,levels=df$name[order(df$contribution, decreasing = TRUE)])\n df1$name <- factor(df1$name,levels=df1$name[order(df1$contribution, decreasing = TRUE)])\n gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\", width = 0.7) +\n theme_classic() + theme(axis.text.y = element_text(angle = x.rotation, hjust = 1,size=font.size, colour = 'black'), axis.text=element_text(size=font.size),\n axis.title.y = element_text(size= font.size), axis.text.x = element_blank(), axis.ticks = element_blank()) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim) + coord_flip() + theme(legend.position=\"none\") +\n scale_x_discrete(limits = rev(levels(df$name)), labels = c(rep(\"\", max(0, 10-nlevels(df1$name))),rev(levels(df1$name))))\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5, size = font.size.title))\n }\n gg\n\n } else {\n pair.name <- factor(unlist(dimnames(prob)[3]), levels = unique(unlist(dimnames(prob)[3])))\n # show all the communications\n pSum <- apply(prob, 3, sum)\n pSum.max <- sum(prob)\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n y.lim <- max(pSum)\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\",width = 0.2) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8),\n axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"All\")+ theme(plot.title = element_text(hjust = 0.5))#+\n\n # show the communications in Hierarchy1\n if (dim(prob)[3] > 1) {\n pSum <- apply(prob[,vertex.receiver,], 3, sum)\n } else {\n pSum <- sum(prob[,vertex.receiver,])\n }\n\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg1 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\",width = 0.2) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"Hierarchy1\") + theme(plot.title = element_text(hjust = 0.5))#+\n #scale_x_discrete(limits = c(0,1))\n\n # show the communications in Hierarchy2\n\n if (dim(prob)[3] > 1) {\n pSum <- apply(prob[,setdiff(1:dim(prob)[1],vertex.receiver),], 3, sum)\n } else {\n pSum <- sum(prob[,setdiff(1:dim(prob)[1],vertex.receiver),])\n }\n pSum <- pSum/pSum.max\n pSum[is.na(pSum)] <- 0\n\n df<- data.frame(name = pair.name, contribution = pSum)\n gg2 <- ggplot(df, aes(x=name, y=contribution)) + geom_bar(stat=\"identity\", width=0.9) +\n theme_classic() + theme(axis.text=element_text(size=10),axis.text.x = element_text(angle = x.rotation, hjust = 1,size=8), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(\"Relative contribution\") + ylim(0,y.lim)+ ggtitle(\"Hierarchy2\")+ theme(plot.title = element_text(hjust = 0.5))#+\n #scale_x_discrete(limits = c(0,1))\n title <- cowplot::ggdraw() + cowplot::draw_label(paste0(\"Contribution of each signaling in \", signaling.name, \" pathway\"), fontface='bold', size = 10)\n gg.combined <- cowplot::plot_grid(gg, gg1, gg2, nrow = 1)\n gg.combined <- cowplot::plot_grid(title, gg.combined, ncol = 1, rel_heights=c(0.1, 1))\n gg <- gg.combined\n gg\n }\n if (return.data) {\n df <- subset(df, contribution > 0)\n return(list(LR.contribution = df, gg.obj = gg))\n } else {\n return(gg)\n }\n}\n\n\n#' Compute the network centrality scores allowing identification of dominant senders, receivers, mediators and influencers in all inferred communication networks\n#'\n#' NB: This function was previously named as `netAnalysis_signalingRole`. The previous function `netVisual_signalingRole` is now named as `netAnalysis_signalingRole_network`.\n#'\n#' @param object CellChat object; If object = NULL, USER must provide `net`\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks. Setting slot.name = \"netP\" to compute the network centrality scores at the level of signaling pathways, and setting slot.name = \"net\" to compute the network centrality scores at the level of ligand-receptor pairs\n#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net\n#' @param net.name a character vector giving the name of signaling networks\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom future nbrOfWorkers\n#' @importFrom methods slot\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#'\n#' @return\n#' @export\n#'\nnetAnalysis_computeCentrality <- function(object = NULL, slot.name = \"netP\", net = NULL, net.name = NULL, thresh = 0.05) {\n if (is.null(net)) {\n prob <- methods::slot(object, slot.name)$prob\n pval <- methods::slot(object, slot.name)$pval\n pval[prob == 0] <- 1\n prob[pval >= thresh] <- 0\n net = prob\n }\n if (is.null(net.name)) {\n net.name <- dimnames(net)[[3]]\n }\n if (length(dim(net)) == 3) {\n nrun <- dim(net)[3]\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n centr.all = my.sapply(\n X = 1:nrun,\n FUN = function(x) {\n net0 <- net[ , , x]\n return(computeCentralityLocal(net0))\n },\n simplify = FALSE\n )\n } else {\n centr.all <- as.list(computeCentralityLocal(net))\n }\n names(centr.all) <- net.name\n if (is.null(object)) {\n return(centr.all)\n } else {\n slot(object, slot.name)$centr <- centr.all\n return(object)\n }\n}\n\n\n\n#' Compute Centrality measures for a signaling network\n#'\n#' @param net compute the centrality measures on a specific signaling network given by a 2 or 3 dimemsional array net\n#' @importFrom igraph graph_from_adjacency_matrix strength hub_score authority_score eigen_centrality page_rank betweenness E\n#' @importFrom sna flowbet infocent\n#'\n#' @return\ncomputeCentralityLocal <- function(net) {\n centr <- vector(\"list\")\n G <- igraph::graph_from_adjacency_matrix(net, mode = \"directed\", weighted = T)\n centr$outdeg_unweighted <- rowSums(net > 0)\n centr$indeg_unweighted <- colSums(net > 0)\n centr$outdeg <- igraph::strength(G, mode=\"out\")\n centr$indeg <- igraph::strength(G, mode=\"in\")\n centr$hub <- igraph::hub_score(G)$vector\n centr$authority <- igraph::authority_score(G)$vector # A node has high authority when it is linked by many other nodes that are linking many other nodes.\n centr$eigen <- igraph::eigen_centrality(G)$vector # A measure of influence in the network that takes into account second-order connections\n centr$page_rank <- igraph::page_rank(G)$vector\n igraph::E(G)$weight <- 1/igraph::E(G)$weight\n centr$betweenness <- igraph::betweenness(G)\n #centr$flowbet <- try(sna::flowbet(net)) # a measure of its role as a gatekeeper for the flow of communication between any two cells; the total maximum flow (aggregated across all pairs of third parties) mediated by v.\n #centr$info <- try(sna::infocent(net)) # actors with higher information centrality are predicted to have greater control over the flow of information within a network; highly information-central individuals tend to have a large number of short paths to many others within the social structure.\n centr$flowbet <- tryCatch({\n sna::flowbet(net)\n }, error = function(e) {\n as.vector(matrix(0, nrow = nrow(net), ncol = 1))\n })\n centr$info <- tryCatch({\n sna::infocent(net, diag = T, rescale = T, cmode = \"lower\")\n # sna::infocent(net, diag = T, rescale = T, cmode = \"weak\")\n }, error = function(e) {\n as.vector(matrix(0, nrow = nrow(net), ncol = 1))\n })\n return(centr)\n}\n\n\n#' Select the number of the patterns for running `identifyCommunicationPatterns`\n#'\n#' We infer the number of patterns based on two metrics that have been implemented in the NMF R package, including Cophenetic and Silhouette. Both metrics measure the stability for a particular number of patterns based on a hierarchical clustering of the consensus matrix. For a range of the number of patterns, a suitable number of patterns is the one at which Cophenetic and Silhouette values begin to drop suddenly.\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param k.range a range of the number of patterns\n#' @param title.name title of plot\n#' @param do.facet whether use facet plot showing the two measures\n#' @param nrun number of runs when performing NMF\n#' @param seed.use seed when performing NMF\n#' @importFrom methods slot\n# #' @importFrom NMF nmfEstimateRank\n#' @import NMF\n# #' @importFrom ggplot2 scale_color_brewer\n#' @import ggplot2\n#' @return a ggplot object\n#' @export\n#'\n#' @examples\nselectK <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), title.name = NULL, do.facet = TRUE, k.range = seq(2,10), nrun = 30, seed.use = 10) {\n pattern <- match.arg(pattern)\n prob <- methods::slot(object, slot.name)$prob\n if (pattern == \"outgoing\") {\n data_sender <- apply(prob, c(1,3), sum)\n data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_sender)\n } else if (pattern == \"incoming\") {\n data_receiver <- apply(prob, c(2,3), sum)\n data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_receiver)\n }\n options(warn = -1)\n data <- data0\n data <- data[rowSums(data)!=0,]\n\n if (is.null(title.name)) {\n title.name <- paste0(pattern, \" signaling \\n\")\n # title.name <- paste0(pattern, \" signaling \\n (nrun = \", nrun, \", seed = \", seed.use, \")\")\n }\n\n res <- NMF::nmfEstimateRank(data, range = k.range, method = 'lee', nrun=nrun, seed = seed.use)\n df1 <- data.frame(k = res$measures$rank, score = res$measures$cophenetic, Measure = \"Cophenetic\")\n df2 <- data.frame(k = res$measures$rank, score = res$measures$silhouette.consensus, Measure = \"Silhouette\")\n # df3 <- data.frame(k = res$measures$rank, score = res$measures$dispersion, Measure = \"Dispersion\")\n df <- rbind(df1, df2)\n #df <- rbind(df1, df2, df3)\n gg <- ggplot(df, aes(x = k, y = score, group = Measure, color = Measure)) + geom_line(size=1) +\n geom_point() +\n theme_classic() + labs(x = 'Number of patterns', y='Measure score') +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(legend.position = \"right\") + theme(text = element_text(size = 10)) + scale_x_discrete(limits = (unique(df$k))) +\n scale_color_brewer(palette=\"Set2\") + guides(color=guide_legend(\"Measure type\"))\n if (do.facet) {\n gg <- gg + facet_wrap(~ Measure, scales='free')\n }\n gg\n return(gg)\n}\n\n\n\n#' Identification of major signals for specific cell groups and general communication patterns\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param pattern \"outgoing\" or \"incoming\"\n#' @param k the number of patterns\n#' @param k.range a range of the number of patterns\n#' @param heatmap.show whether showing heatmap\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param title.legend the title of legend in heatmap\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @importFrom methods slot\n#' @importFrom NMF nmfEstimateRank nmf\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation draw\n#' @importFrom stats setNames\n#' @importFrom grid grid.grabExpr grid.newpage pushViewport grid.draw unit gpar viewport popViewport\n#'\n#' @return\n#' @export\n#'\n#' @examples\n\nidentifyCommunicationPatterns <- function(object, slot.name = \"netP\", pattern = c(\"outgoing\",\"incoming\"), k = NULL, k.range = seq(2,10), heatmap.show = TRUE,\n color.use = NULL, color.heatmap = \"Spectral\", title.legend = \"Contributions\",\n width = 4, height = 6, font.size = 8) {\n pattern <- match.arg(pattern)\n prob <- methods::slot(object, slot.name)$prob\n if (pattern == \"outgoing\") {\n data_sender <- apply(prob, c(1,3), sum)\n data_sender = sweep(data_sender, 2L, apply(data_sender, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_sender)\n } else if (pattern == \"incoming\") {\n data_receiver <- apply(prob, c(2,3), sum)\n data_receiver = sweep(data_receiver, 2L, apply(data_receiver, 2, function(x) max(x, na.rm = TRUE)), '/', check.margin = FALSE)\n data0 = as.matrix(data_receiver)\n }\n options(warn = -1)\n data <- data0\n data <- data[rowSums(data)!=0,]\n if (is.null(k)) {\n stop(\"Please run the function `selectK` for selecting a suitable k!\")\n }\n\n outs_NMF <- NMF::nmf(data, rank = k, method = 'lee', seed = 'nndsvd')\n W <- scaleMat(outs_NMF@fit@W, 'r1')\n H <- scaleMat(outs_NMF@fit@H, 'c1')\n colnames(W) <- paste0(\"Pattern \", seq(1,ncol(W))); rownames(H) <- paste0(\"Pattern \", seq(1,nrow(H)));\n if (heatmap.show) {\n net <- W\n if (is.null(color.use)) {\n color.use <- scPalette(length(rownames(net)))\n }\n color.heatmap = grDevices::colorRampPalette(rev(RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(255)\n\n df<- data.frame(group = rownames(net)); rownames(df) <- rownames(net)\n cell.cols.assigned <- setNames(color.use, unique(as.character(df$group)))\n row_annotation <- HeatmapAnnotation(df = df, col = list(group = cell.cols.assigned),which = \"row\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ht1 = Heatmap(net, col = color.heatmap, na_col = \"white\", name = \"Contribution\",\n left_annotation = row_annotation,\n cluster_rows = T,cluster_columns = F,clustering_method_rows = \"average\",\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n show_heatmap_legend = F,\n column_title = \"Cell patterns\",column_title_gp = gpar(fontsize = 10)\n )\n\n\n net <- t(H)\n\n ht2 = Heatmap(net, col = color.heatmap, na_col = \"white\", name = \"Contribution\",\n cluster_rows = T,cluster_columns = F,clustering_method_rows = \"average\",\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = \"Communication patterns\",column_title_gp = gpar(fontsize = 10),\n heatmap_legend_param = list(title = title.legend, title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = c(round(min(net, na.rm = T), digits = 1), round(max(net, na.rm = T), digits = 1)),\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 6),grid_width = unit(2, \"mm\"))\n )\n\n gb_ht1 = grid.grabExpr(draw(ht1))\n gb_ht2 = grid.grabExpr(draw(ht2))\n #grid.newpage()\n pushViewport(viewport(x = 0.1, y = 0.1, width = 0.2, height = 0.5, just = c(\"left\", \"bottom\")))\n grid.draw(gb_ht1)\n popViewport()\n\n pushViewport(viewport(x = 0.6, y = 0.1, width = 0.2, height = 0.5, just = c(\"left\", \"bottom\")))\n grid.draw(gb_ht2)\n popViewport()\n\n }\n\n data_W <- as.data.frame(as.table(W)); colnames(data_W) <- c(\"CellGroup\",\"Pattern\",\"Contribution\")\n data_H <- as.data.frame(as.table(H)); colnames(data_H) <- c(\"Pattern\",\"Signaling\",\"Contribution\")\n\n res.pattern = list(\"cell\" = data_W, \"signaling\" = data_H)\n methods::slot(object, slot.name)$pattern[[pattern]] <- list(data = data0, pattern = res.pattern)\n return(object)\n}\n\n\n#' Compute signaling network similarity for any pair of signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param k the number of nearest neighbors\n#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity\n#' @importFrom methods slot\n\n#'\n#' @return\n#' @export\n#'\n#' @examples\ncomputeNetSimilarity <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), k = NULL, thresh = NULL) {\n type <- match.arg(type)\n prob = methods::slot(object, slot.name)$prob\n if (is.null(k)) {\n if (dim(prob)[3] <= 25) {\n k <- ceiling(sqrt(dim(prob)[3]))\n } else {\n k <- ceiling(sqrt(dim(prob)[3])) + 1\n }\n\n }\n if (!is.null(thresh)) {\n prob[prob < quantile(c(prob[prob != 0]), thresh)] <- 0\n }\n if (type == \"functional\") {\n # compute the functional similarity\n D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])\n S2 <- D_signalings; S3 <- D_signalings;\n for (i in 1:(dim(prob)[3]-1)) {\n for (j in (i+1):dim(prob)[3]) {\n Gi <- (prob[ , ,i] > 0)*1\n Gj <- (prob[ , ,j] > 0)*1\n S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)\n }\n }\n # define the similarity matrix\n S3[is.na(S3)] <- 0; S3 <- S3 + t(S3); diag(S3) <- 1\n # S_signalings <- S1 *S2\n S_signalings <- S3\n } else if (type == \"structural\") {\n # compute the structure distance\n D_signalings <- matrix(0, nrow = dim(prob)[3], ncol = dim(prob)[3])\n for (i in 1:(dim(prob)[3]-1)) {\n for (j in (i+1):dim(prob)[3]) {\n Gi <- (prob[ , ,i] > 0)*1\n Gj <- (prob[ , ,j] > 0)*1\n D_signalings[i,j] <- computeNetD_structure(Gi,Gj)\n }\n }\n # define the structure similarity matrix\n D_signalings[is.infinite(D_signalings)] <- 0\n D_signalings[is.na(D_signalings)] <- 0\n D_signalings <- D_signalings + t(D_signalings)\n S_signalings <- 1-D_signalings\n }\n\n # smooth the similarity matrix using SNN\n SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)\n Similarity <- as.matrix(S_signalings*SNN)\n rownames(Similarity) <- dimnames(prob)[[3]]\n colnames(Similarity) <- dimnames(prob)[[3]]\n\n comparison <- \"single\"\n comparison.name <- paste(comparison, collapse = \"-\")\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {\n methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity\n return(object)\n}\n\n\n\n#' Compute signaling network similarity for any pair of datasets\n#'\n#' @param object A merged CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison\n#' @param k the number of nearest neighbors\n#' @param thresh the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity\n#' @importFrom methods slot\n#'\n#' @return\n#' @export\n#'\ncomputeNetSimilarityPairwise <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, k = NULL, thresh = NULL) {\n type <- match.arg(type)\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Compute signaling network similarity for datasets\", as.character(comparison), '\\n')\n comparison.name <- paste(comparison, collapse = \"-\")\n net <- list()\n signalingAll <- c()\n object.net.nameAll <- c()\n # 1:length(setdiff(names(methods::slot(object, slot.name)), \"similarity\"))\n for (i in 1:length(comparison)) {\n object.net <- methods::slot(object, slot.name)[[comparison[i]]]\n object.net.name <- names(methods::slot(object, slot.name))[comparison[i]]\n object.net.nameAll <- c(object.net.nameAll, object.net.name)\n net[[i]] = object.net$prob\n signalingAll <- c(signalingAll, paste0(dimnames(net[[i]])[[3]], \"--\", object.net.name))\n # signalingAll <- c(signalingAll, dimnames(net[[i]])[[3]])\n }\n names(net) <- object.net.nameAll\n net.dim <- sapply(net, dim)[3,]\n nnet <- sum(net.dim)\n position <- cumsum(net.dim); position <- c(0,position)\n\n if (is.null(k)) {\n if (nnet <= 25) {\n k <- ceiling(sqrt(nnet))\n } else {\n k <- ceiling(sqrt(nnet)) + 1\n }\n\n }\n if (!is.null(thresh)) {\n for (i in 1:length(net)) {\n neti <- net[[i]]\n neti[neti < quantile(c(neti[neti != 0]), thresh)] <- 0\n net[[i]] <- neti\n }\n }\n if (type == \"functional\") {\n # compute the functional similarity\n S3 <- matrix(0, nrow = nnet, ncol = nnet)\n for (i in 1:nnet) {\n for (j in 1:nnet) {\n idx.i <- which(position - i >= 0)[1]\n idx.j <- which(position - j >= 0)[1]\n net.i <- net[[idx.i-1]]\n net.j <- net[[idx.j-1]]\n Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1\n Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1\n S3[i,j] <- sum(Gi * Gj)/sum(Gi+Gj-Gi*Gj,na.rm=TRUE)\n }\n }\n\n # define the similarity matrix\n S3[is.na(S3)] <- 0; diag(S3) <- 1\n S_signalings <- S3\n } else if (type == \"structural\") {\n # compute the structure distance\n D_signalings <- matrix(0, nrow = nnet, ncol = nnet)\n for (i in 1:nnet) {\n for (j in 1:nnet) {\n idx.i <- which(position - i >= 0)[1]\n idx.j <- which(position - j >= 0)[1]\n net.i <- net[[idx.i-1]]\n net.j <- net[[idx.j-1]]\n Gi <- (net.i[ , ,i-position[idx.i-1]] > 0)*1\n Gj <- (net.j[ , ,j-position[idx.j-1]] > 0)*1\n D_signalings[i,j] <- computeNetD_structure(Gi,Gj)\n }\n }\n # define the structure similarity matrix\n D_signalings[is.infinite(D_signalings)] <- 0\n D_signalings[is.na(D_signalings)] <- 0\n S_signalings <- 1-D_signalings\n }\n # smooth the similarity matrix using SNN\n SNN <- buildSNN(S_signalings, k = k, prune.SNN = 1/15)\n Similarity <- as.matrix(S_signalings*SNN)\n rownames(Similarity) <- signalingAll\n colnames(Similarity) <- rownames(Similarity)\n\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$matrix)) {\n methods::slot(object, slot.name)$similarity[[type]]$matrix <- NULL\n }\n # methods::slot(object, slot.name)$similarity[[type]]$matrix <- Similarity\n methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]] <- Similarity\n return(object)\n}\n\n\n#' Manifold learning of the signaling networks based on their similarity\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object\n#' @param pathway.remove a range of the number of patterns\n#' @param umap.method UMAP implementation to run.\n#'\n#' Can be umap-learn: Run the python umap-learn package; uwot: Runs umap via the uwot R package; If umap.method = \"uwot\", please make sure you have installed the 'uwot' (https://github.com/jlmelville/uwot)\n#'\n#' @param n_neighbors the number of nearest neighbors in running umap\n#' @param min_dist This controls how tightly the embedding is allowed compress points together.\n#' Larger values ensure embedded points are moreevenly distributed, while smaller values allow the\n#' algorithm to optimise more accurately with regard to local structure. Sensible values are in the range 0.001 to 0.5.\n#' @param ... Parameters passing to umap\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nnetEmbedding <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, pathway.remove = NULL,\n umap.method = c(\"umap-learn\", \"uwot\"), n_neighbors = NULL,min_dist = 0.3,...) {\n umap.method <- match.arg(umap.method)\n if (object@options$mode == \"single\") {\n comparison <- \"single\"\n cat(\"Manifold learning of the signaling networks for a single dataset\", '\\n')\n } else if (object@options$mode == \"merged\") {\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Manifold learning of the signaling networks for datasets\", as.character(comparison), '\\n')\n }\n comparison.name <- paste(comparison, collapse = \"-\")\n Similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n if (is.null(pathway.remove)) {\n pathway.remove <- rownames(Similarity)[which(colSums(Similarity) == 1)]\n }\n if (length(pathway.remove) > 0) {\n pathway.remove.idx <- which(rownames(Similarity) %in% pathway.remove)\n Similarity <- Similarity[-pathway.remove.idx, -pathway.remove.idx]\n }\n if (is.null(n_neighbors)) {\n n_neighbors <- ceiling(sqrt(dim(Similarity)[1])) + 1\n }\n options(warn = -1)\n # dimension reduction\n if (umap.method == \"umap-learn\") {\n Y <- runUMAP(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)\n } else if (umap.method == \"uwot\") {\n Y <- uwot::umap(Similarity, min_dist = min_dist, n_neighbors = n_neighbors,...)\n colnames(Y) <- paste0('UMAP', 1:ncol(Y))\n rownames(Y) <- colnames(Similarity)\n }\n\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$dr)) {\n methods::slot(object, slot.name)$similarity[[type]]$dr <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]] <- Y\n return(object)\n}\n\n\n#' Classification learning of the signaling networks\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison a numerical vector giving the datasets for comparison. No need to define for a single dataset. Default are all datasets when object is a merged object\n#' @param k the number of signaling groups when running kmeans\n#' @param methods the methods for clustering: \"kmeans\" or \"spectral\"\n#' @param do.plot whether showing the eigenspectrum for inferring number of clusters; Default will save the plot\n#' @param fig.id add a unique figure id when saving the plot\n#' @param do.parallel whether doing parallel when inferring the number of signaling groups when running kmeans\n#' @param nCores number of workers when doing parallel\n#' @param k.eigen the number of eigenvalues used when doing spectral clustering\n#' @importFrom methods slot\n#' @importFrom future nbrOfWorkers plan\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @return\n#' @export\n#'\n#' @examples\nnetClustering <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison = NULL, k = NULL, methods = \"kmeans\", do.plot = TRUE, fig.id = NULL, do.parallel = TRUE, nCores = 4, k.eigen = NULL) {\n type <- match.arg(type)\n if (object@options$mode == \"single\") {\n comparison <- \"single\"\n cat(\"Classification learning of the signaling networks for a single dataset\", '\\n')\n } else if (object@options$mode == \"merged\") {\n if (is.null(comparison)) {\n comparison <- 1:length(unique(object@meta$datasets))\n }\n cat(\"Classification learning of the signaling networks for datasets\", as.character(comparison), '\\n')\n }\n comparison.name <- paste(comparison, collapse = \"-\")\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n data.use <- Y\n if (methods == \"kmeans\") {\n if (!is.null(k)) {\n clusters = kmeans(data.use,k,nstart=10)$cluster\n } else {\n N <- nrow(data.use)\n kRange <- seq(2,min(N-1, 10),by = 1)\n if (do.parallel) {\n future::plan(\"multisession\", workers = nCores)\n options(future.globals.maxSize = 1000 * 1024^2)\n }\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n results = my.sapply(\n X = 1:length(kRange),\n FUN = function(x) {\n idents <- kmeans(data.use,kRange[x],nstart=10)$cluster\n clusIndex <- idents\n #adjMat0 <- as.numeric(outer(clusIndex, clusIndex, FUN = \"==\")) - outer(1:N, 1:N, \"==\")\n adjMat0 <- Matrix::Matrix(as.numeric(outer(clusIndex, clusIndex, FUN = \"==\")), nrow = N, ncol = N)\n return(list(adjMat = adjMat0, ncluster = length(unique(idents))))\n },\n simplify = FALSE\n )\n adjMat <- lapply(results, \"[[\", 1)\n CM <- Reduce('+', adjMat)/length(kRange)\n res <- computeEigengap(as.matrix(CM))\n numCluster <- res$upper_bound\n clusters = kmeans(data.use,numCluster,nstart=10)$cluster\n if (do.plot) {\n gg <- res$gg.obj\n ggsave(filename= paste0(\"estimationNumCluster_\",fig.id,\"_\",type,\"_dataset_\",comparison.name,\".pdf\"), plot=gg, width = 3.5, height = 3, units = 'in', dpi = 300)\n }\n }\n\n } else if (methods == \"spectral\") {\n A <- as.matrix(data.use)\n D <- apply(A, 1, sum)\n L <- diag(D)-A # unnormalized version\n L <- diag(D^-0.5)%*%L%*% diag(D^-0.5) # normalized version\n evL <- eigen(L,symmetric=TRUE) # evL$values is decreasing sorted when symmetric=TRUE\n # pick the first k first k eigenvectors (corresponding k smallest) as data points in spectral space\n plot(rev(evL$values)[1:30])\n Z <- evL$vectors[,(ncol(evL$vectors)-k.eigen+1):ncol(evL$vectors)]\n clusters = kmeans(Z,k,nstart=20)$cluster\n }\n if (!is.list(methods::slot(object, slot.name)$similarity[[type]]$group)) {\n methods::slot(object, slot.name)$similarity[[type]]$group <- NULL\n }\n methods::slot(object, slot.name)$similarity[[type]]$group[[comparison.name]] <- clusters\n return(object)\n}\n\n\n#' Build SNN matrix\n# #' Adapted from swne (https://github.com/yanwu2014/swne)\n#' @param data.use Features x samples matrix to use to build the SNN\n#' @param k Defines k for the k-nearest neighbor algorithm\n#' @param k.scale Granularity option for k.param\n#' @param prune.SNN Sets the cutoff for acceptable Jaccard distances when\n#' computing the neighborhood overlap for the SNN construction.\n#'\n#' @return Returns similarity matrix in sparse matrix format\n#'\n#' @importFrom FNN get.knn\n#' @importFrom Matrix sparseMatrix\n#' @export\n#'\nbuildSNN <- function(data.use, k = 10, k.scale = 10, prune.SNN = 1/15) {\n n.cells <- ncol(data.use)\n if (n.cells < k) {\n stop(\"k cannot be greater than the number of samples\")\n }\n\n ## find the k-nearest neighbors for each single cell\n my.knn <- FNN::get.knn(t(as.matrix(data.use)), k = min(k.scale * k, n.cells - 1))\n nn.ranked <- cbind(1:n.cells, my.knn$nn.index[, 1:(k - 1)])\n nn.large <- my.knn$nn.index\n\n w <- ComputeSNN(nn.ranked, prune.SNN)\n colnames(w) <- rownames(w) <- colnames(data.use)\n\n Matrix::diag(w) <- 1\n return(w)\n}\n\n\n\n#' Compute the eigengap of a given matrix for inferring the number of clusters\n#'\n#' @param CM consensus matrix\n#' @param tau truncated consensus matrix\n#' @param tol tolerance\n#' @return\n#' @import ggplot2\n#' @export\ncomputeEigengap <- function(CM, tau = NULL, tol = 0.01){\n # compute the drop tolerance, enforcing parsimony of components\n K.init <- computeLaplacian(CM, tol = tol)$n_zeros\n if (is.null(tau)) {\n if (K.init <= 5) {\n tau = 0.3\n } else if (K.init <= 10){\n tau = 0.4\n } else {\n tau = 0.5\n }\n }\n\n # truncate the ensemble consensus matrix\n CM[CM <= tau] <- 0;\n # normalize and make symmetric\n CM <- (CM + t(CM))/2\n eigs <- computeLaplacian(CM, tol = tol)\n\n # compute the largest eigengap\n gaps <- diff(eigs$val)\n upper_bound <- which(gaps == max(gaps))\n\n # compute the number of zero eigenvalues\n lower_bound <- eigs$n_zeros\n\n df <- data.frame(nCluster = 1:min(c(30,length(eigs$val))), eigenVal = eigs$val[1:min(c(30,length(eigs$val)))])\n g <- ggplot(df, aes(x = nCluster, y = eigenVal)) + geom_point(size = 1) +\n geom_point(aes(x= upper_bound, y= eigs$val[upper_bound]), colour=\"red\", size = 3, pch = 1) + theme(legend.position=\"none\")\n title.name <- paste0('Inferred number of clusters: ', upper_bound,'; Min number: ', lower_bound)\n g <- g + labs(title = title.name) + theme_bw() + scale_x_continuous(breaks=seq(0,30,5)) +\n theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = 10)) + labs(x = 'Number of clusters', y = 'Eigenvalue of graph Laplacian')+\n theme(axis.text.x = element_text(size = 8), axis.text.y = element_text(size = 8))\n # ggsave(filename= paste0(\"estimationNumCluster_eigenspectrum\",sample.int(100,1),\".pdf\"), plot=g, width = 3.5, height = 3, units = 'in', dpi = 300)\n return(list(upper_bound = upper_bound,\n lower_bound = lower_bound,\n eigs = eigs,\n gg.obj = g))\n\n}\n\n\n#' Compute eigenvalues of associated Laplacian matrix of a given matrix\n#'\n#' @param CM consensus matrix\n#' @param tol tolerance\n#' @return\n#' @importFrom RSpectra eigs_sym\n#' @importFrom Matrix colSums\n#' @export\ncomputeLaplacian <- function(CM, tol = 0.01) {\n # Normalized Laplacian:\n Dsq <- sqrt(Matrix::colSums(CM))\n L <- -Matrix::t(CM / Dsq) / Dsq\n Matrix::diag(L) <- 1 + Matrix::diag(L)\n\n numEigs <- min(100,nrow(CM))\n res <- RSpectra::eigs_sym(L, k = numEigs, which = \"SM\", opt = list(tol = 1e-4))\n eigs <- abs(Re(res$values))\n n_zeros <- sum(eigs <= tol)\n return(list(val = sort(eigs), n_zeros = n_zeros))\n}\n\n\n#' Rank the similarity of the shared signaling pathways based on their joint manifold learning\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param type \"functional\",\"structural\"\n#' @param comparison1 a numerical vector giving the datasets for comparison. This should be the same as `comparison` in `computeNetSimilarityPairwise`\n#' @param comparison2 a numerical vector with two elements giving the datasets for comparison.\n#'\n#' If there are more than 2 datasets defined in `comparison1`, `comparison2` can be defined to indicate which two datasets used for computing the distance.\n#' e.g., comparison2 = c(1,3) indicates the first and third datasets defined in `comparison1` will be used for comparison.\n#' @param x.rotation rotation of x-labels\n#' @param title main title of the plot\n#' @param bar.w the width of bar plot\n#' @param color.use defining the color\n#' @param font.size font size\n#' @import ggplot2\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nrankSimilarity <- function(object, slot.name = \"netP\", type = c(\"functional\",\"structural\"), comparison1 = NULL, comparison2 = c(1,2),\n x.rotation = 90, title = NULL, color.use = NULL, bar.w = NULL, font.size = 8) {\n type <- match.arg(type)\n\n if (is.null(comparison1)) {\n comparison1 <- 1:length(unique(object@meta$datasets))\n }\n comparison.name <- paste(comparison1, collapse = \"-\")\n cat(\"Compute the distance of signaling networks between datasets\", as.character(comparison1[comparison2]), '\\n')\n comparison2.name <- names(methods::slot(object, slot.name))[comparison1[comparison2]]\n # net <- list()\n # for (i in 1:length(comparison2)) {\n # net[[i]] = methods::slot(object, slot.name)[[comparison1[comparison2[i]]]]$prob\n # }\n\n #net.dim <- sapply(net, dim)[3,]\n #position <- cumsum(net.dim); position <- c(0,position)\n # if (is.null(pathway.remove)) {\n # similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]\n # pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]\n # pathway.remove.idx <- which(rownames(similarity) %in% pathway.remove)\n # }\n\n # if (length(pathway.remove.idx) > 0) {\n # for (i in 1:length(pathway.remove.idx)) {\n # idx <- which(position - pathway.remove.idx[i] > 0)\n # if (!is.null(idx)) {\n # position[idx[1]] <- position[idx[1]] - 1\n # if (idx[1] == 2) {\n # position[3] <- position[3] - 1\n # }\n # }\n # }\n # }\n\n Y <- methods::slot(object, slot.name)$similarity[[type]]$dr[[comparison.name]]\n group <- sub(\".*--\", \"\", rownames(Y))\n data1 <- Y[group %in% comparison2.name[1], ]\n data2 <- Y[group %in% comparison2.name[2], ]\n rownames(data1) <- sub(\"--.*\", \"\", rownames(data1))\n rownames(data2) <- sub(\"--.*\", \"\", rownames(data2))\n\n pathway.show = as.character(intersect(rownames(data1), rownames(data2)))\n data1 <- data1[pathway.show, ]\n data2 <- data2[pathway.show, ]\n euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))\n dist <- NULL\n for(i in 1:nrow(data1)) dist[i] <- euc.dist(data1[i,],data2[i,])\n df <- data.frame(name = pathway.show, dist = dist, row.names = pathway.show)\n df <- df[order(df$dist), , drop = F]\n df$name <- factor(df$name, levels = as.character(df$name))\n\n gg <- ggplot(df, aes(x=name, y=dist)) + geom_bar(stat=\"identity\",width = bar.w) +\n theme_classic() + theme(text=element_text(size=font.size),axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_text(size=font.size)) +\n xlab(\"\") + ylab(\"Pathway distance\") + coord_flip()#+\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n if (!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = 1), drop = FALSE, na.value = \"white\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE, na.value = \"white\")\n }\n return(gg)\n}\n\n\n\n\n\n\n\n#' Rank signaling networks based on the information flow or the number of interactions\n#'\n#' This function can also be used to rank signaling from certain cell groups to other cell groups\n#'\n#' @param object CellChat object\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param measure \"weight\" or \"count\". \"weight\": comparing the total interaction weights (strength); \"count\": comparing the number of interactions;\n#' @param mode \"single\",\"comparison\"\n#' @param comparison a numerical vector giving the datasets for comparison; a single value means ranking for only one dataset and two values means ranking comparison for two datasets\n#' @param color.use defining the color for each cell group\n#' @param stacked whether plot the stacked bar plot\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a vector giving the signaling pathway to show\n#' @param pairLR a vector giving the names of L-R pairs to show (e.g, pairLR = c(\"IL1A_IL1R1_IL1RAP\",\"IL1B_IL1R1_IL1RAP\"))\n#' @param signaling.type a char giving the types of signaling from the three categories c(\"Secreted Signaling\", \"ECM-Receptor\", \"Cell-Cell Contact\")\n#' @param do.stat whether do a Wilcoxon test to determine whether there is significant difference between two datasets. Default = FALSE\n#' @param paired.test a logical indicating whether you want a paired test. Paired test is applicable to compare two datasets with the same cellular compositions.\n#' @param cutoff.pvalue the cutoff of pvalue when doing Wilcoxon test; Default = 0.05\n#' @param tol a tolerance when considering the relative contribution being equal between two datasets. contribution.relative between 1-tol and 1+tol will be considered as equal contribution\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @param do.flip whether flip the x-y axis\n#' @param x.angle,y.angle,x.hjust,y.hjust parameters for rotating and spacing axis labels\n#' @param axis.gap whetehr making gaps in y-axes\n#' @param ylim,segments,tick_width,rel_heights parameters in the function gg.gap when making gaps in y-axes\n#' e.g., ylim = c(0, 35), segments = list(c(11, 14),c(16, 28)), tick_width = c(5,2,5), rel_heights = c(0.8,0,0.1,0,0.1)\n#' https://tobiasbusch.xyz/an-r-package-for-everything-ep2-gaps\n#' @param show.raw whether show the raw information flow. Default = FALSE, showing the scaled information flow to provide compariable data scale; When stacked = TRUE, use raw information flow by default.\n#' @param return.data whether return the data.frame consisting of the calculated information flow of each signaling pathway or L-R pair\n#' @param x.rotation rotation of x-labels\n#' @param title main title of the plot\n#' @param bar.w the width of bar plot\n#' @param font.size font size\n\n#' @import ggplot2\n#' @importFrom methods slot\n#' @return\n#' @export\n#'\n#' @examples\nrankNet <- function(object, slot.name = \"netP\", measure = c(\"weight\",\"count\"), mode = c(\"comparison\", \"single\"), comparison = c(1,2), color.use = NULL, stacked = FALSE, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR = NULL, signaling.type = NULL, do.stat = FALSE, paired.test = TRUE, cutoff.pvalue = 0.05, tol = 0.05, thresh = 0.05, show.raw = FALSE, return.data = FALSE, x.rotation = 90, title = NULL, bar.w = 0.75, font.size = 8,\n do.flip = TRUE, x.angle = NULL, y.angle = 0, x.hjust = 1,y.hjust = 1,\n axis.gap = FALSE, ylim = NULL, segments = NULL, tick_width = NULL, rel_heights = c(0.9,0,0.1)) {\n measure <- match.arg(measure)\n mode <- match.arg(mode)\n options(warn = -1)\n object.names <- names(methods::slot(object, slot.name))\n if (measure == \"weight\") {\n ylabel = \"Information flow\"\n } else if (measure == \"count\") {\n ylabel = \"Number of interactions\"\n }\n if (mode == \"single\") {\n object1 <- methods::slot(object, slot.name)\n prob = object1$prob\n prob[object1$pval > thresh] <- 0\n if (measure == \"count\") {\n prob <- 1*(prob > 0)\n }\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n if (sum(prob) == 0) {\n stop(\"No inferred communications for the input!\")\n }\n\n pSum <- apply(prob, 3, sum)\n pSum.original <- pSum\n if (measure == \"weight\") {\n pSum <- -1/log(pSum)\n pSum[is.na(pSum)] <- 0\n idx1 <- which(is.infinite(pSum) | pSum < 0)\n values.assign <- seq(max(pSum)*1.1, max(pSum)*1.5, length.out = length(idx1))\n position <- sort(pSum.original[idx1], index.return = TRUE)$ix\n pSum[idx1] <- values.assign[match(1:length(idx1), position)]\n } else if (measure == \"count\") {\n pSum <- pSum.original\n }\n\n pair.name <- names(pSum)\n\n df<- data.frame(name = pair.name, contribution = pSum.original, contribution.scaled = pSum, group = object.names[comparison[1]])\n idx <- with(df, order(df$contribution))\n df <- df[idx, ]\n df$name <- factor(df$name, levels = as.character(df$name))\n for (i in 1:length(pair.name)) {\n df.t <- df[df$name == pair.name[i], \"contribution\"]\n if (sum(df.t) == 0) {\n df <- df[-which(df$name == pair.name[i]), ]\n }\n }\n\n if (!is.null(signaling.type)) {\n LR <- subset(object@DB$interaction, annotation %in% signaling.type)\n if (slot.name == \"netP\") {\n signaling <- unique(LR$pathway_name)\n } else if (slot.name == \"net\") {\n pairLR <- LR$interaction_name\n }\n }\n\n if ((slot.name == \"netP\") && (!is.null(signaling))) {\n df <- subset(df, name %in% signaling)\n } else if ((slot.name == \"netP\") &&(!is.null(pairLR))) {\n stop(\"You need to set `slot.name == 'net'` if showing specific L-R pairs \")\n }\n if ((slot.name == \"net\") && (!is.null(pairLR))) {\n df <- subset(df, name %in% pairLR)\n } else if ((slot.name == \"net\") && (!is.null(signaling))) {\n stop(\"You need to set `slot.name == 'netP'` if showing specific signaling pathways \")\n }\n\n gg <- ggplot(df, aes(x=name, y=contribution.scaled)) + geom_bar(stat=\"identity\",width = bar.w) +\n theme_classic() + theme(axis.text=element_text(size=font.size),axis.text.x = element_blank(), axis.ticks.x = element_blank(), axis.title.y = element_text(size=10)) +\n xlab(\"\") + ylab(ylabel) + coord_flip()#+\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n\n } else if (mode == \"comparison\") {\n prob.list <- list()\n pSum <- list()\n pSum.original <- list()\n pair.name <- list()\n idx <- list()\n pSum.original.all <- c()\n object.names.comparison <- c()\n for (i in 1:length(comparison)) {\n object.list <- methods::slot(object, slot.name)[[comparison[i]]]\n prob <- object.list$prob\n prob[object.list$pval > thresh] <- 0\n if (measure == \"count\") {\n prob <- 1*(prob > 0)\n }\n if (!is.null(sources.use)) {\n if (is.character(sources.use)) {\n if (all(sources.use %in% dimnames(prob)[[1]])) {\n sources.use <- match(sources.use, dimnames(prob)[[1]])\n } else {\n stop(\"The input `sources.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), sources.use)\n prob[idx.t, , ] <- 0\n }\n if (!is.null(targets.use)) {\n if (is.character(targets.use)) {\n if (all(targets.use %in% dimnames(prob)[[1]])) {\n targets.use <- match(targets.use, dimnames(prob)[[2]])\n } else {\n stop(\"The input `targets.use` should be cell group names or a numerical vector!\")\n }\n }\n idx.t <- setdiff(1:nrow(prob), targets.use)\n prob[ ,idx.t, ] <- 0\n }\n if (sum(prob) == 0) {\n stop(\"No inferred communications for the input!\")\n }\n prob.list[[i]] <- prob\n pSum.original[[i]] <- apply(prob, 3, sum)\n if (measure == \"weight\") {\n pSum[[i]] <- -1/log(pSum.original[[i]])\n pSum[[i]][is.na(pSum[[i]])] <- 0\n idx[[i]] <- which(is.infinite(pSum[[i]]) | pSum[[i]] < 0)\n pSum.original.all <- c(pSum.original.all, pSum.original[[i]][idx[[i]]])\n } else if (measure == \"count\") {\n pSum[[i]] <- pSum.original[[i]] # the prob is already binarized in line 1136\n }\n pair.name[[i]] <- names(pSum.original[[i]])\n object.names.comparison <- c(object.names.comparison, object.names[comparison[i]])\n }\n if (measure == \"weight\") {\n values.assign <- seq(max(unlist(pSum))*1.1, max(unlist(pSum))*1.5, length.out = length(unlist(idx)))\n position <- sort(pSum.original.all, index.return = TRUE)$ix\n for (i in 1:length(comparison)) {\n if (i == 1) {\n pSum[[i]][idx[[i]]] <- values.assign[match(1:length(idx[[i]]), position)]\n } else {\n pSum[[i]][idx[[i]]] <- values.assign[match(length(unlist(idx[1:i-1]))+1:length(unlist(idx[1:i])), position)]\n }\n }\n }\n\n\n\n pair.name.all <- as.character(unique(unlist(pair.name)))\n df <- list()\n for (i in 1:length(comparison)) {\n df[[i]] <- data.frame(name = pair.name.all, contribution = 0, contribution.scaled = 0, group = object.names[comparison[i]], row.names = pair.name.all)\n df[[i]][pair.name[[i]],3] <- pSum[[i]]\n df[[i]][pair.name[[i]],2] <- pSum.original[[i]]\n }\n\n\n # contribution.relative <- as.numeric(format(df[[length(comparison)]]$contribution/abs(df[[1]]$contribution), digits=1))\n # # contribution.relative <- as.numeric(format(df[[length(comparison)]]$contribution.scaled/abs(df[[1]]$contribution.scaled), digits=1))\n # contribution.relative2 <- as.numeric(format(df[[length(comparison)-1]]$contribution/abs(df[[1]]$contribution), digits=1))\n # contribution.relative[is.na(contribution.relative)] <- 0\n # for (i in 1:length(comparison)) {\n # df[[i]]$contribution.relative <- contribution.relative\n # df[[i]]$contribution.relative2 <- contribution.relative2\n # }\n # df[[1]]$contribution.data2 <- df[[length(comparison)]]$contribution\n # idx <- with(df[[1]], order(-contribution.relative, -contribution.relative2, contribution, -contribution.data2))\n #\n contribution.relative <- list()\n for (i in 1:(length(comparison)-1)) {\n contribution.relative[[i]] <- as.numeric(format(df[[length(comparison)-i+1]]$contribution/df[[1]]$contribution, digits=1))\n contribution.relative[[i]][is.na(contribution.relative[[i]])] <- 0\n }\n names(contribution.relative) <- paste0(\"contribution.relative.\", 1:length(contribution.relative))\n for (i in 1:length(comparison)) {\n for (j in 1:length(contribution.relative)) {\n df[[i]][[names(contribution.relative)[j]]] <- contribution.relative[[j]]\n }\n }\n df[[1]]$contribution.data2 <- df[[length(comparison)]]$contribution\n if (length(comparison) == 2) {\n idx <- with(df[[1]], order(-contribution.relative.1, contribution, -contribution.data2))\n } else if (length(comparison) == 3) {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2,contribution, -contribution.data2))\n } else if (length(comparison) == 4) {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2, -contribution.relative.3, contribution, -contribution.data2))\n } else {\n idx <- with(df[[1]], order(-contribution.relative.1, -contribution.relative.2, -contribution.relative.3, -contribution.relative.4, contribution, -contribution.data2))\n }\n\n\n\n for (i in 1:length(comparison)) {\n df[[i]] <- df[[i]][idx, ]\n df[[i]]$name <- factor(df[[i]]$name, levels = as.character(df[[i]]$name))\n }\n df[[1]]$contribution.data2 <- NULL\n\n df <- do.call(rbind, df)\n df$group <- factor(df$group, levels = object.names.comparison)\n\n if (is.null(color.use)) {\n color.use = ggPalette(length(comparison))\n }\n\n # https://stackoverflow.com/questions/49448497/coord-flip-changes-ordering-of-bars-within-groups-in-grouped-bar-plot\n df$group <- factor(df$group, levels = rev(levels(df$group)))\n color.use <- rev(color.use)\n\n # perform statistical analysis\n # if (do.stat) {\n # pvalues <- c()\n # for (i in 1:length(pair.name.all)) {\n # df.prob <- data.frame()\n # for (j in 1:length(comparison)) {\n # if (pair.name.all[i] %in% pair.name[[j]]) {\n # df.prob <- rbind(df.prob, data.frame(prob = as.vector(prob.list[[j]][ , , pair.name.all[i]]), group = comparison[j]))\n # } else {\n # df.prob <- rbind(df.prob, data.frame(prob = as.vector(matrix(0, nrow = nrow(prob.list[[j]]), ncol = nrow(prob.list[[j]]))), group = comparison[j]))\n # }\n #\n # }\n # df.prob$group <- factor(df.prob$group, levels = comparison)\n # if (length(comparison) == 2) {\n # pvalues[i] <- wilcox.test(prob ~ group, data = df.prob)$p.value\n # } else {\n # pvalues[i] <- kruskal.test(prob ~ group, data = df.prob)$p.value\n # }\n # }\n # df$pvalues <- pvalues\n # }\n if (do.stat & length(comparison) == 2) {\n for (i in 1:length(pair.name.all)) {\n if (nrow(prob.list[[j]]) != nrow(prob.list[[1]])) {\n if (paired.test) {\n stop(\"Paired test is not applicable to datasets with different cellular compositions! Please set `do.stat = FALSE` or `paired.test = FALSE`! \\n\")\n }\n }\n prob.values <- matrix(0, nrow = nrow(prob.list[[1]]) * nrow(prob.list[[1]]), ncol = length(comparison))\n for (j in 1:length(comparison)) {\n if (pair.name.all[i] %in% pair.name[[j]]) {\n prob.values[, j] <- as.vector(prob.list[[j]][ , , pair.name.all[i]])\n } else {\n prob.values[, j] <- NA\n }\n }\n prob.values <- prob.values[rowSums(prob.values, na.rm = TRUE) != 0, , drop = FALSE]\n if (nrow(prob.values) >3 & sum(is.na(prob.values)) == 0) {\n pvalues <- wilcox.test(prob.values[ ,1], prob.values[ ,2], paired = paired.test)$p.value\n } else {\n pvalues <- 0\n }\n pvalues[is.na(pvalues)] <- 0\n df$pvalues[df$name == pair.name.all[i]] <- pvalues\n }\n }\n\n\n if (length(comparison) == 2) {\n if (do.stat) {\n colors.text <- ifelse((df$contribution.relative < 1-tol) & (df$pvalues < cutoff.pvalue), color.use[2], ifelse((df$contribution.relative > 1+tol) & df$pvalues < cutoff.pvalue, color.use[1], \"black\"))\n } else {\n colors.text <- ifelse(df$contribution.relative < 1-tol, color.use[2], ifelse(df$contribution.relative > 1+tol, color.use[1], \"black\"))\n }\n } else {\n message(\"The text on the y-axis will not be colored for the number of compared datasets larger than 3!\")\n colors.text = NULL\n }\n\n for (i in 1:length(pair.name.all)) {\n df.t <- df[df$name == pair.name.all[i], \"contribution\"]\n if (sum(df.t) == 0) {\n df <- df[-which(df$name == pair.name.all[i]), ]\n }\n }\n\n if ((slot.name == \"netP\") && (!is.null(signaling))) {\n df <- subset(df, name %in% signaling)\n } else if ((slot.name == \"netP\") &&(!is.null(pairLR))) {\n stop(\"You need to set `slot.name == 'net'` if showing specific L-R pairs \")\n }\n if ((slot.name == \"net\") && (!is.null(pairLR))) {\n df <- subset(df, name %in% pairLR)\n } else if ((slot.name == \"net\") && (!is.null(signaling))) {\n stop(\"You need to set `slot.name == 'netP'` if showing specific signaling pathways \")\n }\n\n if (stacked) {\n gg <- ggplot(df, aes(x=name, y=contribution, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position =\"fill\") # +\n # xlab(\"\") + ylab(\"Relative information flow\") #+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n # scale_y_discrete(breaks=c(\"0\",\"0.5\",\"1\")) +\n if (measure == \"weight\") {\n gg <- gg + xlab(\"\") + ylab(\"Relative information flow\")\n } else if (measure == \"count\") {\n gg <- gg + xlab(\"\") + ylab(\"Relative number of interactions\")\n }\n\n gg <- gg + geom_hline(yintercept = 0.5, linetype=\"dashed\", color = \"grey50\", size=0.5)\n } else {\n if (show.raw) {\n gg <- ggplot(df, aes(x=name, y=contribution, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position = position_dodge(0.8)) +\n xlab(\"\") + ylab(ylabel) #+ coord_flip()#+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n } else {\n gg <- ggplot(df, aes(x=name, y=contribution.scaled, fill = group)) + geom_bar(stat=\"identity\",width = bar.w, position = position_dodge(0.8)) +\n xlab(\"\") + ylab(ylabel) #+ coord_flip()#+ theme(axis.text.x = element_blank(),axis.ticks.x = element_blank())\n }\n\n if (axis.gap) {\n gg <- gg + theme_bw() + theme(panel.grid = element_blank())\n gg.gap::gg.gap(gg,\n ylim = ylim,\n segments = segments,\n tick_width = tick_width,\n rel_heights = rel_heights)\n }\n }\n gg <- gg + CellChat_theme_opts() + theme_classic()\n if (do.flip) {\n gg <- gg + coord_flip() + theme(axis.text.y = element_text(colour = colors.text))\n if (is.null(x.angle)) {\n x.angle = 0\n }\n\n } else {\n if (is.null(x.angle)) {\n x.angle = 45\n }\n gg <- gg + scale_x_discrete(limits = rev) + theme(axis.text.x = element_text(colour = rev(colors.text)))\n\n }\n\n gg <- gg + theme(axis.text=element_text(size=font.size), axis.title.y = element_text(size=font.size))\n gg <- gg + scale_fill_manual(name = \"\", values = color.use)\n gg <- gg + guides(fill = guide_legend(reverse = TRUE))\n gg <- gg + theme(axis.text.x = element_text(angle = x.angle, hjust=x.hjust),\n axis.text.y = element_text(angle = y.angle, hjust=y.hjust))\n if (!is.null(title)) {\n gg <- gg + ggtitle(title)+ theme(plot.title = element_text(hjust = 0.5))\n }\n }\n\n if (return.data) {\n df$contribution <- abs(df$contribution)\n df$contribution.scaled <- abs(df$contribution.scaled)\n return(list(signaling.contribution = df, gg.obj = gg))\n } else {\n return(gg)\n }\n}\n\n\n#' Comparing the number of inferred communication links between different datasets\n#'\n#' @param object A merged CellChat object\n#' @param measure \"count\" or \"weight\". \"count\": comparing the number of interactions; \"weight\": comparing the total interaction weights (strength)\n#' @param color.use defining the color for each group of datasets\n#' @param group a vector giving the groups of different datasets to define colors of the bar plot. Default: only one group and a single color\n#' @param group.levels the factor level in the defined group\n#' @param group.facet Name of one metadata column defining faceting groups\n#' @param group.facet.levels the factor level in the defined group.facet\n#' @param n.row Number of rows in facet_grid()\n#' @param color.alpha transparency\n#' @param legend.title legend title\n#' @param width bar width\n#' @param title.name main title of the plot\n#' @param digits integer indicating the number of decimal places (round) to be used when `measure` is `weight`.\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param remove.xtick whether remove xtick\n#' @param size.text font size of the text\n#' @param show.legend whether show the legend\n#' @param x.lab.rot,angle.x,vjust.x,hjust.x adjusting parameters if rotating xtick.labels when x.lab.rot = TRUE\n#' @import ggplot2\n#' @return A ggplot object\n#' @export\n#'\ncompareInteractions <- function(object, measure = c(\"count\", \"weight\"), color.use = NULL, group = NULL, group.levels = NULL, group.facet = NULL, group.facet.levels = NULL, n.row = 1, color.alpha = 1, legend.title = NULL, width=0.6, title.name = NULL, digits = 3,\n xlabel = NULL, ylabel = NULL, remove.xtick = FALSE,\n show.legend = TRUE, x.lab.rot = FALSE, angle.x = 45, vjust.x = NULL, hjust.x = 1, size.text = 10) {\n measure <- match.arg(measure)\n if (measure == \"count\") {\n df <- as.data.frame(sapply(object@net, function(x) sum(x$count)))\n if (is.null(ylabel)) {\n ylabel = \"Number of inferred interactions\"\n }\n } else if (measure == \"weight\") {\n df <- as.data.frame(sapply(object@net, function(x) sum(x$weight)))\n df[,1] <- round(df[,1],digits)\n if (is.null(ylabel)) {\n ylabel = \"Interaction strength\"\n }\n }\n colnames(df) <- \"count\"\n\n df$dataset <- names(object@net)\n if (is.null(group)) {\n group <- 1\n }\n df$group <- group\n df$dataset <- factor(df$dataset, levels = names(object@net))\n if (is.null(group.levels)) {\n df$group <- factor(df$group)\n } else {\n df$group <- factor(df$group, levels = group.levels)\n }\n\n if (is.null(color.use)) {\n color.use <- ggPalette(length(unique(group)))\n }\n # theme_classic() #+ scale_x_discrete(limits = (levels(df$x)))\n if (!is.null(group.facet)) {\n if (all(group.facet %in% colnames(df))) {\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n gg <- gg + facet_wrap(group.facet, nrow = n.row)\n } else {\n df$group.facet <- group.facet\n if (is.null(group.facet.levels)) {\n df$group.facet <- factor(df$group.facet)\n } else {\n df$group.facet <- factor(df$group.facet, levels = group.facet.levels)\n }\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n gg <- gg + facet_wrap(~group.facet, nrow = n.row)\n }\n } else {\n gg <- ggplot(df, aes(x=dataset, y=count, fill = group)) +\n geom_bar(stat=\"identity\", width=width, position=position_dodge())\n }\n gg <- gg + geom_text(aes(label=count), vjust=-0.3, size=3, position = position_dodge(0.9))\n gg <- gg + ylab(ylabel) + xlab(xlabel) + theme_classic() +\n labs(title = title.name) + theme(plot.title = element_text(size = 10, face = \"bold\", hjust = 0.5)) +\n theme(text = element_text(size = size.text), axis.text = element_text(colour=\"black\"))\n gg <- gg + scale_fill_manual(values = alpha(color.use, alpha = color.alpha), drop = FALSE)\n # gg <- gg + scale_color_manual(values = alpha(color.use, alpha = 1), drop = FALSE) + guides(colour = FALSE)\n if (remove.xtick) {\n gg <- gg + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank())\n }\n if (is.null(legend.title)) {\n gg <- gg + theme(legend.title = element_blank())\n } else {\n gg <- gg + guides(fill=guide_legend(legend.title))\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n if (x.lab.rot) {\n gg <- gg + theme(axis.text.x = element_text(angle = angle.x, hjust = hjust.x, vjust = vjust.x, size=size.text))\n }\n gg\n return(gg)\n}\n\n\n#' Rank ligand-receptor interactions for any pair of two cell groups\n#'\n#' @param object CellChat object\n#' @param LR.use ligand-receptor interactions used in inferring communication network\n#' @return\n#' @export\n#'\nrankNetPairwise <- function(object, LR.use = NULL) {\n if (is.null(LR.use)) {\n pairLR.use <- object@LR$LRsig\n } else {\n pairLR.use <- LR.use\n }\n net <- object@net\n prob <- net$prob\n pval <- net$pval\n numCluster <- dim(prob)[1]\n pairwiseLR <- list()\n for (i in 1:numCluster) {\n temp <- list()\n for (j in 1:numCluster) {\n pvalij <- pval[i,j,]; pvalij <- as.vector(pvalij)\n probij <- prob[i,j,]; probij <- as.vector(probij)\n index <- 1:length(pvalij)\n data <- data.frame(pathway_index = index, interaction_name = pairLR.use$interaction_name, interaction_name_2 = pairLR.use$interaction_name_2, pathway_name = pairLR.use$pathway_name, ligand = pairLR.use$ligand, receptor = pairLR.use$receptor,\n prob = probij, pval = pvalij, row.names = rownames(pairLR.use))\n temp[[j]] <- data[with(data, order(pval, -prob)), ]\n }\n names(temp) <- colnames(prob)\n pairwiseLR[[i]] <- temp\n }\n names(pairwiseLR) <- rownames(prob)\n object@net$pairwiseRank <- pairwiseLR\n return(object)\n}\n\n\n#' compute the Shannon entropy\n#'\n#' @param a a numeric vector\n#' @return\nentropia<-function(a){\n a<-a[which(a>0)]\n return(-sum(a*log(a)))\n}\n\n\n#' compute the node distance matrix\n#'\n#' @param g a graph objecct\n#' @return\nnode_distance<-function(g){\n n<-length(V(g))\n if(n==1){\n retorno=1\n }\n\n if(n>1){\n a<-Matrix::Matrix(0,nrow=n,ncol=n,sparse=TRUE)\n m<-igraph::shortest.paths(g,algorithm=c(\"unweighted\"))\n m[which(m==\"Inf\")]<-n\n quem<-setdiff(intersect(m,m),0)\n for(j in (1:length(quem))){\n\n l<-which(m==quem[j])/n\n\n linhas<-floor(l)+1\n\n posicoesm1<-which(l==floor(l))\n\n if(length(posicoesm1)>0){\n linhas[posicoesm1]<-linhas[posicoesm1]-1\n }\n a[1:n,quem[j]]<-hist(linhas,plot=FALSE,breaks=(0:n))$counts\n\n }\n retorno=(a/(n-1))\n }\n return(retorno)\n}\n\n\n#' compute nnd\n#'\n#' @param g a graph objecct\n#' @return\nnnd<-function(g){\n\n N<-length(V(g))\n\n nd<-node_distance(g)\n\n pdfm<-Matrix::colMeans(nd)\n\n norm<-log(max(c(2,length(which(pdfm[1:(N-1)]>0))+1)))\n\n return(c(pdfm,max(c(0,entropia(pdfm)-entropia(as.matrix(nd))/N))/norm))\n}\n\n#' compute alpha centrality\n#'\n#' @param g a graph objecct\n#' @importFrom igraph degree alpha.centrality\n#' @return\nalpha_centrality<-function(g){\n\n N<-length(igraph::V(g))\n\n r<-sort(igraph::alpha.centrality(g,exo=igraph::degree(g)/(N-1),alpha=1/N))/((N^2))\n\n return(c(r,max(c(0,1-sum(r)))))\n\n}\n\n#' Compute the structural distance between two signaling networks\n#'\n#' @param g a graph object of one signaling network\n#' @param h a graph object of another signaling network\n#' @param w1 parameter\n#' @param w2 parameter\n#' @param w3 parameter\n#' @importFrom igraph graph_from_adjacency_matrix V graph.complementer\n#' @return\n#' @export\n#'\n#' @examples\ncomputeNetD_structure <- function(g, h, w1 = 0.45, w2 = 0.45, w3 = 0.1){\n\n first<-0\n\n second<-0\n\n third<-0\n\n # g<-read.graph(g,format=c(\"edgelist\"),directed=FALSE)\n #\n # h<-read.graph(h,format=c(\"edgelist\"),directed=FALSE)\n\n g <- graph_from_adjacency_matrix(g,mode=\"directed\")\n h <- graph_from_adjacency_matrix(h,mode=\"directed\")\n\n N<-length(V(g))\n\n M<-length(V(h))\n\n PM<-matrix(0,ncol=max(c(M,N)))\n\n if(w1+w2>0){\n\n pg = nnd(g)\n\n PM[1:(N-1)]=pg[1:(N-1)]\n\n PM[length(PM)]<-pg[N]\n\n ph=nnd(h)\n\n PM[1:(M-1)]=PM[1:(M-1)]+ph[1:(M-1)]\n\n PM[length(PM)]<-PM[length(PM)]+ph[M]\n\n PM<-PM/2\n\n first<-sqrt(max(c((entropia(PM)-(entropia(pg[1:N])+entropia(ph[1:M]))/2)/log(2),0)))\n\n second<-abs(sqrt(pg[N+1])-sqrt(ph[M+1]))\n\n\n }\n\n if(w3>0){\n\n pg<-alpha_centrality(g)\n\n ph<-alpha_centrality(h)\n\n m<-max(c(length(pg),length(ph)))\n\n Pg<-matrix(0,ncol=m)\n\n Ph<-matrix(0,ncol=m)\n\n Pg[(m-length(pg)+1):m]<-pg\n\n Ph[(m-length(ph)+1):m]<-ph\n\n third<-third+sqrt((entropia((Pg+Ph)/2)-(entropia(pg)+entropia(ph))/2)/log(2))/2\n\n g<-graph.complementer(g)\n\n h<-graph.complementer(h)\n\n\n pg<-alpha_centrality(g)\n\n ph<-alpha_centrality(h)\n\n m<-max(c(length(pg),length(ph)))\n\n Pg<-matrix(0,ncol=m)\n\n Ph<-matrix(0,ncol=m)\n\n Pg[(m-length(pg)+1):m]<-pg\n\n Ph[(m-length(ph)+1):m]<-ph\n\n third<-third+sqrt((entropia((Pg+Ph)/2)-(entropia(pg)+entropia(ph))/2)/log(2))/2\n }\n return(w1*first+w2*second+w3*third)\n}\n\n\n#' Identify all the significant interactions (L-R pairs) and related signaling genes for a given signaling pathway\n#'\n#' @param object CellChat object\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param geneLR.return whether return the related signaling genes of enriched L-R pairs\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param geneInfo a dataframe with gene official symbol (there should be one column named `Symbol`)\n#' @param complex_input signaling complex information from CellChatDB\n#' @importFrom dplyr select\n#'\n#' @return The returned value depends on the input argument:\n#'\n#' When `geneLR.return = FALSE`, it returns a data frame containing the significant interactions (L-R pairs)\n#'\n#' When `geneLR.return = TRUE`, it returns a list, the first element is a data frame containing the significant interactions (L-R pairs), and the second is a vector containing the related signaling genes of enriched L-R pairs, which can be used for examining the gene expression pattern using the function \\code{\\link{plotGeneExpression}}\n#'\n#' @export\n#'\nextractEnrichedLR <- function(object, signaling, geneLR.return = FALSE, enriched.only = TRUE, thresh = 0.05, geneInfo = NULL, complex_input = NULL) {\n DB <- object@DB\n if (is.null(geneInfo)) {\n geneInfo = DB$geneInfo\n } else {\n DB$geneInfo = geneInfo\n }\n if (is.null(complex_input)) {\n complex_input = DB$complex\n } else {\n DB$complex = complex_input\n }\n pairLR.all <- c()\n geneLR.all <- c()\n net0 <- slot(object, \"net\")\n for (ii in 1:length(signaling)) {\n signaling.i <- signaling[ii]\n if (object@options$mode == \"single\") {\n net <- net0\n LR <- object@LR\n res <- extractEnrichedLR_internal(net, LR, DB, signaling = signaling.i, enriched.only = enriched.only, thresh = thresh)\n } else {\n geneLR.t <- c()\n pairLR.t <- c()\n for (i in 1:length(net0)) {\n net <- net0[[i]]\n LR <- object@LR[[i]]\n res.t <- extractEnrichedLR_internal(net, LR, DB, signaling = signaling.i, enriched.only = enriched.only, thresh = thresh)\n geneLR.t <- BiocGenerics::union(geneLR.t, as.character(res.t[[1]]))\n pairLR.t <- BiocGenerics::union(pairLR.t, as.character(res.t[[2]]))\n }\n res <- list(geneLR.t, pairLR.t)\n }\n geneLR.all <- c(geneLR.all, as.character(res[[1]]))\n pairLR.all <- c(pairLR.all, as.character(res[[2]]))\n }\n pairLR.all <- data.frame(interaction_name = pairLR.all, stringsAsFactors = FALSE)\n\n if (geneLR.return) {\n return(list(pairLR = pairLR.all, geneLR = geneLR.all))\n } else {\n return(pairLR.all)\n }\n}\n\n#' Identify all the significant interactions (L-R pairs) and related signaling genes for a given signaling pathway\n#'\n#' @param net,LR,DB object@net object@LR object@DB\n#' @param signaling a char vector containing signaling pathway names for searching\n#' @param enriched.only whether only return the identified enriched signaling genes in the database. Default = TRUE, returning the significantly enriched signaling interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom dplyr select\n#'\n#' @return a list: list(geneLR, pairLR.name.use)\nextractEnrichedLR_internal <- function(net, LR, DB, signaling, enriched.only = TRUE, thresh = 0.05){\n pairLR <- searchPair(signaling = signaling, pairLR.use = LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.name.use = dplyr::select(DB$interaction[rownames(pairLR),],\"interaction_name\")\n if (enriched.only) {\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n if (length(pairLR.name.use) == 0) {\n message(paste0('There is no significant communication of ', signaling))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n }\n geneL <- unique(pairLR$ligand)\n geneR <- unique(pairLR$receptor)\n geneL <- extractGeneSubset(geneL, DB$complex, DB$geneInfo)\n geneR <- extractGeneSubset(geneR, DB$complex, DB$geneInfo)\n geneLR <- c(geneL, geneR)\n return(list(geneLR, pairLR.name.use))\n}\n\n\n#' Compute the maximum value of certain measures in the inferred cell-cell communication networks\n#'\n#' To better control the node size and edge weights of the inferred networks across different datasets,\n#' we compute the maximum number of cells per cell group and the maximum number of interactions (or interaction weights) across all datasets\n#'\n#' @param object.list List of CellChat objects\n#' @param slot.name the slot name of object that is used to compute the maximum value.\n#'\n#' When slot.name = \"idents\", 'attribute' should be \"idents\", which will compute the maximum number of cells per cell group across all datasets\n#'\n#' When slot.name = \"net\", 'attribute' can be either \"count\" or \"weight\", which will compute he maximum number of interactions (or interaction weights) across all datasets\n#'\n#' When slot.name = \"net\" or \"netP\", 'attribute' can be a single pathway name or a ligand-receptor pair name\n#'\n#' @param attribute the attribute to compute the maximum values. `attribute` should have the same length as `slot.name`.\n#'\n#' `attribute` can only be \"count\", \"weight\",\"count.merged\",\"weight.merged\" or a single pathway name or a ligand-receptor pair name\n#'\n#' @return A numeric vector\n#' @export\n#'\ngetMaxWeight <- function(object.list, slot.name = c(\"idents\", \"net\"), attribute = c(\"idents\", \"count\")) {\n weight <- c()\n for (i in 1:length(slot.name)) {\n if (slot.name[i] == \"idents\") {\n weight.all <- sapply(object.list, function (x) {max(as.numeric(table(slot(x, slot.name[i]))))})\n } else if ((slot.name[i] == \"net\") & (attribute[i] %in% c(\"count\", \"weight\",\"count.merged\",\"weight.merged\"))) {\n weight.all <- sapply(object.list, function (x) {max(slot(x, slot.name[i])[[attribute[i]]])})\n } else if (attribute[i] %in% c(object.list[[1]]@DB$interaction$pathway_name, object.list[[1]]@DB$interaction$interaction_name)) {\n weight.all <- sapply(object.list, function (x) {max(slot(x, slot.name[i])$prob[,,attribute[i]])})\n }\n weight[i] <- max(weight.all)\n }\n names(weight) <- attribute\n weight.max <- weight\n return(weight.max)\n}\n\n\n#' Compute the number of interactions/interaction strength between cell types based on their associated cell subpopulations\n#'\n#' @param object CellChat object\n#' @param group.merged a factor defining the group for merging different clusters/subpopulations\n#'\n#' @return An updated slot `net` by adding three elements:\n#'\n#' `count.merged`: the number of interactions between cell types (i.e., merged cell groups)\n#'\n#' `weight.merged`: interaction strength between cell types (i.e., merged cell groups)\n#'\n#' `group.merged` the defined group for merging different clusters/subpopulations\n#'\n#' @export\n#'\nmergeInteractions <- function(object, group.merged) {\n if (!is.factor(group.merged)) {\n group.merged <- factor(group.merged)\n }\n count <- object@net$count\n count.merged <- matrix(0, nrow = nlevels(group.merged), ncol = nlevels(group.merged))\n rownames(count.merged) <- levels(group.merged); colnames(count.merged) <- levels(group.merged);\n weight <- object@net$weight\n weight.merged <- count.merged\n dimnames(weight.merged) <- dimnames(count.merged)\n for (i in levels(group.merged)) {\n for (j in levels(group.merged)) {\n count.merged[i, j] <- sum(count[group.merged == i, group.merged == j])\n weight.merged[i, j] <- sum(weight[group.merged == i, group.merged == j])\n }\n }\n object@net$count.merged <- count.merged\n object@net$weight.merged <- weight.merged\n object@net$group.merged <- group.merged\n return(object)\n}\n\n\n#' Subset the inferred cell-cell communications of interest\n#'\n#' NB: If all arguments are NULL, it returns a data frame consisting of all the inferred cell-cell communications\n#'\n#' @param object CellChat object\n#' @param net Alternative input is a data frame with at least with three columns defining the cell-cell communication network (\"source\",\"target\",\"interaction_name\")\n#' @param slot.name the slot name of object: slot.name = \"net\" when extracting the inferred communications at the level of ligands/receptors; slot.name = \"netP\" when extracting the inferred communications at the level of signaling pathways\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param datasets select the inferred cell-cell communications from a particular `datasets` when inputing a data frame `net`\n#' @param ligand.pvalues,ligand.logFC,ligand.pct.1,ligand.pct.2 set threshold for ligand genes\n#'\n#' ligand.pvalues: threshold for pvalues in the differential expression gene analysis (DEG)\n#'\n#' ligand.logFC: threshold for logFoldChange in the DEG analysis; When ligand.logFC > 0, keep upgulated genes; otherwise, kepp downregulated genes\n#'\n#' ligand.pct.1: threshold for the percent of expressed genes in the defined 'positive' cell group. keep genes with percent greater than ligand.pct.1\n#'\n#' ligand.pct.2: threshold for the percent of expressed genes in the cells except for the defined 'positive' cell group\n#'\n#' @param receptor.pvalues,receptor.logFC,receptor.pct.1,receptor.pct.2 set threshold for receptor genes\n#' @importFrom dplyr select group_by summarize groups\n#' @importFrom stringr str_split\n#' @importFrom BiocGenerics as.data.frame\n#' @importFrom reshape2 melt\n#' @importFrom magrittr %>%\n#'\n#' @return If input object is created from a single dataset, a data frame of the inferred cell-cell communications of interest, consisting of source, target, interaction_name, pathway_name, prob and other information\n#'\n#' If input object is a merged object from multiple datasets, it will return a list and each element is a data frame for one dataset\n#'\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # access all the inferred cell-cell communications\n#' df.net <- subsetCommunication(cellchat)\n#'\n#' # access all the inferred cell-cell communications at the level of signaling pathways\n#' df.net <- subsetCommunication(cellchat, slot.name = \"netP\")\n#'\n#' # Subset to certain cells with sources.use and targets.use\n#' df.net <- subsetCommunication(cellchat, sources.use = c(1,2), targets.use = c(4,5))\n#'\n#' # Subset to certain signaling, e.g., WNT and TGFb\n#' df.net <- subsetCommunication(cellchat, signaling = c(\"WNT\", \"TGFb\"))\n#'}\n#'\nsubsetCommunication <- function(object = NULL, net = NULL, slot.name = \"net\",\n sources.use = NULL, targets.use = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n thresh = 0.05,\n datasets = NULL, ligand.pvalues = NULL, ligand.logFC = NULL, ligand.pct.1 = NULL, ligand.pct.2 = NULL,\n receptor.pvalues = NULL, receptor.logFC = NULL, receptor.pct.1 = NULL, receptor.pct.2 = NULL) {\n if (!is.null(pairLR.use)) {\n if (!is.data.frame(pairLR.use)) {\n stop(\"pairLR.use should be a data frame with a signle column named either 'interaction_name' or 'pathway_name' \")\n } else if (\"pathway_name\" %in% colnames(pairLR.use)) {\n message(\"slot.name is set to be 'netP' when pairLR.use contains signaling pathways\")\n slot.name = \"netP\"\n }\n }\n\n if (!is.null(pairLR.use) & !is.null(signaling)) {\n stop(\"Please do not assign values to 'signaling' when using 'pairLR.use'\")\n }\n\n if (object@options$mode == \"single\") {\n if (is.null(net)) {\n net <- slot(object, \"net\")\n }\n LR <- object@LR$LRsig\n cells.level <- levels(object@idents)\n df.net <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n } else if (object@options$mode == \"merged\") {\n if (is.null(net)) {\n net0 <- slot(object, \"net\")\n df.net <- vector(\"list\", length(net0))\n names(df.net) <- names(net0)\n for (i in 1:length(net0)) {\n net <- net0[[i]]\n LR <- object@LR[[i]]$LRsig\n cells.level <- levels(object@idents[[i]])\n\n df.net[[i]] <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n }\n } else {\n LR <- data.frame()\n for (i in 1:length(object@LR)) {\n LR <- rbind(LR, object@LR[[i]]$LRsig)\n }\n LR <- unique(LR)\n cells.level <- levels(object@idents$joint)\n df.net <- subsetCommunication_internal(net, LR, cells.level, slot.name = slot.name,\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh,\n datasets = datasets, ligand.pvalues = ligand.pvalues, ligand.logFC = ligand.logFC, ligand.pct.1 = ligand.pct.1, ligand.pct.2 = ligand.pct.2,\n receptor.pvalues = receptor.pvalues, receptor.logFC = receptor.logFC, receptor.pct.1 = receptor.pct.1, receptor.pct.2 =receptor.pct.2)\n }\n\n }\n\n return(df.net)\n\n}\n\n#' Subset the inferred cell-cell communications of interest\n#'\n#' NB: If all arguments are NULL, it returns a data frame consisting of all the inferred cell-cell communications\n#'\n#' @param net,LR,cells.level net is object@net or a data frame; LR: object@LR$LRsig; cells.level: levels(object@idents)\n#' @param slot.name the slot name of object: slot.name = \"net\" when extracting the inferred communications at the level of ligands/receptors; slot.name = \"netP\" when extracting the inferred communications at the level of signaling pathways\n#' @param sources.use a vector giving the index or the name of source cell groups\n#' @param targets.use a vector giving the index or the name of target cell groups.\n#' @param signaling a character vector giving the name of signaling pathways of interest\n#' @param pairLR.use a data frame consisting of one column named either \"interaction_name\" or \"pathway_name\", defining the interactions of interest\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param datasets select the inferred cell-cell communications from a particular `datasets` when inputing a data frame `net`\n#' @param ligand.pvalues,ligand.logFC,ligand.pct.1,ligand.pct.2 set threshold for ligand genes\n#'\n#' ligand.pvalues: threshold for pvalues in the differential expression gene analysis (DEG)\n#'\n#' ligand.logFC: threshold for logFoldChange in the DEG analysis; When ligand.logFC > 0, keep upgulated genes; otherwise, kepp downregulated genes\n#'\n#' ligand.pct.1: threshold for the percent of expressed genes in the defined 'positive' cell group. keep genes with percent greater than ligand.pct.1\n#'\n#' ligand.pct.2: threshold for the percent of expressed genes in the cells except for the defined 'positive' cell group\n#'\n#' @param receptor.pvalues,receptor.logFC,receptor.pct.1,receptor.pct.2 set threshold for receptor genes\n#' @importFrom dplyr select group_by summarize groups\n#' @importFrom stringr str_split\n#' @importFrom BiocGenerics as.data.frame\n#' @importFrom reshape2 melt\n#' @importFrom magrittr %>%\n#'\n#' @return A data frame of the inferred cell-cell communications of interest, consisting of source, target, interaction_name, pathway_name, prob and other information\n\nsubsetCommunication_internal <- function(net, LR, cells.level, slot.name = \"net\",\n sources.use = NULL, targets.use = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n thresh = 0.05,\n datasets = NULL, ligand.pvalues = NULL, ligand.logFC = NULL, ligand.pct.1 = NULL, ligand.pct.2 = NULL,\n receptor.pvalues = NULL, receptor.logFC = NULL, receptor.pct.1 = NULL, receptor.pct.2 = NULL) {\n if (!is.data.frame(net)) {\n prob <- net$prob\n pval <- net$pval\n prob[pval >= thresh] <- 0\n net <- reshape2::melt(prob, value.name = \"prob\")\n colnames(net)[1:3] <- c(\"source\",\"target\",\"interaction_name\")\n net.pval <- reshape2::melt(pval, value.name = \"pval\")\n net$pval <- net.pval$pval\n # remove the interactions with zero values\n net <- subset(net, prob > 0)\n }\n if (!(\"ligand\" %in% colnames(net))) {\n col.use <- intersect(c(\"interaction_name_2\", \"pathway_name\", \"ligand\", \"receptor\" ,\"annotation\",\"evidence\"), colnames(LR))\n pairLR <- dplyr::select(LR, col.use)\n idx <- match(net$interaction_name, rownames(pairLR))\n net <- cbind(net, pairLR[idx,])\n }\n\n if (!is.null(signaling)) {\n pairLR.use <- data.frame()\n for (i in 1:length(signaling)) {\n pairLR.use.i <- searchPair(signaling = signaling[i], pairLR.use = LR, key = \"pathway_name\", matching.exact = T, pair.only = T)\n pairLR.use <- rbind(pairLR.use, pairLR.use.i)\n }\n }\n\n if (!is.null(pairLR.use)){\n net <- tryCatch({\n subset(net,interaction_name %in% pairLR.use$interaction_name)\n }, error = function(e) {\n subset(net, pathway_name %in% pairLR.use$pathway_name)\n })\n }\n\n if (!is.null(datasets)) {\n if (!(\"datasets\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before selecting 'datasets'\")\n }\n net <- net[net$datasets %in% datasets, , drop = FALSE]\n }\n if (!is.null(ligand.pvalues)){\n if (!(\"ligand.pvalues\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pvalues'\")\n }\n net <- net[net$ligand.pvalues <= ligand.pvalues, , drop = FALSE]\n }\n if (!is.null(ligand.logFC)){\n if (!(\"ligand.logFC\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.logFC'\")\n }\n if (ligand.logFC >= 0) {\n net <- net[net$ligand.logFC >= ligand.logFC, , drop = FALSE]\n } else {\n net <- net[net$ligand.logFC <= ligand.logFC, , drop = FALSE]\n }\n }\n if (!is.null(ligand.pct.1)){\n if (!(\"ligand.pct.1\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pct.1'\")\n }\n net <- net[net$ligand.pct.1 >= ligand.pct.1, , drop = FALSE]\n }\n if (!is.null(ligand.pct.2)){\n if (!(\"ligand.pct.2\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'ligand.pct.2'\")\n }\n net <- net[net$ligand.pct.2 >= ligand.pct.2, , drop = FALSE]\n }\n\n if (!is.null(receptor.pvalues)){\n if (!(\"receptor.pvalues\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pvalues'\")\n }\n net <- net[net$receptor.pvalues <= receptor.pvalues, , drop = FALSE]\n }\n if (!is.null(receptor.logFC)){\n if (!(\"receptor.logFC\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.logFC'\")\n }\n if (receptor.logFC >= 0) {\n net <- net[net$receptor.logFC >= receptor.logFC, , drop = FALSE]\n } else {\n net <- net[net$receptor.logFC <= receptor.logFC, , drop = FALSE]\n }\n }\n if (!is.null(receptor.pct.1)){\n if (!(\"receptor.pct.1\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pct.1'\")\n }\n net <- net[net$receptor.pct.1 >= receptor.pct.1, , drop = FALSE]\n }\n if (!is.null(receptor.pct.2)){\n if (!(\"receptor.pct.2\" %in% colnames(net))) {\n stop(\"Please run `identifyOverExpressedGenes` and `netMappingDEG` before using the threshold 'receptor.pct.2'\")\n }\n net <- net[net$receptor.pct.2 >= receptor.pct.2, , drop = FALSE]\n }\n\n net <- net[rowSums(is.na(net)) != ncol(net), , drop = FALSE]\n\n if (nrow(net) == 0) {\n stop(\"No significant signaling interactions are inferred based on the input!\")\n }\n\n\n if (slot.name == \"netP\") {\n col.use <- intersect(c(\"source\",\"target\",\"pathway_name\",\"prob\", \"pval\",\"annotation\"), colnames(net))\n net <- dplyr::select(net, col.use)\n net$source_target <- paste(net$source, net$target, sep = \"sourceTotarget\")\n # net$source_target_pathway <- paste(paste(net$source, net$target, sep = \"_\"), net$pathway_name, sep = \"_\")\n net.pval <- net %>% group_by(source_target, pathway_name) %>% summarize(pval = mean(pval), .groups = 'drop')\n net <- net %>% group_by(source_target, pathway_name) %>% summarize(prob = sum(prob), .groups = 'drop')\n a <- stringr::str_split(net$source_target, \"sourceTotarget\", simplify = T)\n net$source <- as.character(a[, 1])\n net$target <- as.character(a[, 2])\n net <- dplyr::select(net, -source_target)\n net$pval <- net.pval$pval\n }\n\n # keep the interactions associated with sources and targets of interest\n if (!is.null(sources.use)){\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n net <- subset(net, source %in% sources.use)\n }\n if (!is.null(targets.use)){\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n net <- subset(net, target %in% targets.use)\n }\n\n net <- BiocGenerics::as.data.frame(net, stringsAsFactors=FALSE)\n\n if (nrow(net) == 0) {\n warning(\"No significant signaling interactions are inferred!\")\n } else {\n rownames(net) <- 1:nrow(net)\n }\n\n if (slot.name == \"net\") {\n if ((\"ligand.logFC\" %in% colnames(net)) & (\"datasets\" %in% colnames(net))) {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\",\n \"datasets\",\"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\", \"ligand.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\", \"receptor.pvalues\"), colnames(net))\n net <- net[,col.use]\n } else if (\"ligand.logFC\" %in% colnames(net)) {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\",\n \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\", \"ligand.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\", \"receptor.pvalues\"), colnames(net))\n net <- net[,col.use]\n } else {\n col.use <- intersect(c(\"source\", \"target\", \"ligand\", \"receptor\", \"prob\", \"pval\", \"interaction_name\", \"interaction_name_2\", \"pathway_name\",\"annotation\",\"evidence\"), colnames(net))\n net <- net[,col.use]\n }\n } else if (slot.name == \"netP\") {\n col.use <- intersect(c(\"source\", \"target\", \"pathway_name\", \"prob\", \"pval\"), colnames(net))\n net <- net[,col.use]\n }\n\n return(net)\n\n}\n\n\n\n\n\n\n\n\n\n\n#' Heatmap showing the centrality scores/importance of cell groups as senders, receivers, mediators and influencers in a single intercellular communication network\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the name of signaling networks\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param measure centrality measures to show\n#' @param measure.name the names of centrality measures to show\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation draw\n#' @importFrom stats setNames\n#'\n#' @return\n#' @export\n#'\n#' @examples\nnetAnalysis_signalingRole_network <- function(object, signaling, slot.name = \"netP\", measure = c(\"outdeg\",\"indeg\",\"flowbet\",\"info\"), measure.name = c(\"Sender\",\"Receiver\",\"Mediator\",\"Influencer\"),\n color.use = NULL, color.heatmap = \"BuGn\",\n width = 6.5, height = 1.4, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE) {\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n centr <- slot(object, slot.name)$centr[signaling]\n for(i in 1:length(centr)) {\n centr0 <- centr[[i]]\n mat <- matrix(unlist(centr0), ncol = length(centr0), byrow = FALSE)\n mat <- t(mat)\n rownames(mat) <- names(centr0); colnames(mat) <- names(centr0$outdeg)\n if (!is.null(measure)) {\n mat <- mat[measure,,drop = FALSE]\n if (!is.null(measure.name)) {\n if (length(measure.name) != length(measure)) {\n stop(\"The length of `measure.name` is not the same as that of `measure`! Please modify it! \\n\")\n }\n rownames(mat) <- measure.name\n }\n }\n mat <- sweep(mat, 1L, apply(mat, 1, max), '/', check.margin = FALSE)\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(colnames(mat)))\n }\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n\n df<- data.frame(group = colnames(mat)); rownames(df) <- colnames(mat)\n cell.cols.assigned <- setNames(color.use, unique(as.character(df$group)))\n col_annotation <- HeatmapAnnotation(df = df, col = list(group = cell.cols.assigned),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = \"Importance\",\n bottom_annotation = col_annotation,\n cluster_rows = cluster.rows,cluster_columns = cluster.cols,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = paste0(names(centr[i]), \" signaling pathway network\"),column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 45,\n heatmap_legend_param = list(title = \"Importance\", title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = c(round(min(mat, na.rm = T), digits = 1), round(max(mat, na.rm = T), digits = 1)),\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n draw(ht1)\n }\n}\n\n\n#' 2D visualization of dominant senders (sources) and receivers (targets)\n#'\n#' @description\n#' This scatter plot shows the dominant senders (sources) and receivers (targets) in a 2D space.\n#' x-axis and y-axis are respectively the total outgoing or incoming communication probability associated with each cell group.\n#' Dot size is proportional to the number of inferred links (both outgoing and incoming) associated with each cell group.\n#' Dot colors indicate different cell groups. Dot shapes indicate different categories of cell groups if `group`` is defined.\n#'\n#' @param object CellChat object\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param color.use defining the color for each cell group\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param group a vector to categorize the cell groups, e.g., categorize the cell groups into two major categories: immune cells and fibroblasts\n#' @param weight.MinMax the Minmum/maximum weight, which is useful to control the dot size when comparing multiple datasets\n#' @param point.shape point shape when group is not NULL\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size a range defining the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_signalingRole_scatter <- function(object, signaling = NULL, color.use = NULL, slot.name = \"netP\", group = NULL, weight.MinMax = NULL, dot.size = c(2, 6), point.shape = c(21, 22, 24, 23, 25, 8, 3), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\",xlabel = \"Outgoing interaction strength\", ylabel = \"Incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n centr <- slot(object, slot.name)$centr\n outgoing <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n incoming <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n dimnames(outgoing) <- list(levels(object@idents), names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n if (is.null(signaling)) {\n message(\"Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\")\n } else {\n message(\"Signaling role analysis on the cell-cell communication network from user's input\")\n signaling <- signaling[signaling %in% object@netP$pathways]\n if (length(signaling) == 0) {\n stop('There is no significant communication for the input signaling. All the significant signaling are shown in `object@netP$pathways`')\n }\n outgoing <- outgoing[ , signaling, drop = FALSE]\n incoming <- incoming[ , signaling, drop = FALSE]\n }\n outgoing.cells <- rowSums(outgoing)\n incoming.cells <- rowSums(incoming)\n\n num.link <- aggregateNet(object, signaling = signaling, return.object = FALSE, remove.isolate = FALSE)$count\n num.link <- rowSums(num.link) + colSums(num.link)-diag(num.link)\n df <- data.frame(x = outgoing.cells, y = incoming.cells, labels = names(incoming.cells),\n Count = num.link)\n df$labels <- factor(df$labels, levels = names(incoming.cells))\n if (!is.null(group)) {\n df$Group <- group\n }\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(object@idents))\n }\n if (!is.null(group)) {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Count, colour = labels, fill = labels, shape = Group))\n } else {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(size = Count, colour = labels, fill = labels))\n }\n\n gg <- gg + CellChat_theme_opts() +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\"))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE) + guides(colour=\"none\")\n # gg <- gg + scale_colour_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(colour=\"none\")\n # gg <- gg + scale_shape_manual(values = point.shape[1:length(prob)])\n if (!is.null(group)) {\n gg <- gg + scale_shape_manual(values = point.shape[1:length(unique(df$Group))])\n }\n if (is.null(weight.MinMax)) {\n gg <- gg + scale_size_continuous(range = dot.size)\n } else {\n gg <- gg + scale_size_continuous(limits = weight.MinMax, range = dot.size)\n }\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = labels), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n\n#' 2D visualization of differential signaling roles (dominant senders (sources) or receivers (targets) ) of each cell group when comparing mutiple datasets\n#'\n#' @description\n#' This scatter plot shows the differential signaling roles (dominant senders (sources) or receivers (targets) in a 2D space.\n#'\n#' x-axis and y-axis are respectively the differential outgoing or incoming communication probability associated with each cell group.\n#' Dot colors indicate different cell groups. Dot shapes indicate different categories of cell groups if `group`` is defined.\n#'\n#' Positive values indicate the increase in the second dataset while negative values indicate the increase in the first dataset\n#'\n#' @param object A merged CellChat object of a list of CellChat objects\n#' @param color.use defining the color for each cell group\n#' @param comparison an index vector giving the two datasets for comparison\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param signaling.exclude signaling pathways to exclude\n#' @param idents.exclude cell groups to exclude. This is useful when zooming into the small changes\n#' @param slot.name the slot name of object that is used to compute centrality measures of signaling networks\n#' @param group a vector to categorize the cell groups, e.g., categorize the cell groups into two major categories: immune cells and fibroblasts\n#' @param point.shape point shape when group is not NULL\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., Outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., Incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_diff_signalingRole_scatter <- function(object, color.use = NULL, comparison = c(1,2), signaling = NULL, signaling.exclude = NULL, idents.exclude = NULL, slot.name = \"netP\", group = NULL, dot.size = 2.5, point.shape = c(21, 22, 24, 23, 25, 8, 3), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\", xlabel = \"Outgoing interaction strength\", ylabel = \"Incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (is.list(object)) {\n object <- mergeCellChat(object, add.names = names(object))\n }\n if (!is.list(object@net[[1]])) {\n stop(\"This function cannot be applied to a single cellchat object from one dataset!\")\n }\n\n dataset.name <- names(object@net)\n message(paste0(\"Visualizing differential outgoing and incoming signaling changes from \", dataset.name[comparison[1]], \" to \", dataset.name[comparison[2]]))\n title <- paste0(\"Signaling changes \", \" (\", dataset.name[comparison[1]], \" vs. \", dataset.name[comparison[2]], \")\")\n\n cell.levels <- levels(object@idents$joint)\n if (is.null(xlabel) | is.null(ylabel)) {\n xlabel = \"Differential outgoing interaction strength\"\n ylabel = \"Differential incoming interaction strength\"\n }\n if (is.null(signaling)) {\n signaling <- union(object@netP[[comparison[1]]]$pathways, object@netP[[comparison[2]]]$pathways)\n }\n if (!is.null(signaling.exclude)) {\n signaling <- setdiff(signaling, signaling.exclude)\n }\n\n mat.all.merged <- list()\n for (ii in 1:length(comparison)) {\n if (length(slot(object, slot.name)[[comparison[ii]]]$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores for each dataset seperately! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n\n centr <- slot(object, slot.name)[[comparison[ii]]]$centr\n outgoing <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n incoming <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n dimnames(outgoing) <- list(cell.levels, names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n mat.out <- t(outgoing)\n mat.in <- t(incoming)\n\n mat.all <- array(0, dim = c(length(signaling),ncol(mat.out),2))\n mat.t <-list(mat.out, mat.in)\n for (i in 1:length(comparison)) {\n mat = mat.t[[i]]\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n mat.all[,,i] = mat\n }\n dimnames(mat.all) <- list(dimnames(mat)[[1]], dimnames(mat)[[2]], c(\"outgoing\", \"incoming\"))\n mat.all.merged[[ii]] <- mat.all\n\n }\n\n mat.diff <- mat.all.merged[[2]] - mat.all.merged[[1]]\n\n outgoing.diff <- colSums(mat.diff[ , , 1])\n incoming.diff <- colSums(mat.diff[ , , 2])\n\n\n df <- data.frame(x = outgoing.diff, y = incoming.diff, labels = names(incoming.diff))\n df$labels <- factor(df$labels, levels = names(incoming.diff))\n if (!is.null(group)) {\n df$Group <- group\n }\n if (is.null(color.use)) {\n color.use <- scPalette(length(cell.levels))\n }\n if (!is.null(idents.exclude)) {\n df <- df[!(df$labels %in% idents.exclude), ]\n color.use <- color.use[!(cell.levels %in% idents.exclude)]\n df$labels = droplevels(df$labels, exclude = setdiff(levels(df$labels),unique(df$labels)))\n }\n\n if (!is.null(group)) {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = labels, fill = labels, shape = Group), size = dot.size)\n } else {\n gg <- ggplot(data = df, aes(x, y)) +\n geom_point(aes(colour = labels, fill = labels), size = dot.size)\n }\n\n gg <- gg + CellChat_theme_opts() + theme_linedraw() +theme(panel.grid = element_blank()) +\n geom_hline(yintercept=0,linetype=\"dashed\", color = \"grey50\", size = 0.25) + geom_vline(xintercept=0, linetype=\"dashed\", color = \"grey50\",size = 0.25) +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, face=\"plain\", hjust = 0.5))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE) + guides(colour=\"none\")\n if (!is.null(group)) {\n gg <- gg + scale_shape_manual(values = point.shape[1:length(unique(df$Group))])\n }\n if (do.label) {\n gg <- gg + ggrepel::geom_text_repel(mapping = aes(label = labels, colour = labels), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n\n#' 2D visualization of differential outgoing and incoming signaling associated with one cell group\n#'\n#' @description\n#' Positive values indicate the increase in the second dataset while negative values indicate the increase in the first dataset\n#'\n#'\n#' @param object A merged CellChat object of a list of CellChat objects\n#' @param idents.use the cell group names of interest. Should be one of `levels(object@idents$joint)`\n#' @param color.use a vector with three elements: the first is for coloring shared pathways, the second is for specific pathways in the first dataset, and the third is for specific pathways in the second dataset\n#' @param comparison an index vector giving the two datasets for comparison\n#' @param signaling a char vector containing signaling pathway names. signaling = NULL: Signaling role analysis on the aggregated cell-cell communication network from all signaling pathways\n#' @param signaling.label a char vector giving the signaling names to show when labeling each point\n#' @param top.label the fraction of signaling pathways to label\n#' @param signaling.exclude signaling pathways to exclude when plotting\n#' @param xlims,ylims set x-Axis and y-Axis Limits for zoom into the plot. e.g., xlims = c(-0.05, 0.1), ylims = c(-0.01, 0.035)\n#' @param slot.name the slot name of object\n#' @param point.shape point shape\n#' @param label.size font size of the text\n#' @param dot.alpha transparency\n#' @param dot.size the size of the symbol\n#' @param x.measure The measure used as x-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"outdeg\" is the weighted outgoing links (i.e., Outgoing interaction strength). If setting as \"outdeg_unweighted\", it represents the total number of outgoing signaling.\n#'\n#' @param y.measure The measure used as y-axis. This measure should be one of `names(slot(object, slot.name)$centr[[1]])` computed from `netAnalysis_computeCentrality`\n#'\n#' Default = \"indeg\" is the weighted incoming links (i.e., Incoming interaction strength). If setting as \"indeg_unweighted\", it represents the total number of incoming signaling.\n#'\n#' @param xlabel label of x-axis\n#' @param ylabel label of y-axis\n#' @param title main title of the plot\n#' @param font.size font size of the text\n#' @param font.size.title font size of the title\n#' @param do.label label the each point\n#' @param show.legend whether show the legend\n#' @param show.axes whether show the axes\n#' @import ggplot2\n#' @importFrom ggrepel geom_text_repel\n#' @importFrom methods slot\n#' @importFrom plyr mapvalues\n#' @return ggplot object\n#' @export\n#'\nnetAnalysis_signalingChanges_scatter <- function(object, idents.use, color.use = c(\"grey10\", \"#F8766D\", \"#00BFC4\"), comparison = c(1,2), signaling = NULL, signaling.label = NULL, top.label = 1, signaling.exclude = NULL, xlims = NULL, ylims = NULL,slot.name = \"netP\", dot.size = 2.5, point.shape = c(21, 22, 24, 23), label.size = 3, dot.alpha = 0.6,\n x.measure = \"outdeg\", y.measure = \"indeg\", xlabel = \"Differential outgoing interaction strength\", ylabel = \"Differential incoming interaction strength\", title = NULL,\n font.size = 10, font.size.title = 10, do.label = T, show.legend = T, show.axes = T) {\n if (is.list(object)) {\n object <- mergeCellChat(object, add.names = names(object))\n }\n if (is.list(object@net[[1]])) {\n dataset.name <- names(object@net)\n message(paste0(\"Visualizing differential outgoing and incoming signaling changes from \", dataset.name[comparison[1]], \" to \", dataset.name[comparison[2]]))\n title <- paste0(\"Signaling changes of \", idents.use, \" (\", dataset.name[comparison[1]], \" vs. \", dataset.name[comparison[2]], \")\")\n\n cell.levels <- levels(object@idents$joint)\n if (is.null(xlabel) | is.null(ylabel)) {\n xlabel = \"Differential outgoing interaction strength\"\n ylabel = \"Differential incoming interaction strength\"\n }\n\n } else {\n message(\"Visualizing outgoing and incoming signaling on a single object \\n\")\n title <- paste0(\"Signaling patterns of \", idents.use)\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n cell.levels <- levels(object@idents)\n }\n if (!(idents.use %in% cell.levels)) {\n stop(\"Please check the input cell group names!\")\n }\n if (is.null(signaling)) {\n signaling <- union(object@netP[[comparison[1]]]$pathways, object@netP[[comparison[2]]]$pathways)\n }\n if (!is.null(signaling.exclude)) {\n signaling <- setdiff(signaling, signaling.exclude)\n }\n mat.all.merged <- list()\n for (ii in 1:length(comparison)) {\n if (length(slot(object, slot.name)[[comparison[ii]]]$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores for each dataset seperately! \")\n }\n if (sum(c(x.measure, y.measure) %in% names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]])) !=2) {\n stop(paste0(\"`x.measure, y.measure` should be one of \", paste(names(slot(object, slot.name)[[comparison[ii]]]$centr[[1]]),collapse=\", \"), '\\n', \"`outdeg_unweighted` is only supported for version >= 1.1.2\"))\n }\n centr <- slot(object, slot.name)[[comparison[ii]]]$centr\n outgoing <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n incoming <- matrix(0, nrow = length(cell.levels), ncol = length(centr))\n dimnames(outgoing) <- list(cell.levels, names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]][[x.measure]]\n incoming[,i] <- centr[[i]][[y.measure]]\n }\n mat.out <- t(outgoing)\n mat.in <- t(incoming)\n\n mat.all <- array(0, dim = c(length(signaling),ncol(mat.out),2))\n mat.t <-list(mat.out, mat.in)\n for (i in 1:length(comparison)) {\n mat = mat.t[[i]]\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n mat.all[,,i] = mat\n }\n dimnames(mat.all) <- list(dimnames(mat)[[1]], dimnames(mat)[[2]], c(\"outgoing\", \"incoming\"))\n mat.all.merged[[ii]] <- mat.all\n }\n mat.all.merged.use <- list(mat.all.merged[[1]][,idents.use,], mat.all.merged[[2]][,idents.use,])\n idx.specific <- mat.all.merged.use[[1]] * mat.all.merged.use[[2]]\n mat.sum <- mat.all.merged.use[[2]] + mat.all.merged.use[[1]]\n out.specific.signaling <- rownames(idx.specific)[(mat.sum[,1] != 0) & (idx.specific[,1] == 0)]\n in.specific.signaling <- rownames(idx.specific)[(mat.sum[,2] != 0) & (idx.specific[,2] == 0)]\n\n mat.diff <- mat.all.merged.use[[2]] - mat.all.merged.use[[1]]\n idx <- rowSums(mat.diff) != 0\n mat.diff <- mat.diff[idx, ]\n out.specific.signaling <- rownames(mat.diff) %in% out.specific.signaling\n in.specific.signaling <- rownames(mat.diff) %in% in.specific.signaling\n out.in.specific.signaling <- as.logical(out.specific.signaling * in.specific.signaling)\n specificity.out.in <- matrix(0, nrow = nrow(mat.diff), ncol = 1)\n specificity.out.in[out.in.specific.signaling] <- 2 # both outgoing and incoming specific to one condition\n specificity.out.in[setdiff(which(out.specific.signaling), which(out.in.specific.signaling))] <- 1 # only outgoing specific to one condition\n specificity.out.in[setdiff(which(in.specific.signaling), which(out.in.specific.signaling))] <- -1 # only incoming specific to one condition\n\n\n df <- as.data.frame(mat.diff)\n df$specificity.out.in <- specificity.out.in\n df$specificity = 0\n df$specificity[(specificity.out.in != 0) & (rowSums(mat.diff >= 0) ==2)] = 1 # specific to dataset 2\n df$specificity[(specificity.out.in != 0) & (rowSums(mat.diff <= 0) ==2)] = -1 # specific to dataset 1\n\n # change number to char\n out.in.category <- c(\"Shared\", \"Incoming specific\", \"Outgoing specific\", \"Incoming & Outgoing specific\")\n specificity.category <- c(\"Shared\", paste0(dataset.name[comparison[1]],\" specific\"), paste0(dataset.name[comparison[2]],\" specific\"))\n df$specificity.out.in <- plyr::mapvalues(df$specificity.out.in, from = c(0,-1,1,2),to = out.in.category)\n df$specificity.out.in <- factor(df$specificity.out.in, levels = out.in.category)\n df$specificity <- plyr::mapvalues(df$specificity, from = c(0,-1,1),to = specificity.category)\n df$specificity <- factor(df$specificity, levels = specificity.category)\n\n point.shape.use <- point.shape[out.in.category %in% unique(df$specificity.out.in)]\n df$specificity.out.in = droplevels(df$specificity.out.in, exclude = setdiff(out.in.category,unique(df$specificity.out.in)))\n\n color.use <- color.use[specificity.category %in% unique(df$specificity)]\n df$specificity = droplevels(df$specificity, exclude = setdiff(specificity.category,unique(df$specificity)))\n\n df$labels <- rownames(df)\n gg <- ggplot(data = df, aes(outgoing, incoming)) +\n geom_point(aes(colour = specificity, fill = specificity, shape = specificity.out.in), size = dot.size)\n gg <- gg + theme_linedraw() +theme(panel.grid = element_blank()) +\n geom_hline(yintercept=0,linetype=\"dashed\", color = \"grey50\", size = 0.25) + geom_vline(xintercept=0, linetype=\"dashed\", color = \"grey50\",size = 0.25) +\n theme(text = element_text(size = font.size), legend.key.height = grid::unit(0.15, \"in\"))+\n # guides(colour = guide_legend(override.aes = list(size = 3)))+\n labs(title = title, x = xlabel, y = ylabel) + theme(plot.title = element_text(size= font.size.title, hjust = 0.5, face=\"plain\"))+\n # theme(axis.text.x = element_blank(),axis.text.y = element_blank(),axis.ticks = element_blank()) +\n theme(axis.line.x = element_line(size = 0.25), axis.line.y = element_line(size = 0.25))\n gg <- gg + scale_fill_manual(values = ggplot2::alpha(color.use, alpha = dot.alpha), drop = FALSE) + guides(fill=\"none\")\n gg <- gg + scale_colour_manual(values = color.use, drop = FALSE)\n gg <- gg + scale_shape_manual(values = point.shape.use)\n gg <- gg + theme(legend.title = element_blank())\n if (!is.null(xlims)) {\n gg <- gg + xlim(xlims)\n }\n if (!is.null(ylims)) {\n gg <- gg + ylim(ylims)\n }\n\n if (do.label) {\n if (is.null(signaling.label)) {\n thresh <- stats::quantile(abs(as.matrix(df[,1:2])), probs = 1-top.label)\n idx = abs(df[,1]) > thresh | abs(df[,2]) > thresh\n data.label <- df[idx,]\n } else {\n data.label <- df[rownames(df) %in% signaling.label, ]\n }\n\n gg <- gg + ggrepel::geom_text_repel(data = data.label, mapping = aes(label = labels, colour = specificity), size = label.size, show.legend = F,segment.size = 0.2, segment.alpha = 0.5)\n }\n if (!show.legend) {\n gg <- gg + theme(legend.position = \"none\")\n }\n\n if (!show.axes) {\n gg <- gg + theme_void()\n }\n\n gg\n\n}\n\n\n#' Heatmap showing the contribution of signals (signaling pathways or ligand-receptor pairs) to cell groups in terms of outgoing or incoming signaling\n#'\n#' In this heatmap, colobar represents the relative signaling strength of a signaling pathway across cell groups (NB: values are row-scaled).\n#' The top colored bar plot shows the total signaling strength of a cell group by summarizing all signaling pathways displayed in the heatmap.\n#' The right grey bar plot shows the total signaling strength of a signaling pathway by summarizing all cell groups displayed in the heatmap.\n#'\n#' @param object CellChat object\n#' @param signaling a character vector giving the names of signaling networks of interest\n#' @param pattern this parameter can be set as \"outgoing\", \"incoming\" or \"all\". When pattern = \"all\", CellChat aggregates the outgoing and incoming signaling strength together;\n#' @param slot.name the slot name of object that is used to examine the signaling patterns at the level of signaling pathways (slot.name = \"netP\") or ligand-receptor pairs (slot.name = \"net\");\n#' @param color.use the character vector defining the color of each cell group\n#' @param color.heatmap a color name in brewer.pal\n#' @param title title name\n#' @param width width of heatmap\n#' @param height height of heatmap\n#' @param font.size fontsize in heatmap\n#' @param font.size.title font size of the title\n#' @param cluster.rows whether cluster rows\n#' @param cluster.cols whether cluster columns\n#' @importFrom methods slot\n#' @importFrom grDevices colorRampPalette\n#' @importFrom RColorBrewer brewer.pal\n#' @importFrom ComplexHeatmap Heatmap HeatmapAnnotation anno_barplot rowAnnotation\n#' @importFrom stats setNames\n#'\n#' @return\n#' @export\n#'\nnetAnalysis_signalingRole_heatmap <- function(object, signaling = NULL, pattern = c(\"outgoing\", \"incoming\",\"all\"), slot.name = \"netP\",\n color.use = NULL, color.heatmap = \"BuGn\",\n title = NULL, width = 10, height = 8, font.size = 8, font.size.title = 10, cluster.rows = FALSE, cluster.cols = FALSE){\n pattern <- match.arg(pattern)\n if (length(slot(object, slot.name)$centr) == 0) {\n stop(\"Please run `netAnalysis_computeCentrality` to compute the network centrality scores! \")\n }\n centr <- slot(object, slot.name)$centr\n outgoing <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n incoming <- matrix(0, nrow = nlevels(object@idents), ncol = length(centr))\n dimnames(outgoing) <- list(levels(object@idents), names(centr))\n dimnames(incoming) <- dimnames(outgoing)\n for (i in 1:length(centr)) {\n outgoing[,i] <- centr[[i]]$outdeg\n incoming[,i] <- centr[[i]]$indeg\n }\n if (pattern == \"outgoing\") {\n mat <- t(outgoing)\n legend.name <- \"Outgoing\"\n } else if (pattern == \"incoming\") {\n mat <- t(incoming)\n legend.name <- \"Incoming\"\n } else if (pattern == \"all\") {\n mat <- t(outgoing+ incoming)\n legend.name <- \"Overall\"\n }\n if (is.null(title)) {\n title <- paste0(legend.name, \" signaling patterns\")\n } else {\n title <- paste0(paste0(legend.name, \" signaling patterns\"), \" - \",title)\n }\n\n if (!is.null(signaling)) {\n mat1 <- mat[rownames(mat) %in% signaling, , drop = FALSE]\n mat <- matrix(0, nrow = length(signaling), ncol = ncol(mat))\n idx <- match(rownames(mat1), signaling)\n mat[idx[!is.na(idx)], ] <- mat1\n dimnames(mat) <- list(signaling, colnames(mat1))\n }\n mat.ori <- mat\n mat <- sweep(mat, 1L, apply(mat, 1, max), '/', check.margin = FALSE)\n mat[mat == 0] <- NA\n\n\n if (is.null(color.use)) {\n color.use <- scPalette(length(colnames(mat)))\n }\n color.heatmap.use = grDevices::colorRampPalette((RColorBrewer::brewer.pal(n = 9, name = color.heatmap)))(100)\n\n df<- data.frame(group = colnames(mat)); rownames(df) <- colnames(mat)\n names(color.use) <- colnames(mat)\n col_annotation <- HeatmapAnnotation(df = df, col = list(group = color.use),which = \"column\",\n show_legend = FALSE, show_annotation_name = FALSE,\n simple_anno_size = grid::unit(0.2, \"cm\"))\n ha2 = HeatmapAnnotation(Strength = anno_barplot(colSums(mat.ori), border = FALSE,gp = gpar(fill = color.use, col=color.use)), show_annotation_name = FALSE)\n\n pSum <- rowSums(mat.ori)\n pSum.original <- pSum\n pSum <- -1/log(pSum)\n pSum[is.na(pSum)] <- 0\n idx1 <- which(is.infinite(pSum) | pSum < 0)\n if (length(idx1) > 0) {\n values.assign <- seq(max(pSum)*1.1, max(pSum)*1.5, length.out = length(idx1))\n position <- sort(pSum.original[idx1], index.return = TRUE)$ix\n pSum[idx1] <- values.assign[match(1:length(idx1), position)]\n }\n\n ha1 = rowAnnotation(Strength = anno_barplot(pSum, border = FALSE), show_annotation_name = FALSE)\n\n if (min(mat, na.rm = T) == max(mat, na.rm = T)) {\n legend.break <- max(mat, na.rm = T)\n } else {\n legend.break <- c(round(min(mat, na.rm = T), digits = 1), round(max(mat, na.rm = T), digits = 1))\n }\n ht1 = Heatmap(mat, col = color.heatmap.use, na_col = \"white\", name = \"Relative strength\",\n bottom_annotation = col_annotation, top_annotation = ha2, right_annotation = ha1,\n cluster_rows = cluster.rows,cluster_columns = cluster.rows,\n row_names_side = \"left\",row_names_rot = 0,row_names_gp = gpar(fontsize = font.size),column_names_gp = gpar(fontsize = font.size),\n width = unit(width, \"cm\"), height = unit(height, \"cm\"),\n column_title = title,column_title_gp = gpar(fontsize = font.size.title),column_names_rot = 90,\n heatmap_legend_param = list(title_gp = gpar(fontsize = 8, fontface = \"plain\"),title_position = \"leftcenter-rot\",\n border = NA, at = legend.break,\n legend_height = unit(20, \"mm\"),labels_gp = gpar(fontsize = 8),grid_width = unit(2, \"mm\"))\n )\n # draw(ht1)\n return(ht1)\n}\n\n\n\n#' Mapping the differential expressed genes (DEG) information onto the inferred cell-cell communications\n#'\n#' This function returns a data frame consisting of all the inferred cell-cell communications with mapped DEG information\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for extracting the DEG in `object@var.features[[features.name]]`\n#' @param variable.all variable.all = TRUE will compute the c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\") for a ligand/receptor complex using the mean value of its all subunits, that is requiring all subunits of the complex are differential expressed;\n#' variable.all = FALSE will compute the minimum value of \"pvalues\" and maximum value of c(\"logFC\", \"pct.1\", \"pct.2\") among the subunits, that is only requiring that any one of the subunits of the complex is differential expressed.\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @importFrom dplyr select\n#'\n#' @return a data frame of the inferred cell-cell communications, consisting of source, target, interaction_name, pathway_name, prob and other CellChatDB information as well as DEG information\n#'\n#' @export\n#'\nnetMappingDEG <- function(object, features.name, variable.all = TRUE, thresh = 0.05) {\n features.name <- paste0(features.name, \".info\")\n if (!(features.name %in% names(object@var.features))) {\n stop(\"The input features.name does not exist in `names(object@var.features)`. Please first run `identifyOverExpressedGenes`! \")\n }\n DEG <- object@var.features[[features.name]]\n geneInfo <- object@DB$geneInfo\n complex_input <- object@DB$complex\n\n df.net <- subsetCommunication(object, thresh = thresh)\n if (!is.data.frame(df.net)) {\n net <- data.frame()\n for (ii in 1:length(df.net)) {\n df.net[[ii]]$datasets <- names(df.net)[ii]\n net <- rbind(net, df.net[[ii]])\n }\n } else {\n net <- df.net\n }\n net$source.ligand <- paste0(net$source,\".\", net$ligand)\n net$target.receptor <- paste0(net$target,\".\", net$receptor)\n\n DEG$clusters.features <- paste0(DEG$clusters,\".\", DEG$features)\n\n net <- cbind(net, data.frame(ligand.pvalues = NA, ligand.logFC = NA, ligand.pct.1 = NA, ligand.pct.2 = NA,\n receptor.pvalues = NA, receptor.logFC = NA, receptor.pct.1 = NA, receptor.pct.2 = NA))\n # compute values for ligand\n idx1.ligand <- net$ligand %in% geneInfo$Symbol\n idx2.ligand <- which((net$ligand %in% geneInfo$Symbol) == \"FALSE\")\n idx.pos <- match(net$source.ligand, DEG$clusters.features)\n idx1.source.ligand <- which(!is.na(idx.pos))\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n idx2.source.ligand <- which(idx1.ligand & !(net$source.ligand %in% DEG$clusters.features))\n net[idx1.source.ligand, c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")] <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n\n if (length(idx2.ligand) > 0) {\n net.temp.all <- data.frame()\n for (i in 1:length(idx2.ligand)) {\n complex <- net$ligand[idx2.ligand[i]]\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n\n source.ligand.complex <- paste0(net$source[idx2.ligand[i]],\".\", complexsubunitsV)\n idx.pos <- match(source.ligand.complex, DEG$clusters.features)\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n if (length(idx1.clusters.features) > 0) {\n net.temp <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\"), drop = FALSE]\n if (variable.all == TRUE) {\n net.temp <- colMeans(net.temp, na.rm = TRUE)\n } else {\n net.temp <- c(min(net.temp$pvalues), apply(net.temp[, 2:ncol(net.temp), drop = FALSE], 2, function(x) max(x, na.rm = TRUE)))\n names(net.temp)[1] <- \"pvalues\"\n }\n net.temp <- as.data.frame(t(net.temp))\n colnames(net.temp) <- c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")\n } else {\n net.temp <- data.frame(ligand.pvalues = NA, ligand.logFC = NA, ligand.pct.1 = NA, ligand.pct.2 = NA)\n }\n net.temp.all <- rbind(net.temp.all, net.temp)\n }\n net[idx2.ligand, c(\"ligand.pvalues\", \"ligand.logFC\", \"ligand.pct.1\", \"ligand.pct.2\")] <- net.temp.all\n }\n\n # compute values for receptor\n idx1.receptor <- net$receptor %in% geneInfo$Symbol\n idx2.receptor <- which((net$receptor %in% geneInfo$Symbol) == \"FALSE\")\n idx.pos <- match(net$target.receptor, DEG$clusters.features)\n idx1.target.receptor <- which(!is.na(idx.pos))\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n net[idx1.target.receptor, c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")] <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n\n if (length(idx2.receptor) > 0) {\n net.temp.all <- data.frame()\n for (i in 1:length(idx2.receptor)) {\n complex <- net$receptor[idx2.receptor[i]]\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n\n target.receptor.complex <- paste0(net$target[idx2.receptor[i]],\".\", complexsubunitsV)\n idx.pos <- match(target.receptor.complex, DEG$clusters.features)\n idx1.clusters.features <- idx.pos[!is.na(idx.pos)]\n if (length(idx1.clusters.features) > 0) {\n net.temp <- DEG[idx1.clusters.features, c(\"pvalues\", \"logFC\", \"pct.1\", \"pct.2\")]\n if (variable.all == TRUE) {\n net.temp <- colMeans(net.temp, na.rm = TRUE)\n } else {\n net.temp <- c(min(net.temp$pvalues, na.rm = TRUE), apply(net.temp[, 2:ncol(net.temp), drop = FALSE], 2, function(x) max(x, na.rm = TRUE)))\n names(net.temp)[1] <- \"pvalues\"\n }\n net.temp <- as.data.frame(t(net.temp))\n colnames(net.temp) <- c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")\n } else {\n net.temp <- data.frame(receptor.pvalues = NA, receptor.logFC = NA, receptor.pct.1 = NA, receptor.pct.2 = NA)\n }\n net.temp.all <- rbind(net.temp.all, net.temp)\n }\n net[idx2.receptor, c(\"receptor.pvalues\", \"receptor.logFC\", \"receptor.pct.1\", \"receptor.pct.2\")] <- net.temp.all\n }\n # net <- dplyr::select[net, -c(\"source.ligand\", \"target.receptor\")]\n return(net)\n}\n\n\n#' Compute and visualize the enrichment score of ligand-receptor pairs in one condition compared to another condition\n#'\n#' @param df a dataframe\n#' @param measure compute the enrichment score in terms of \"ligand\", \"signaling\",or \"LR-pair\"\n#' @param color.use defining the color for each group of datasets\n#' @param color.name the color names in RColorBrewer::brewer.pal\n#' @param n.color the number of colors\n#' @param species define the species as one of the c('mouse','human') to extract the CellChatDB; For other species, users need to provide a ligand-receptor database `db`\n#' @param db a customized ligand-receptor database `db`\n#' @param variable.both variable.both = TRUE will require that both ligand and receptor from one pair are over-expressed;\n#' variable.both = FALSE will only require that either ligand or receptor from one pair is over-expressed.\n#' @param scale A vector of length 2 indicating the range of the size of the words.\n#' @param min.freq words with frequency below min.freq will not be plotted\n#' @param max.words Maximum number of words to be plotted. least frequent terms dropped\n#' @param random.order plot words in random order. If false, they will be plotted in decreasing frequency\n#' @param rot.per \tproportion words with 90 degree rotation\n#' @param return.data whether return the data frame for plotting wordcloud\n#' @param seed set a seed\n#' @param ... Other parameters passing to wordcloud::wordcloud\n#' @import dplyr\n#' @return A ggplot object\n#' @export\n#'\ncomputeEnrichmentScore <- function(df, measure = c(\"ligand\", \"signaling\",\"LR-pair\"), variable.both = TRUE, species = c('mouse','human'), db = NULL, color.use = NULL, color.name = \"Dark2\", n.color = 8,\n scale=c(4,.8), min.freq = 0, max.words = 200, random.order = FALSE, rot.per = 0,return.data = FALSE,seed = 1,...) {\n measure <- match.arg(measure)\n species <- match.arg(species)\n LRpairs <- as.character(unique(df$interaction_name))\n ES <- vector(length = length(LRpairs))\n for (i in 1:length(LRpairs)) {\n df.i <- subset(df, interaction_name == LRpairs[i])\n idx = which(rowSums(is.na(df.i)) > 0)\n if (variable.both & (length(idx) > 0)) {\n df.i <- df.i[-idx, ,drop = FALSE]\n }\n ES[i] = mean(abs(df.i$ligand.logFC) * abs(df.i$receptor.logFC) *abs(df.i$ligand.pct.2-df.i$ligand.pct.1)*abs(df.i$receptor.pct.2-df.i$receptor.pct.1), na.rm = TRUE)\n }\n idx.na <- which(is.na(ES))\n if (length(idx.na) > 0) {\n ES <- ES[-idx.na]\n LRpairs <- LRpairs[-idx.na]\n }\n\n if (length(ES) == 0) {\n stop(\"No enriched signaling! Please adjust the parameters for selecting differential expressed signaling!\")\n }\n if (is.null(db)) {\n if (species == \"mouse\") {\n CellChatDB <- CellChatDB.mouse\n } else if (species == 'human') {\n CellChatDB <- CellChatDB.human\n } else {\n stop(\"Only mouse and human are supported currently. Please provide a `db` instead! \")\n }\n } else {\n CellChatDB <- db\n }\n df.es <- CellChatDB$interaction[LRpairs, c(\"ligand\",'receptor','pathway_name')]\n df.es$score <- ES\n # summarize the enrichment score\n df.es.ensemble <- df.es %>% group_by(ligand) %>% summarize(total = sum(score)) # avg = mean(score),\n\n set.seed(seed)\n if (is.null(color.use)) {\n color.use <- RColorBrewer::brewer.pal(n.color, color.name)\n }\n\n wordcloud::wordcloud(words = df.es.ensemble$ligand, freq = df.es.ensemble$total, min.freq = min.freq, max.words = max.words,scale=scale,\n random.order = random.order, rot.per = rot.per, colors = color.use,...)\n if (return.data) {\n return(df.es.ensemble)\n }\n}\n\n\n#' Find the enriched signaling according to the genes (e.g.DEGs) and cell groups of interest\n#'\n#' @param object CellChat object\n#' @param features a vector giving the genes of interest\n#' @param idents a vector giving the names of cell groups of interest. If idents = NULL, it returns signaling according to the input features.\n#' @param pattern \"both\", \"outgoing\" or \"incoming\"\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @return a dataframe of the cell-cell communication associated with the input features.\n#' @export\n#' @examples\n#'\\dontrun{\n#' # find all the significant outgoing signaling according to the features and cell groups of interest\n#' df <- findEnrichedSignaling(object, features = c(\"CCL19\", \"CXCL12\"), idents = c(\"Inflam. FIB\", \"COL11A1+ FIB\"), pattern =\"outgoing\")\n#'}\nfindEnrichedSignaling <- function(object, features, idents = NULL, pattern = c(\"both\",\"outgoing\",\"incoming\"), thresh = 0.05) {\n pattern <- match.arg(pattern)\n df.net <- subsetCommunication(object, thresh = thresh)\n if (!is.null(idents)) {\n if (pattern == \"both\") {\n idx <- (df.net$source %in% idents) | (df.net$target %in% idents)\n } else if (pattern == \"outgoing\") {\n idx <- df.net$source %in% idents\n } else if (pattern == \"incoming\"){\n idx <- df.net$target %in% idents\n }\n idx.feature <- (df.net$ligand %in% features) | (df.net$receptor %in% features)\n df.net.sub <- df.net[idx & idx.feature, , drop = FALSE]\n } else {\n if (pattern == \"both\") {\n idx.feature <- (df.net$ligand %in% features) | (df.net$receptor %in% features)\n } else if (pattern == \"outgoing\") {\n idx.feature <- (df.net$ligand %in% features)\n } else if (pattern == \"incoming\"){\n idx.feature <- (df.net$receptor %in% features)\n }\n df.net.sub <- df.net[idx.feature, , drop = FALSE]\n }\n return(df.net.sub)\n}\n\n"], ["/CellChat/R/app.R", "#' Generate a Shiny App for interactive exploration of CellChat's outputs\n#'\n#' @param object CellChat object\n#' @param ... Other parameters of `shinyApp` function from shiny R package\n#' @return A Shiny app object on the basis of one CellChat object\n#' @export\n#' @importFrom stringr str_split_1\n# #' @importFrom plotly subplot plot_ly ggplotly add_markers highlight highlight_key plotlyOutput layout\n# #' @importFrom bsicons bs_icon\n#' @import shiny bslib\n#'\nrunCellChatApp <- function(object,...) {\n # ##########################################################################\n # set some global options\n # ##########################################################################\n options(stringsAsFactors = FALSE)\n\n # ##########################################################################\n # some useful elements for ui.R\n # ##########################################################################\n choices_cell_groups <-levels(object@idents)\n names(choices_cell_groups) <- levels(object@idents)\n\n choices_pathways <- object@netP$pathways\n names(choices_pathways) <- object@netP$pathways\n\n # all signaling gene names\n choices_gene_names <- CellChat::extractGene(object@DB)\n # all ligand-receptor pair names\n #choices_pairLR_use <- object@DB$interaction$interaction_name\n if (\"LRs\" %in% names(object@net)) {\n choices_pairLR_use <- object@net$LRs\n } else {\n thresh = 0.05\n prob <- object@net$prob\n prob[object@net$pval > thresh] <- 0\n LR <- dimnames(prob)[[3]]\n LR.sig <- LR[apply(prob, 3, sum) != 0]\n choices_pairLR_use <- LR.sig\n }\n\n\n # Palettes (sequential)\n choices_palettes_sequential <- stringr::str_split_1(\"Blues, BuGn, BuPu, GnBu, Greens, Greys, Oranges, OrRd, PuBu, PuBuGn, PuRd, Purples, RdPu, Reds, YlGn, YlGnBu, YlOrBr, YlOrRd\",\", \")\n names(choices_palettes_sequential) <- choices_palettes_sequential\n choices_palettes_diverging <- stringr::str_split_1(\"BrBG, PiYG, PRGn, PuOr, RdBu, RdGy, RdYlBu, RdYlGn, Spectral\",\", \")\n names(choices_palettes_diverging) <- choices_palettes_diverging\n\n # ##########################################################################\n # interactive visualization\n # ##########################################################################\n\n # interactive Heatmap\n # [Colors (ggplot2)](http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/)\n plotly_netVisual_heatmap <- function(obj_heatmap,palette.heatmap,direction.heatmap=1) {\n gg_heatmap <- obj_heatmap@matrix %>%\n as.data.frame() %>%\n mutate(row = rownames(.)) %>%\n tidyr::pivot_longer(\n data = .,\n cols = colnames(.)[-length(colnames(.))],\n names_to = \"column\",\n values_to = \"value\"\n ) %>%\n ggplot() +\n geom_tile(aes(row, column, fill = value),\n width = 0.95,\n height = 0.95) +\n # guides(fill=guide_legend(title=obj_heatmap@row_title))+\n labs(title = '',\n x = '',\n y = obj_heatmap@row_title,\n # I can't set the direction of the legend title, I thick it's a bug\n # fill = obj_heatmap@column_title,\n ) +\n scale_fill_distiller(\n palette = palette.heatmap,\n na.value = 'white',\n direction = direction.heatmap,\n ) +\n theme_minimal()+\n theme(axis.title.y = element_text(size = 14))\n\n # ggplot transpose the matrix, so we need use colSums to calc the 'rowSums'\n # of the matrix\n gg_right <- obj_heatmap@matrix %>%\n colSums(abs(.)) %>%\n tibble(row_sum = ., sources_name = names(.)) %>%\n ggplot() +\n geom_bar(aes(x = sources_name, y = row_sum, fill = sources_name),\n stat = 'identity') +\n labs(title = '',\n x = '',\n y = '',) +\n guides(fill = FALSE) +\n scale_fill_brewer(palette = \"Set1\", direction = 1) +\n theme_minimal() +\n coord_flip()\n\n gg_top <- obj_heatmap@matrix %>%\n rowSums(abs(.)) %>%\n tibble(col_sum = ., sources_name = names(.)) %>%\n ggplot() +\n # use fill to set the columns' colors\n geom_bar(aes(x = sources_name, y = col_sum, fill = sources_name),\n stat = 'identity') +\n labs(title = obj_heatmap@column_title,\n x = '',\n y = '',) +\n guides(fill = FALSE)+\n scale_fill_brewer(palette = \"Set1\", direction = 1) +\n # theme() function should be used behind the theme_*()\n theme_minimal()+\n theme(plot.title = element_text(hjust = 0.5,size = 14))\n\n return(plotly::subplot(\n gg_top,\n plotly::plotly_empty(),\n gg_heatmap,\n gg_right,\n nrows = 2,\n heights = c(0.2, 0.8),\n widths = c(0.8, 0.2),\n margin = 0,\n shareX = TRUE,\n shareY = TRUE,\n titleX = TRUE,\n titleY = TRUE\n )\n )\n }\n\n # interactive DimPlot\n plotly_DimPlot <- function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n reduction = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1)\n {\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[, group.by]\n labels <- factor(labels)\n }\n if (length(names(object@dr)) == 0) {\n stop(\"Please check `addReduction` to add a new reduced space into `object@dr`. \\n\")\n }\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please specify the dimensionality reduction to use. \\n\"))\n }\n }\n coordinates <- as.data.frame(coords)\n samples <- object@meta$samples\n if (ncol(coordinates) >= 2) {\n coordinates <- coordinates[, c(1,2)]\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n # temp_coordinates = coordinates\n # coordinates[,1] = temp_coordinates[,2]\n # coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n\n\n\n cells.level <- levels(labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n if (is.null(sources.use) & is.null(targets.use)) {\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n }\n else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use,\n \"Others\"))\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use,\n targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n # print(color.use)->return a color vector\n coordinates$cell_labels <- labels\n\n py <- plotly::highlight_key(coordinates,~cell_labels) %>%\n plotly::plot_ly(x = ~x_cent, y = ~y_cent,marker = list(size = point.size)) %>%\n plotly::add_markers(color=~cell_labels,alpha=alpha,colors=color.use) %>%\n plotly::layout(\n title = title.name,\n yaxis = list(\n title = \"\",\n #autorange = \"reversed\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n ),\n xaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n zeroline = FALSE,\n showline = FALSE\n )\n ) %>%\n plotly::highlight(on = \"plotly_click\",\n off = \"plotly_relayout\")\n\n return(py)\n }\n\n # interactive FeaturePlot\n # https://plotly.com/r/subplots/\n plotly_FeaturePlot <- function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n reduction = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE){\n if (!is.null(reduction)) {\n coords <- object@dr[[reduction]]\n } else {\n if (\"umap\" %in% names(object@dr)) {\n coords <- object@dr$umap\n } else if (\"tsne\" %in% names(object@dr)){\n coords <- object@dr$tsne\n } else {\n stop(\"Please make sure `object@dr` contains a low-dimensional space of the data and specify the dimensionality reduction to use.\")\n }\n }\n\n samples <- object@meta$samples\n cell_labels <- object@idents\n data <- as.matrix(object@data)\n meta <- object@meta\n coords <- as.data.frame(coords)\n if (ncol(coords) >= 2) {\n coords <- coords[, c(1,2)]\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n } else {\n stop(\"Please check the input 'object@dr' and make sure it has at least two columns.\")\n }\n\n # add idents info\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = -1))(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n }\n else {\n colormap <- color.heatmap\n }\n if (is.null(features) &\n is.null(signaling) & is.null(pairLR.use)) {\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)) {\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)) {\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)) {\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n df <- data.frame(x = coords[, 1], y = coords[, 2],\n cell_labels = cell_labels)\n\n\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n geneLR.return = TRUE,\n enriched.only = enriched.only,\n thresh = thresh\n )\n feature.use <- res$geneLR\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex,\n object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex,\n object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n }\n else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) >\n 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n }\n else if (length(intersect(feature.use, colnames(meta))) >\n 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[, feature.use, drop = FALSE])\n }\n else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \", cutoff, \"to the values...\",\n \"\\n\")\n data.use[data.use <= cutoff] <- 0\n }\n\n\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 0.95) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_colour_gradientn(\n colours = colormap,\n guide = guide_colorbar(\n title = NULL,\n ticks = T,\n label = T,\n barwidth = 0.5\n ),\n na.value = \"grey90\"\n ) +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + ggtitle(feature.name) +\n theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n # g <- g + coord_fixed() +\n # scale_y_reverse()\n\n gg[[i]] <- g %>% plotly::ggplotly(height = 400)\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n # print(annotations_pos)\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',annotations = annotations)\n }\n else {\n gg <- plotly::ggplotly(gg[[1]])\n }\n }\n else {\n # do.binary\n set_individual_legend <- function(plt) {\n # plt is a plotly plot obj\n plt_build <- plotly::plotly_build(plt)\n\n # get the num of traces\n len_legend <- length(plt_build$x$data)\n\n for (i in 1:len_legend) {\n # set legendgroup\n plt_build$x$data[[i]]$legendgroup <- feature.name\n # set legendtitle\n plt_build$x$data[[i]]$legendgrouptitle <- list(text=feature.name,font=list(size=12))\n }\n return(plt_build)\n }\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n enriched.only = enriched.only,\n thresh = thresh\n )\n LR.pair <- object@LR$LRsig[res$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL\n rownames(dataR) <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \")\n }\n gg <- vector(\"list\", numFeature)\n\n # set subplot title pos\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 1) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i,] > cutoff\n idx2 = dataR[i,] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\", ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i], geneR[i],\n \"Both\", \"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i], geneR[i], \"Both\",\n \"None\")\n if (length(setdiff(levels(group), unique(group))) >\n 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group),\n unique(group)))\n }\n df$feature.data <- group\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + guides(color = guide_legend(override.aes = list(size = legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n # g <- g + coord_fixed() +\n # scale_y_reverse()\n\n # cat(feature.name)\n gg[[i]] <- g %>% plotly::ggplotly(\n type = 'scatter',\n mode='markers+text',\n ) %>% set_individual_legend()\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',\n annotations = annotations,\n legend = list(tracegroupgap = 10,title=list(text=''))\n )\n }\n else {\n gg <- plotly::ggplotly(gg[[1]],\n type = 'scatter',\n mode = 'markers') %>%\n plotly::layout(legend = list(title = list(text = '')))\n }\n }\n return(gg)\n }\n\n # interactive spatialDimPlot\n plotly_spatialDimPlot <- function (object,\n color.use = NULL,\n group.by = NULL,\n sample.use = NULL,\n sources.use = NULL,\n targets.use = NULL,\n idents.use = NULL,\n alpha = 1,\n title.name = NULL,\n point.size = 1)\n {\n if (is.null(group.by)) {\n labels <- object@idents\n } else {\n labels = object@meta[, group.by]\n labels <- factor(labels)\n }\n\n coordinates <- as.data.frame(object@images$coordinates)\n samples <- object@meta$samples\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coordinates = coordinates[samples == sample.use, ]\n labels = labels[samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coordinates = coordinates\n coordinates[,1] = temp_coordinates[,2]\n coordinates[,2] = temp_coordinates[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n\n\n cells.level <- levels(labels)\n if (!is.null(idents.use)) {\n if (is.numeric(idents.use)) {\n idents.use <- cells.level[idents.use]\n }\n cell.use <- !(labels %in% idents.use)\n labels[cell.use] <- NA\n cells.level <- cells.level[cells.level %in% idents.use]\n labels <- factor(labels, levels = cells.level)\n }\n if (is.null(sources.use) & is.null(targets.use)) {\n if (is.null(color.use)) {\n color.use <- scPalette(nlevels(labels))\n }\n }\n else {\n if (is.numeric(sources.use)) {\n sources.use <- cells.level[sources.use]\n }\n if (is.numeric(targets.use)) {\n targets.use <- cells.level[targets.use]\n }\n group <- rep(\"Others\", length(labels))\n group[(labels %in% sources.use)] <- sources.use\n group[(labels %in% targets.use)] <- targets.use\n group = factor(group, levels = c(sources.use, targets.use,\n \"Others\"))\n if (is.null(color.use)) {\n color.use.all <- scPalette(nlevels(labels))\n color.use <- color.use.all[match(c(sources.use,\n targets.use), levels(labels))]\n color.use[nlevels(group)] <- \"grey90\"\n }\n labels <- group\n }\n # print(color.use)->return a color vector\n coordinates$cell_labels <- labels\n\n py <- plotly::highlight_key(coordinates,~cell_labels) %>%\n plotly::plot_ly(x = ~x_cent, y = ~y_cent,marker = list(size = point.size)) %>%\n plotly::add_markers(color=~cell_labels,alpha=alpha,colors=color.use) %>%\n plotly::layout(\n title = title.name,\n yaxis = list(\n autorange = \"reversed\",\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n showline = FALSE\n ),\n xaxis = list(\n title = \"\",\n showgrid = FALSE,\n ticks = \"\",\n # ticktext = \"\",\n tickvals = \"\",\n showline = FALSE\n )\n ) %>%\n plotly::highlight(on = \"plotly_click\",\n off = \"plotly_relayout\")\n\n return(py)\n }\n\n # interactive spatialFeaturePlot\n # https://plotly.com/r/subplots/\n plotly_spatialFeaturePlot <- function (object,\n features = NULL,\n signaling = NULL,\n pairLR.use = NULL,\n sample.use = NULL,\n enriched.only = TRUE,\n thresh = 0.05,\n do.group = TRUE,\n color.heatmap = \"Reds\",\n n.colors = 8,\n direction = -1,\n do.binary = FALSE,\n cutoff = NULL,\n color.use = NULL,\n alpha = 1,\n point.size = 0.8,\n legend.size = 3,\n legend.text.size = 8,\n shape.by = 16,\n plot_nrows = 1,\n show.legend = TRUE,\n show.legend.combined = FALSE){\n coords <- as.data.frame(object@images$coordinates)\n samples <- object@meta$samples\n cell_labels <- object@idents\n data <- as.matrix(object@data)\n meta <- object@meta\n\n if (ncol(coords) == 2) {\n colnames(coords) <- c(\"x_cent\",\"y_cent\")\n if (length(unique(samples)) > 1) {\n if (is.null(sample.use)) {\n stop(\"`sample.use` should be provided for visualizing signaling on each individual sample.\")\n } else if (sample.use %in% unique(samples)) {\n coords = coords[samples == sample.use, ]\n meta = meta[samples == sample.use, ]\n data = data[, samples == sample.use]\n } else {\n stop(\"Please check the input `sample.use`, which should be the element in `meta$samples`.\")\n }\n }\n temp_coords = coords\n coords[,1] = temp_coords[,2]\n coords[,2] = temp_coords[,1]\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n # add idents info\n\n if (length(color.heatmap) == 1) {\n colormap <- tryCatch({\n RColorBrewer::brewer.pal(n = n.colors, name = color.heatmap)\n }, error = function(e) {\n (scales::viridis_pal(option = color.heatmap, direction = -1))(n.colors)\n })\n if (direction == -1) {\n colormap <- rev(colormap)\n }\n colormap <- colorRampPalette(colormap)(99)\n colormap[1] <- \"#E5E5E5\"\n }\n else {\n colormap <- color.heatmap\n }\n if (is.null(features) &\n is.null(signaling) & is.null(pairLR.use)) {\n stop(\"Please input either features, signaling or pairLR.use.\")\n }\n if (!is.null(features) & !is.null(signaling)) {\n stop(\"Please don't input features or signaling simultaneously.\")\n }\n if (!is.null(features) & !is.null(pairLR.use)) {\n stop(\"Please don't input features or pairLR.use simultaneously.\")\n }\n if (!is.null(signaling) & !is.null(pairLR.use)) {\n stop(\"Please don't input signaling or pairLR.use simultaneously.\")\n }\n df <- data.frame(x = coords[, 1], y = coords[, 2],\n cell_labels = cell_labels)\n\n\n if (!do.binary) {\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n geneLR.return = TRUE,\n enriched.only = enriched.only,\n thresh = thresh\n )\n feature.use <- res$geneLR\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n geneL <- unique(LR.pair$ligand)\n geneR <- unique(LR.pair$receptor)\n geneL <- extractGeneSubset(geneL, object@DB$complex,\n object@DB$geneInfo)\n geneR <- extractGeneSubset(geneR, object@DB$complex,\n object@DB$geneInfo)\n feature.use <- c(geneL, geneR)\n }\n else {\n feature.use <- features\n }\n if (length(intersect(feature.use, rownames(data))) >\n 0) {\n feature.use <- feature.use[feature.use %in% rownames(data)]\n data.use <- data[feature.use, , drop = FALSE]\n }\n else if (length(intersect(feature.use, colnames(meta))) >\n 0) {\n feature.use <- feature.use[feature.use %in% colnames(meta)]\n data.use <- t(meta[, feature.use, drop = FALSE])\n }\n else {\n stop(\"Please check your input! \")\n }\n if (!is.null(cutoff)) {\n cat(\"Applying a cutoff of \", cutoff, \"to the values...\",\n \"\\n\")\n data.use[data.use <= cutoff] <- 0\n }\n\n\n numFeature = length(feature.use)\n gg <- vector(\"list\", numFeature)\n\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 0.95) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n df$feature.data <- data.use[i,]\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_colour_gradientn(\n colours = colormap,\n guide = guide_colorbar(\n title = NULL,\n ticks = T,\n label = T,\n barwidth = 0.5\n ),\n na.value = \"grey90\"\n ) +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + ggtitle(feature.name) +\n theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n g <- g + coord_fixed() +\n scale_y_reverse()\n\n gg[[i]] <- g %>% plotly::ggplotly(height = 400)\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n # print(annotations_pos)\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',annotations = annotations)\n }\n else {\n gg <- plotly::ggplotly(gg[[1]])\n }\n }\n else {\n # do.binary\n set_individual_legend <- function(plt) {\n # plt is a plotly plot obj\n plt_build <- plotly::plotly_build(plt)\n\n # get the num of traces\n len_legend <- length(plt_build$x$data)\n\n for (i in 1:len_legend) {\n # set legendgroup\n plt_build$x$data[[i]]$legendgroup <- feature.name\n # set legendtitle\n plt_build$x$data[[i]]$legendgrouptitle <- list(text=feature.name,font=list(size=12))\n }\n return(plt_build)\n }\n if (is.null(color.use)) {\n color.use <- ggPalette(4)\n color.use[4] <- \"grey90\"\n }\n color.use1 = color.use\n if (!is.null(signaling)) {\n res <- extractEnrichedLR(\n object,\n signaling = signaling,\n enriched.only = enriched.only,\n thresh = thresh\n )\n LR.pair <- object@LR$LRsig[res$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else if (!is.null(pairLR.use)) {\n if (is.character(pairLR.use)) {\n pairLR.use <- data.frame(interaction_name = pairLR.use)\n }\n if (enriched.only) {\n if (do.group) {\n object@net$prob[object@net$pval > thresh] <- 0\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob)[[3]]]\n prob <- object@net$prob[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n else {\n pairLR.use.name <-\n pairLR.use$interaction_name[pairLR.use$interaction_name %in%\n dimnames(object@net$prob.cell)[[3]]]\n prob.cell <- object@net$prob.cell[, , pairLR.use.name,\n drop = FALSE]\n prob.sum <- apply(prob.cell > 0, 3, sum)\n names(prob.sum) <- pairLR.use.name\n signaling.includes <- names(prob.sum)[prob.sum >\n 0]\n pairLR.use <- pairLR.use[pairLR.use$interaction_name %in%\n signaling.includes, , drop = FALSE]\n }\n if (length(pairLR.use$interaction_name) == 0) {\n stop(\n paste0(\n \"There is no significant communication related with the input `pairLR.use`. Set `enriched.only = FALSE` to show non-significant signaling.\"\n )\n )\n }\n }\n LR.pair <- object@LR$LRsig[pairLR.use$interaction_name,\n c(\"ligand\", \"receptor\")]\n }\n else {\n stop(\"Please input either `pairLR.use` or `signaling` for `binary` mode!\")\n }\n geneL <- as.character(LR.pair$ligand)\n geneR <- as.character(LR.pair$receptor)\n complex_input <- object@DB$complex\n dataL <- computeExpr_LR(geneL, data, complex_input)\n dataR <- computeExpr_LR(geneR, data, complex_input)\n rownames(dataL) <- geneL\n rownames(dataR) <- geneR\n\n feature.use <- rownames(LR.pair)\n numFeature = nrow(LR.pair)\n\n if (is.null(cutoff)) {\n stop(\"A `cutoff` must be provided when plotting expression in binary mode! \")\n }\n gg <- vector(\"list\", numFeature)\n\n # set subplot title pos\n plot_ncols <- ceiling(numFeature / plot_nrows)\n plot_width <- 1 / plot_ncols\n plot_height <- 1 / plot_nrows\n annotations_pos <- vector(\"list\", 0)\n for (i in 1:plot_nrows) {\n for (j in 1:plot_ncols) {\n x <- (j - 0.5) * plot_width\n y <- 1-(i - 1) * plot_height\n annotations_pos[[length(annotations_pos)+1]] <- list(\n x=x,\n y=y\n )\n }\n\n }\n annotations <- vector(\"list\", numFeature)\n\n for (i in seq_len(numFeature)) {\n feature.name <- feature.use[i]\n idx1 = dataL[i,] > cutoff\n idx2 = dataR[i,] > cutoff\n idx3 = idx1 & idx2\n group = rep(\"None\", ncol(dataL))\n group[idx1] = geneL[i]\n group[idx2] = geneR[i]\n group[idx3] = \"Both\"\n group = factor(group, levels = c(geneL[i], geneR[i],\n \"Both\", \"None\"))\n color.use <- color.use1\n names(color.use) <- c(geneL[i], geneR[i], \"Both\",\n \"None\")\n if (length(setdiff(levels(group), unique(group))) >\n 0) {\n color.use <- color.use[names(color.use) %in% unique(group)]\n group = droplevels(group, exclude = setdiff(levels(group),\n unique(group)))\n }\n df$feature.data <- group\n g <-\n ggplot(data = df, aes(x, y)) + geom_point(\n aes(colour = feature.data,cell_labels=cell_labels),\n alpha = alpha,\n size = point.size,\n shape = shape.by\n ) +\n scale_color_manual(values = color.use, na.value = \"grey90\") +\n theme(legend.position = \"right\") + theme(\n legend.title = element_blank(),\n legend.text = element_text(size = legend.text.size),\n legend.key.size = unit(0.15, \"inches\")\n ) + guides(color = guide_legend(override.aes = list(size = legend.size))) +\n ggtitle(feature.name) + theme(plot.title = element_text(\n hjust = 0.5,\n vjust = 0,\n size = 10\n )) + theme(\n panel.background = element_blank(),\n axis.ticks = element_blank(),\n axis.text = element_blank()\n ) +\n xlab(NULL) + ylab(NULL) + theme(legend.key = element_blank())\n g <- g + coord_fixed() +\n scale_y_reverse()\n\n # cat(feature.name)\n gg[[i]] <- g %>% plotly::ggplotly(\n type = 'scatter',\n mode='markers+text',\n ) %>% set_individual_legend()\n\n annotations[[i]] <- list(\n x=annotations_pos[[i]]$x,\n y=annotations_pos[[i]]$y,\n text = feature.name,\n xref = \"paper\",\n yref = \"paper\",\n xanchor = \"center\",\n yanchor = \"top\",\n showarrow = FALSE,\n font = list(size = 16))\n }\n\n if (numFeature > 1) {\n gg <- plotly::subplot(gg, nrows = plot_nrows,margin = 0.02,shareX = FALSE,shareY = FALSE) %>%\n plotly::layout(title = '',\n annotations = annotations,\n legend = list(tracegroupgap = 10,title=list(text=''))\n )\n }\n else {\n gg <- plotly::ggplotly(gg[[1]],\n type = 'scatter',\n mode = 'markers') %>%\n plotly::layout(legend = list(title = list(text = '')))\n }\n }\n return(gg)\n }\n\n\n\n # ##########################################################################\n # Shiny App's UI\n # ##########################################################################\n ui <- fluidPage(\n theme = bslib::bs_theme(version = 5),\n # ##########################################################################\n # meta info of the HTML pages\n # ##########################################################################\n tags$head(\n # title\n tags$title(\"Interactive CellChat Explorer\"),\n # icon\n tags$link(rel = \"shortcut icon\", type = \"image/x-icon\", href = \"favicon.ico\"),\n tags$link(rel=\"stylesheet\",href=\"https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css\"),\n ),\n tags$body(\n # ##########################################################################\n # logo and title of the website\n # ##########################################################################\n tags$nav(class=\"navbar navbar-light bg-light\",\n div(class=\"container-fluid justify-content-center\",\n tags$a(\n class=\"navbar-brand\",href=\"http://www.cellchat.org/\",\n img(src=\"https://s2.loli.net/2023/08/08/2qjSoRACDtHByOY.png\",class=\"d-inline\",alt=\"\",height=\"30\"),\n tags$p(\"Interactive CellChat Explorer\",class=\"fs-1 d-inline\")\n )\n\n )),\n # ##########################################################################\n # 1.Basic exploration of spatial-resolved gene expression\n # ##########################################################################\n\n # Visualize cell groups and signaling expression\n h3(tags$i(class=\"bi bi-1-square-fill\"),\n \"Visualize cell groups and signaling expression\",class=\"h3\"),\n bslib::card(\n bslib::card_header(\n h6(tags$i(class=\"bi bi-bookmark\"),\n \"Dim Plot\",class=\"h6\")),\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n sliderInput(\n \"dimplot_point_size\",\n label = \"Point size\",\n min = 3,\n max = 8,\n step = 0.5,\n value = 3\n ),\n sliderInput(\n \"dimplot_alpha\",\n label = \"Alpha\",\n min = 0,\n max = 1,\n step = 0.2,\n value = 1\n ),\n )\n ),\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"DimPlot\",\n width = 664,height = 498)\n )\n\n ),\n\n ),\n\n # gene expression distribution\n # https://shiny.posit.co/r/gallery/widgets/datatables-options/\n # https://shiny.posit.co/r/gallery/widgets/selectize-examples/\n navset_card_tab(\n title = h6(tags$i(class=\"bi bi-bookmark-dash\"),\n \"Feature Plot\",class=\"h6\"),\n sidebar = NULL,\n # content\n nav_panel(\n title = \"use gene names\",\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectizeInput(\n inputId = 'selectize_gene_names',\n label = 'Gene Names',\n choices = NULL,\n multiple = TRUE,\n # options = list(maxItems = 4)\n ),\n numericInput(\n \"nrows_feature_plot1\",\n label = \"nrows\",\n min = 1,\n step = 1,\n value = 1,\n ),\n ),\n\n accordion_panel(\n title = \"Color\",\n icon = tags$i(class=\"bi bi-palette-fill\"),\n selectInput(\n \"direction_feature_plot1\",\n label = \"direction\",\n choices = list(\"1\"=1,\"-1\"=-1),\n selected = 1,\n multiple = F\n ),\n selectInput(\n \"palette_feature_plot1\",\n label = \"palette\",\n choices = c(choices_palettes_diverging,choices_palettes_sequential),\n selected = \"Reds\",\n multiple = F\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n numericInput(\n \"cut.off_feature_plot1\",\n label = \"cut.off\",\n min = 0,\n step = 0.1,\n value = 0,\n ),\n sliderInput(\n \"point.size_feature_plot1\",\n label = \"point.size\",\n min = 0,\n max = 2,\n step = 0.1,\n value = 0.4\n )\n )\n\n ),\n # nav content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"gene_expression_distribution\",width = 664,height = 498),\n ),\n )\n ),\n nav_panel(\n title = \"use L-R pairs\",\n layout_sidebar(\n sidebar = accordion(\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectizeInput(\n inputId = 'selectize_pairLR_use',\n label = 'pairLR_use',\n choices = NULL,\n multiple = T\n ),\n numericInput(\n \"nrows_feature_plot2\",\n label = \"nrows\",\n min = 1,\n step = 1,\n value = 1,\n ),\n checkboxInput(\n \"do.binary_feature_plot\",\n label = \"do.binary\",\n value = TRUE),\n ),\n accordion_panel(\n title = \"Color\",\n icon = tags$i(class=\"bi bi-palette-fill\"),\n selectInput(\n \"direction_feature_plot2\",\n label = \"direction\",\n choices = list(\"1\"=1,\"-1\"=-1),\n selected = 1,\n multiple = F\n ),\n selectInput(\n \"palette_feature_plot2\",\n label = \"palette\",\n choices = c(choices_palettes_diverging,choices_palettes_sequential),\n selected = \"Reds\",\n multiple = F\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n numericInput(\n \"cut.off_feature_plot2\",\n label = \"cut.off\",\n min = 0,\n step = 0.1,\n value = 0,\n ),\n sliderInput(\n \"point.size_feature_plot2\",\n label = \"point.size\",\n min = 0,\n max = 2,\n step = 0.1,\n value = 0.4\n )\n )\n ),\n # nav content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"gene_expression_distribution2\",width = 664,height = 498)\n )\n ),\n )\n ),\n\n # ##########################################################################\n # 2.Examine signaling between cell groups\n # ##########################################################################\n h2(tags$i(class=\"bi bi-2-square-fill\"),\n \"Examine signaling between cell groups\"),\n navset_card_tab(\n title = NULL,\n sidebar = NULL,\n nav_panel(\"Heatmap\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"The number of interactions/interaction strength between any two cell groups\",\n class=\"h6\"),\n hr(),\n\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"measure_heatmap\",\n label = \"measurement\",\n choices = list(\"count\" = \"count\", \"weight\" = \"weight\"),\n selected = \"count\"\n ),\n selectInput(\n \"palette_heatmap\",\n label = \"palette (sequential)\",\n choices = choices_palettes_sequential,\n selected = \"Blues\"\n ),\n # Sets the order of colours in the scale. If 1, the default, colours are as output by RColorBrewer::brewer.pal(). If -1, the order of colours is reversed.\n selectInput(\n \"direction_heatmap\",\n label = \"direction\",\n choices = list(\n \"1\"=1,\n \"-1\"=-1\n ),\n selected = 1,\n )\n\n # refer to: https://ggplot2.tidyverse.org/reference/scale_brewer.html\n ),\n ),\n\n # content\n div(class=\"d-flex justify-content-center\",\n plotly::plotlyOutput(outputId = \"netVisual_heatmap\",width = 664,height = 498)\n )\n )\n ),\n\n # the enriched signaling among one selected pair of cell groups\n nav_panel(\"rankNet\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"The enriched signaling\",\n class=\"h6\"),\n hr(),\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"select1_cell_group\",\n label = \"cell groups for sources.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[1],\n multiple = TRUE\n ),\n selectInput(\n \"select2_cell_group\",\n label = \"cell groups for targets.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[2],\n multiple = TRUE\n ),\n\n # selectInput(\n # \"measure_ranknet\",\n # label = \"measurement\",\n # choices = list(\"count\" = \"count\", \"weight\" = \"weight\"),\n # selected = \"count\"\n # ),\n selectInput(\n \"slot.name_ranknet\",\n label = \"slot.name\",\n choices = list(\"net\" = \"net\", \"netP\" = \"netP\"),\n selected = \"netP\"\n ),\n # selectInput(\n # \"palette_ranknet\",\n # label = \"palette (sequential)\",\n # choices = choices_palettes_sequential,\n # selected = \"Blues\"\n # ),\n ),\n ),\n\n # content\n plotly::plotlyOutput(outputId = \"rankNet\")\n )\n ),\n nav_panel(\"Contribution Plot\",\n layout_sidebar(\n sidebar = accordion(\n h6(\"Contribution of each L-R pair to overall signaling\",\n class = \"h6\"),\n hr(),\n accordion_panel(\n \"Select\",\n icon = bsicons::bs_icon(\"menu-app\"),\n selectInput(\n \"pathway_contribution_plot\",\n label = \"a pathway to show\",\n choices = choices_pathways,\n selected = choices_pathways[1]\n ),\n selectInput(\n \"select3_cell_group\",\n label = \"a cell group for sources.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[1]\n ),\n selectInput(\n \"select4_cell_group\",\n label = \"a cell group for targets.use\",\n choices = choices_cell_groups,\n selected = choices_cell_groups[2]\n ),\n ),\n\n accordion_panel(\n title = \"Numerical\",\n icon = bsicons::bs_icon(\"sliders\"),\n sliderInput(\n \"font.size_contribution_plot\",\n label = \"font.size\",\n min = 10,\n max=30,\n step = 5,\n value = 20\n )\n )\n ),\n\n # content\n plotOutput(outputId = \"netAnalysis_contribution\"),\n )\n ),\n ),\n\n # Contribution of each L-R pair to overall signaling\n # width = 3.2inch, height = 1.5inch,\n # height might change dependent on dataset\n\n ## Examine individual signaling pathway\n ## (the following four plots will be appeared based on user's input)\n h2(tags$i(class=\"bi bi-3-square-fill\"),\n \"Examine individual signaling pathway\"),\n navset_card_tab(\n title = h6(\"Plots\",class=\"h6\"),\n sidebar = accordion(\n selectizeInput(\n inputId = 'selectize_pathway',\n label = 'Select a pathway to show',\n choices = NULL,\n multiple = FALSE\n ),\n hr(),\n accordion_panel(\n title = \"Circle plot\",\n icon = tags$i(class=\"bi bi-circle-fill\"),\n # edge.width.max = 5, vertex.size.max = 12, vertex.label.cex = 0.8\n sliderInput(\n \"slider_Circle_plot_edge.width.max\",\n label = \"edge.width.max\",\n min = 5,\n max = 15,\n value = 8,\n step = 1\n ),\n sliderInput(\n \"slider_Circle_plot_vertex.size.max\",\n label = \"vertex.size.max\",\n min = 8,\n max = 16,\n value = 12,\n step = 2),\n sliderInput(\n \"slider_Circle_plot_vertex.label.cex\",\n label = \"vertex.label.cex\",\n min = 1,\n max = 2,\n value = 1,\n step = 0.2\n ),\n ),\n accordion_panel(\n title = \"Spatial plot\",\n icon = tags$i(class=\"bi bi-layers-half\"),\n # edge.width.max = 5, vertex.size.max = 1,\n # point.size = 2.5,\n # alpha.image = 0.2, vertex.label.cex = 5\n sliderInput(\n \"slider_Spatial_plot_edge.width.max\",\n label = \"edge.width.max\",\n min = 2,\n max = 8,\n value = 5,\n step = 1\n ),\n sliderInput(\n \"slider_Spatial_plot_vertex.size.max\",\n label = \"vertex.size.max\",\n min = 2,\n max = 8,\n value = 5,\n step = 1),\n sliderInput(\n \"slider_Spatial_plot_vertex.label.cex\",\n label = \"vertex.label.cex\",\n min = 5,\n max = 10,\n value = 8,\n step = 1\n ),\n\n sliderInput(\n \"slider_Spatial_plot_point.size\",\n label = \"point.size\",\n min = 1,\n max = 3,\n value = 2.4,\n step = 0.2\n ),\n sliderInput(\n \"slider_Spatial_plot_alpha.image\",\n label = \"alpha.image\",\n min = 0,\n max = 1,\n value = 0.2,\n step = 0.05\n ),\n ),\n accordion_panel(\n title = \"Contribution of each L-R pair\",\n icon = tags$i(class=\"bi bi-bar-chart-fill\"),\n ),\n ),\n\n # nav tab\n nav_panel(\n title = \"Circle plot\",\n div(class=\"d-flex justify-content-center\",\n plotOutput(outputId = \"Circle_plot\",\n height = \"780px\",width = \"580px\")\n )\n ),\n nav_panel(\n title = \"Spatial plot\",\n div(class=\"d-flex justify-content-center\",\n plotOutput(outputId = \"Spatial_plot\",\n height = \"780px\",width = \"580px\")\n )\n ),\n nav_panel(\n title = \"Contribution of each L-R pair\",\n plotly::plotlyOutput(outputId = \"LR_pair_contribution\",\n height = \"900px\")\n ),\n\n ),\n # body\n\n ),\n # page\n )\n # ##########################################################################\n # Shiny App's Server\n # ##########################################################################\n server <- function(input, output, session) {\n ############################################################################\n if (object@options$datatype == \"RNA\") {\n output$DimPlot <- plotly::renderPlotly({\n plotly_DimPlot(\n object,\n point.size = input$dimplot_point_size,\n alpha = input$dimplot_alpha,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"DimPlot\",\n width = 800,\n height = 600\n ))\n })\n } else {\n output$spatialDimPlot <- plotly::renderPlotly({\n plotly_spatialDimPlot(\n object,\n point.size = input$dimplot_point_size,\n alpha = input$dimplot_alpha,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialDimPlot\",\n width = 800,\n height = 600\n ))\n })\n }\n\n\n observe({\n updateSelectizeInput(\n session,\n \"selectize_gene_names\",\n # selected = c(\"Wnt10a\", \"Fzd1\", \"Lrp6\"),\n selected = choices_gene_names[1:2],\n # selected = c(\"Wnt10a\", \"Fzd1\", \"Lrp6\",\"Ror2\",\n # \"Nrp1\",\"Nrp2\",\"Bmpr2\",\"Ret\"),\n choices = choices_gene_names,\n server = TRUE\n )\n })\n # output$out6 <- renderPrint(input$selectize_gene_names)\n\n if (object@options$datatype == \"RNA\") {\n output$gene_expression_distribution <- plotly::renderPlotly(plotly_FeaturePlot(\n object,\n features = input$selectize_gene_names,\n plot_nrows = input$nrows_feature_plot1,\n point.size = input$point.size_feature_plot1,\n cutoff = input$cut.off_feature_plot1,\n color.heatmap = input$palette_feature_plot1,\n direction = input$direction_feature_plot1,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"FeaturePlot (use gene names)\",\n width = 600,\n height = 600\n ))\n )\n } else {\n output$gene_expression_distribution <- plotly::renderPlotly(plotly_spatialFeaturePlot(\n object,\n features = input$selectize_gene_names,\n plot_nrows = input$nrows_feature_plot1,\n point.size = input$point.size_feature_plot1,\n cutoff = input$cut.off_feature_plot1,\n color.heatmap = input$palette_feature_plot1,\n direction = input$direction_feature_plot1,\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialFeaturePlot (use gene names)\",\n width = 600,\n height = 600\n ))\n )\n }\n\n\n observe({\n updateSelectizeInput(\n session,\n \"selectize_pairLR_use\",\n selected = choices_pairLR_use[1],\n # selected = c(\"WNT10A_FZD1_LRP6\",\"WNT10A_FZD10_LRP6\",\"BMP2_BMPR1A_ACVR2A\"),\n choices = choices_pairLR_use,\n server = TRUE\n )\n })\n # output$out7 <- renderPrint(input$selectize_pairLR_use)\n if (object@options$datatype == \"RNA\") {\n output$gene_expression_distribution2 <- plotly::renderPlotly({\n plotly_FeaturePlot(\n object,\n pairLR.use = input$selectize_pairLR_use,\n point.size = input$point.size_feature_plot2,\n do.binary = input$do.binary_feature_plot,\n cutoff = input$cut.off_feature_plot2,\n enriched.only = F,\n color.heatmap = input$palette_feature_plot2,\n direction = input$direction_feature_plot2,\n plot_nrows = as.numeric(input$nrows_feature_plot2)\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"FeaturePlot(use pairLRs)\",\n width = 600,\n height = 600\n ))\n })\n } else {\n output$gene_expression_distribution2 <- plotly::renderPlotly({\n plotly_spatialFeaturePlot(\n object,\n pairLR.use = input$selectize_pairLR_use,\n point.size = input$point.size_feature_plot2,\n do.binary = input$do.binary_feature_plot,\n cutoff = input$cut.off_feature_plot2,\n enriched.only = F,\n color.heatmap = input$palette_feature_plot2,\n direction = input$direction_feature_plot2,\n plot_nrows = as.numeric(input$nrows_feature_plot2)\n ) %>%\n plotly::config(toImageButtonOptions = list(\n format = \"svg\",\n filename = \"spatialFeaturePlot(use pairLRs)\",\n width = 600,\n height = 600\n ))\n })\n }\n\n\n ############################################################################\n output$netVisual_heatmap <- plotly::renderPlotly({\n suppressWarnings({\n netVisual_heatmap(object,\n measure = input$measure_heatmap,\n ) %>%\n plotly_netVisual_heatmap(\n palette.heatmap = input$palette_heatmap,\n direction.heatmap = input$direction_heatmap)\n })\n })\n\n output$rankNet <- plotly::renderPlotly({\n rankNet(\n object,\n mode = \"single\",\n measure = \"weight\",\n sources.use = input$select1_cell_group,\n targets.use = input$select2_cell_group,\n slot.name = input$slot.name_ranknet\n ) %>%\n plotly::ggplotly()\n })\n\n output$netAnalysis_contribution <- renderPlot({\n netAnalysis_contribution(\n object,\n signaling = input$pathway_contribution_plot,\n sources.use = input$select3_cell_group,\n targets.use = input$select4_cell_group,\n font.size = input$font.size_contribution_plot,\n font.size.title = input$font.size_contribution_plot,\n )\n },res = 96)\n ############################################################################\n observe({\n updateSelectizeInput(\n session,\n \"selectize_pathway\",\n selected = choices_pathways[1],\n choices = choices_pathways,\n server = TRUE\n )\n })\n output$Circle_plot <- renderPlot({\n netVisual_aggregate(\n object,\n signaling = input$selectize_pathway,\n layout = \"circle\",\n edge.width.max = input$slider_Circle_plot_edge.width.max,\n vertex.size.max = input$slider_Circle_plot_vertex.size.max,\n vertex.label.cex = input$slider_Circle_plot_vertex.label.cex\n )\n },res = 96)\n output$Spatial_plot <- renderPlot({\n netVisual_aggregate(\n object,\n signaling = input$selectize_pathway,\n layout = \"spatial\",\n edge.width.max = input$slider_Spatial_plot_edge.width.max,\n vertex.size.max = input$slider_Spatial_plot_vertex.size.max,\n vertex.label.cex = input$slider_Spatial_plot_vertex.label.cex,\n alpha.image = input$slider_Spatial_plot_alpha.image,\n point.size = input$slider_Spatial_plot_point.size,\n )\n })\n output$LR_pair_contribution <- plotly::renderPlotly({\n netAnalysis_contribution(\n object,\n signaling = input$selectize_pathway,\n font.size = 12,\n font.size.title = 14\n )\n })\n ############################################################################\n }\n\n\n # Running a Shiny app\n shinyApp(ui = ui, server = server,...)\n}\n"], ["/CellChat/R/utilities.R", "#' Normalize data using a scaling factor\n#'\n#' @param data.raw input raw data\n#' @param scale.factor the scaling factor used for each cell\n#' @param do.log whether to do log transformation with pseudocount 1\n#' @param do.sparse whether to use sparse format\n#' @export\n#'\nnormalizeData <- function(data.raw, scale.factor = 10000, do.log = TRUE, do.sparse = TRUE) {\n # Scale counts within a sample\n library.size <- Matrix::colSums(data.raw)\n #scale.factor <- median(library.size)\n expr <- Matrix::t(Matrix::t(data.raw) / library.size) * scale.factor\n if (do.log) {\n data.norm <-log1p(expr)\n }\n if (do.sparse) {\n data.input <- as(data.norm, \"dgCMatrix\")\n }\n return(data.norm)\n}\n\n\n#' Scale the data\n#'\n#' @param data.use input data\n#' @param do.center whether center the values\n#' @export\n#'\nscaleData <- function(data.use, do.center = T) {\n data.use <- Matrix::t(scale(Matrix::t(data.use), center = do.center, scale = TRUE))\n return(data.use)\n}\n\n\n#' Scale a data matrix\n#'\n#' @param x data matrix\n#' @param scale the method to scale the data\n#' @param na.rm whether remove na\n#' @importFrom Matrix rowMeans colMeans rowSums colSums\n#' @return\n#' @export\n#'\n#' @examples\nscaleMat <- function(x, scale, na.rm=TRUE){\n\n av <- c(\"none\", \"row\", \"column\", 'r1', 'c1')\n i <- pmatch(scale, av)\n if(is.na(i) )\n stop(\"scale argument shoud take values: 'none', 'row' or 'column'\")\n scale <- av[i]\n\n switch(scale, none = x\n , row = {\n x <- sweep(x, 1L, rowMeans(x, na.rm = na.rm), '-',check.margin = FALSE)\n sx <- apply(x, 1L, sd, na.rm = na.rm)\n sweep(x, 1L, sx, \"/\", check.margin = FALSE)\n }\n , column = {\n x <- sweep(x, 2L, colMeans(x, na.rm = na.rm), '-',check.margin = FALSE)\n sx <- apply(x, 2L, sd, na.rm = na.rm)\n sweep(x, 2L, sx, \"/\", check.margin = FALSE)\n }\n , r1 = sweep(x, 1L, rowSums(x, na.rm = na.rm), '/', check.margin = FALSE)\n , c1 = sweep(x, 2L, colSums(x, na.rm = na.rm), '/', check.margin = FALSE)\n )\n}\n\n#' Downsampling single cell data using geometric sketching algorithm\n#'\n#' USERs need to install the python package `pip install geosketch` (https://github.com/brianhie/geosketch)\n#'\n#' @param object A data matrix (should have row names; samples in rows, features in columns) or a Seurat object.\n#'\n#' When object is a PCA or UMAP space, please set `do.PCA = FALSE`\n#'\n#' When object is a data matrix (cells in rows and genes in columns), it is better to use the highly variable genes. PCA will be done on this input data matrix.\n#' @param percent the percent of data to sketch\n#' @param idents A vector of identity classes to keep for sketching\n#' @param do.PCA whether doing PCA on the input data\n#' @param dimPC the number of components to use\n#' @importFrom reticulate import\n#' @return A vector of cell names to use for downsampling\n#' @export\n#'\nsketchData <- function(object, percent, idents = NULL, do.PCA = TRUE, dimPC = 30) {\n # pip install geosketch\n geosketch <- reticulate::import('geosketch')\n if (is(object,\"Seurat\")) {\n sketch.size <- as.integer(percent*ncol(object))\n if (!is.null(idents)) {\n object <- subset(object, idents = idents)\n }\n object <- object %>% #Seurat::NormalizeData(verbose = FALSE) %>%\n FindVariableFeatures(selection.method = \"vst\", nfeatures = 2000) %>%\n RunPCA(pc.genes = object@var.genes, npcs = dimPC, verbose = FALSE)\n\n X.pcs <- object@reductions$pca@cell.embeddings\n cells.all <- Cells(object)\n\n } else {\n # Get top PCs\n if (do.PCA) {\n X.pcs <- runPCA(object, dimPC = dimPC)\n } else {\n X.pcs <- object\n }\n\n # Sketch percent of data.\n sketch.size <- as.integer(percent*nrow(X))\n cells.all <- rownames(object)\n }\n sketch.index <- geosketch$gs(X.pcs, sketch.size)\n sketch.index <- unlist(sketch.index) + 1\n sketch.cells <- cells.all[sketch.index]\n return(sketch.cells)\n}\n\n\n#' Add the cell information into meta slot\n#'\n#' @param object CellChat object\n#' @param meta cell information to be added\n#' @param meta.name the name of column to be assigned\n#'\n#' @return\n#' @export\n#'\n#' @examples\naddMeta <- function(object, meta, meta.name = NULL) {\n if (is.null(x = meta.name) && is.atomic(x = meta)) {\n stop(\"'meta.name' must be provided for atomic meta types (eg. vectors)\")\n }\n if (inherits(x = meta, what = c(\"matrix\", \"Matrix\"))) {\n meta <- as.data.frame(x = meta)\n }\n\n if (is.null(x = meta.name)) {\n meta.name <- names(meta)\n } else {\n names(meta) <- meta.name\n }\n object@meta <- meta\n return(object)\n}\n\n\n#' Set the default identity of cells\n#' @param object CellChat object\n#' @param ident.use the name of the variable in object.meta;\n#' @param levels set the levels of factor\n#' @param display.warning whether display the warning message\n#' @return\n#' @export\n#'\n#' @examples\nsetIdent <- function(object, ident.use = NULL, levels = NULL, display.warning = TRUE){\n if (!is.null(ident.use)) {\n object@idents <- as.factor(object@meta[[ident.use]])\n }\n\n if (!is.null(levels)) {\n object@idents <- factor(object@idents, levels = levels)\n }\n if (\"0\" %in% as.character(object@idents)) {\n stop(\"Cell labels cannot contain `0`! \")\n }\n if (length(object@net) > 0) {\n if (all(dimnames(object@net$prob)[[1]] %in% levels(object@idents) )) {\n message(\"Reorder cell groups! \")\n cat(\"The cell group order before reordering is \", dimnames(object@net$prob)[[1]],'\\n')\n # idx <- match(dimnames(object@net$prob)[[1]], levels(object@idents))\n idx <- match(levels(object@idents), dimnames(object@net$prob)[[1]])\n object@net$prob <- object@net$prob[idx, , ]\n object@net$prob <- object@net$prob[, idx, ]\n object@net$pval <- object@net$pval[idx, , ]\n object@net$pval <- object@net$pval[, idx, ]\n cat(\"The cell group order after reordering is \", dimnames(object@net$prob)[[1]],'\\n')\n } else {\n message(\"Rename cell groups but do not change the order! \")\n cat(\"The cell group order before renaming is \", dimnames(object@net$prob)[[1]],'\\n')\n dimnames(object@net$prob) <- list(levels(object@idents), levels(object@idents), dimnames(object@net$prob)[[3]])\n dimnames(object@net$pval) <- dimnames(object@net$prob)\n cat(\"The cell group order after renaming is \", dimnames(object@net$prob)[[1]],'\\n')\n }\n if (display.warning) {\n warning(\"All the calculations after `computeCommunProb` should be re-run!!\n These include but not limited to `computeCommunProbPathway`,`aggregateNet`, and `netAnalysis_computeCentrality`.\")\n }\n\n\n }\n return(object)\n}\n\n\n#' Add a reduced space of the data into CellChat object\n#'\n#' @param object CellChat object from a single dataset\n#' @param dr A data frame (rows are cells with rownames) consisting of a low-dimensional space for visualization\n#' @param dr.name A char name of the reduction method for the input `dr`\n#' @param seu.obj A Seurat object with the reduced space of the data\n#' @param dr.use A char name of the reduction method to use when taking `seu.obj` as input. By default, all reduced space in `seu.obj` will be added in `object@dr`\n#' @param force.add Whether to force to add a new reduced space when a reduced space exists in `object@dr`\n#' @return\n#' @export\n#' @examples\n#' \\dontrun{\n#' cellChat <- addReduction(object = cellchat, dr = cell.embeddings, dr.name = \"umap\")\n#'\n#' cellChat <- addReduction(object = cellchat, seu.obj = seu.obj)\n#' }\naddReduction <- function(object, dr = NULL, dr.name = NULL, seu.obj = NULL, dr.use = NULL, force.add = FALSE) {\n if (length(names(object@dr)) > 0) {\n if (!force.add) {\n stop(paste0(\"The `object@dr` contains the following reduced space: \", toString(names(object@dr)), \". Please set `force.add = TRUE` if intending to add a new reduced space. \\n\"))\n }\n }\n if (!is.null(dr)) {\n if (is.null(dr.name)) {\n stop(\"When inputing `dr`, please also provide the `dr.name`! \\n\")\n }\n dr <- as.data.frame(dr)\n if (all(colnames(object@data.signaling) %in% rownames(dr))) {\n object@dr[[dr.name]] <- dr[colnames(object@data.signaling), ]\n } else {\n stop(\"Some cell barcodes in the CellChat object are not the rownames of the input `dr`. Please check the input `dr` and make sure it contains all cells in the CellChat analysis. \\n\")\n }\n } else if(!is.null(seu.obj)) {\n if (!is(seu.obj,\"Seurat\")) {\n stop(\"The input `seu.obj` can be only the Seurat object. \\n\")\n }\n reductions <- names(seu.obj@reductions)\n if (length(reductions) == 0) {\n stop(\"The input `seu.obj` does not contain any low-dimensional space. Please generate a low-dimensional space for visualization. \\n\")\n }\n if (!is.null(dr.use)) {\n reductions <- intersect(reductions, dr.use)\n }\n if (length(reductions) == 0) {\n stop(\"The input `dr.use` is not in the reduced space in `seu.obj`. \\n\")\n }\n for (i in 1:length(reductions)) {\n dr.name <- reductions[i]\n dr = seu.obj@reductions[[dr.name]]@cell.embeddings\n if (all(colnames(object@data.signaling) %in% rownames(dr))) {\n cat(paste0(dr.name, \" is now added in `object@dr` as a low-dimensional space. \\n\"))\n object@dr[[dr.name]] <- dr[colnames(object@data.signaling), ]\n } else {\n stop(\"Some cell barcodes in the CellChat object are not in the input `seu.obj`. Please check the input `seu.obj` and make sure it contains all cells in the CellChat analysis. \\n\")\n }\n }\n } else {\n stop(\"Please input either `dr` or `seu.obj`! \\n\")\n }\n return(object)\n}\n\n\n#' Update and re-order the cell group names after running `computeCommunProb`\n#'\n#' @param object CellChat object\n#' @param old.cluster.name A vector defining old cell group labels in `object@idents`; Default = NULL, which will use `levels(object@idents)`\n#' @param new.cluster.name A vector defining new cell group labels to rename\n#' @param new.order reset order of cell group labels\n#' @param new.cluster.metaname assign a name of the new labels, which will be the column name of new labels in `object@meta`\n#' @return An updated CellChat object\n#' @export\n#'\nupdateClusterLabels <- function(object, old.cluster.name = NULL, new.cluster.name = NULL, new.order = NULL, new.cluster.metaname = \"new.labels\") {\n if (is.null(old.cluster.name)) {\n old.cluster.name <- levels(object@idents)\n }\n if (new.cluster.metaname %in% colnames(object@meta)) {\n stop(\"Please define another `new.cluster.metaname` as it exists in `colnames(object@meta)`!\")\n }\n if (!is.null(new.cluster.name)) {\n labels.new <- plyr::mapvalues(object@idents, from = old.cluster.name, to = new.cluster.name)\n object@meta[[new.cluster.metaname]] <- labels.new\n object <- setIdent(object, ident.use = new.cluster.metaname, display.warning = FALSE)\n } else {\n new.cluster.metaname <- NULL\n cat(\"Only reorder cell groups but do not rename cell groups!\")\n }\n\n if (!is.null(new.order)) {\n object <- setIdent(object, ident.use = new.cluster.metaname, levels = new.order, display.warning = FALSE)\n }\n message(\"We now re-run computeCommunProbPathway`,`aggregateNet`, and `netAnalysis_computeCentrality`...\")\n object <- computeCommunProbPathway(object)\n ## calculate the aggregated network by counting the number of links or summarizing the communication probability\n object <- aggregateNet(object)\n # network importance analysis\n object <-netAnalysis_computeCentrality(object, slot.name = \"netP\")\n return(object)\n}\n\n\n\n\n\n#' Subset the expression data of signaling genes for saving computation cost\n#'\n#' @param object CellChat object\n#' @param features default = NULL: subset the expression data of signaling genes in CellChatDB.use\n#'\n#' @return An updated CellChat object by assigning a subset of the data into the slot `data.signaling`\n#' @export\n#'\nsubsetData <- function(object, features = NULL) {\n interaction_input <- object@DB$interaction\n if (object@options$datatype != \"RNA\") {\n if (\"annotation\" %in% colnames(interaction_input) == FALSE) {\n warning(\"A column named `annotation` is required in `object@DB$interaction` when running CellChat on spatial transcriptomics! The `annotation` column is now automatically added and all L-R pairs are assigned as `Secreted Signaling`, which means that these L-R pairs are assumed to mediate diffusion-based cellular communication.\")\n interaction_input$annotation <- \"Secreted Signaling\"\n }\n }\n if (\"annotation\" %in% colnames(interaction_input) == TRUE) {\n if (length(unique(interaction_input$annotation)) > 1) {\n interaction_input$annotation <- factor(interaction_input$annotation, levels = c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\", \"Cell-Cell Contact\"))\n interaction_input <- interaction_input[order(interaction_input$annotation), , drop = FALSE]\n interaction_input$annotation <- as.character(interaction_input$annotation)\n }\n object@DB$interaction <- interaction_input\n }\n\n if (is.null(features)) {\n DB <- object@DB\n gene.use_input <- extractGene(DB)\n gene.use <- intersect(gene.use_input, rownames(object@data))\n } else {\n gene.use <- intersect(features, rownames(object@data))\n }\n object@data.signaling <- object@data[rownames(object@data) %in% gene.use, ]\n return(object)\n}\n\n\n\n#' Identify over-expressed signaling genes associated with each cell group\n#'\n#' USERS can use customized gene set as over-expressed signaling genes by setting `object@var.features[[features.name]] <- features.sig`\n#' The Bonferroni corrected/adjusted p value can be obtained via `object@var.features[[paste0(features.name, \".info\")]]`. Note that by default `features.name = \"features\"`\n#'\n#' @param object CellChat object\n#' @param data.use a customed data matrix. Default: data.use = NULL and the expression matrix in the slot 'data.signaling' is used\n#' @param group.by cell group information; default is `object@idents`; otherwise it should be one of the column names of the meta slot\n#' @param idents.use a subset of cell groups used for analysis\n#' @param invert whether to invert the idents.use\n#' @param group.dataset dataset origin information in a merged CellChat object; set it as one of the column names of meta slot when identifying the highly enriched genes in one dataset for each cell group\n#' @param pos.dataset the dataset name used for identifying highly enriched genes in this dataset for each cell group\n#' @param group.DE.combined Whether to perform differential expression between conditions by ignoring cell group information. By default, group.DE.combined = FALSE, which will perform differential expression analysis between two biological conditions for each cell group;\n#' When group.DE.combined = TRUE, it will perform DE analysis by combining all cell groups together.\n#'\n#' @param features.name a char name used for storing the over-expressed signaling genes in `object@var.features[[features.name]]`\n#' @param only.pos Only return positive markers\n#' @param features features used for identifying Over Expressed genes. default use all features\n#' @param return.object whether to return the object; otherwise return a data frame consisting of over-expressed signaling genes associated with each cell group\n#' @param thresh.pc Threshold of the fraction of cells expressed in one cluster, i.e., thresh.pc = 0.1\n#' @param thresh.fc Threshold of Log Fold Change, i.e., thresh.pc = 0.1\n#' @param thresh.p Threshold of p-values, i.e., thresh.pc = 0.05\n#' @param do.DE Whether to perform differential expression analysis. By default do.DE = TRUE; When do.DE = FALSE, selecting over-expressed genes that are expressed in more than `min.cells` cells.\n#' @param do.fast If do.fast = TRUE, then perform a ultra-fast Wilcoxon test using presto package; otherwise using stats package. These two methods produce different logFC values, and the presto::wilcoxauc method gives smaller values.\n#' @param min.cells the minmum number of expressed cells required for the genes that are considered for cell-cell communication analysis\n#' @importFrom future nbrOfWorkers\n#' @importFrom pbapply pbsapply\n#' @importFrom future.apply future_sapply\n#' @importFrom stats sd wilcox.test p.adjust\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, two new elements named 'features.name' and paste0(features.name, \".info\") will be added into the list `object@var.features`\n#' `object@var.features[[features.name]]` is a vector consisting of the identified over-expressed signaling genes;\n#' `object@var.features[[paste0(features.name, \".info\")]]` is a data frame returned from the differential expression analysis\n#' @export\n#'\nidentifyOverExpressedGenes <- function(object, data.use = NULL, group.by = NULL, idents.use = NULL, invert = FALSE,\n group.dataset = NULL, pos.dataset = NULL, group.DE.combined = FALSE,\n features.name = \"features\", only.pos = TRUE, features = NULL, return.object = TRUE,\n thresh.pc = 0, thresh.fc = 0, thresh.p = 0.05, do.DE = TRUE, do.fast = TRUE, min.cells = 10) {\n if (!is.list(object@var.features)) {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n if (is.null(data.use)) {\n X <- object@data.signaling\n if (nrow(X) < 3) {stop(\"Please check `object@data.signaling` and ensure that you have run `subsetData` and that the data matrix `object@data.signaling` looks OK.\")}\n } else {\n X <- data.use\n }\n\n if (is.null(features)) {\n features.use <- row.names(X)\n } else {\n features.use <- intersect(features, row.names(X))\n }\n data.use <- X[features.use,]\n\n if (do.DE) {\n # select genes based on differential expression\n data.use <- as.matrix(data.use)\n\n if (is.null(group.by)) {\n labels <- object@idents\n if (!is.factor(labels)) {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n level.use <- levels(labels)[levels(labels) %in% unique(labels)]\n if (!is.null(idents.use)) {\n if (invert) {\n level.use <- level.use[!(level.use %in% idents.use)]\n } else {\n level.use <- level.use[level.use %in% idents.use]\n }\n }\n numCluster <- length(level.use)\n\n if (!is.null(group.dataset)) {\n labels.dataset <- as.character(object@meta[[group.dataset]])\n if (!(pos.dataset %in% unique(labels.dataset))) {\n cat(\"Please set pos.dataset to be one of the following dataset names: \", unique(as.character(labels.dataset)))\n stop()\n }\n labels.dataset[labels.dataset != pos.dataset] <- toString(setdiff(unique(labels.dataset), pos.dataset))\n labels.dataset <- factor(labels.dataset, levels = c(pos.dataset, setdiff(unique(labels.dataset), pos.dataset)))\n }\n\n if (do.fast) {\n presto.check <- rlang::is_installed(c(\"presto\"))\n if (!presto.check) {\n stop(\n \"For a faster implementation of the Wilcoxon Test, please install the presto package\",\n \"\\n--------------------------------------------\",\n \"\\n devtools::install_github('immunogenomics/presto')\",\n \"\\n--------------------------------------------\",\n \"\\n Otherwise, plase set `do.fast = FALSE` for running the standard Wilcoxon Test!\\n\"\n )\n }\n if (is.null(group.dataset)) {\n genes.de <- presto::wilcoxauc(data.use, labels, groups_use = level.use)\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"clusters\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100) %>% arrange(pvalues)\n\n } else if ((!is.null(group.dataset)) & (group.DE.combined == FALSE)) {\n genes.de <- data.frame()\n for (i in 1:numCluster) {\n idx <- which(labels == level.use[i])\n data.use.i <- data.use[ ,idx]\n labels.i <- labels.dataset[idx]\n genes.de.i <- presto::wilcoxauc(data.use.i, labels.i)\n # genes.de.i <- genes.de.i[1:(nrow(genes.de.i)/2),]\n genes.de.i$clusters <- level.use[i]\n genes.de <- rbind(genes.de, genes.de.i)\n }\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"datasets\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100)\n markers.all$datasets <- factor(markers.all$datasets, levels = levels(labels.dataset))\n markers.all <- markers.all[order(markers.all$datasets, markers.all$pvalues, -markers.all$logFC), ]\n } else if ((!is.null(group.dataset)) & (group.DE.combined == TRUE)) {\n genes.de.c <- presto::wilcoxauc(data.use, labels.dataset)\n genes.de.c <- genes.de.c[1:(nrow(genes.de.c)/2),]\n genes.de <- data.frame()\n for (i in 1:numCluster) {\n genes.de.c$clusters <- level.use[i]\n genes.de <- rbind(genes.de, genes.de.c)\n }\n colnames(genes.de) <- plyr::mapvalues(colnames(genes.de),from = c(\"group\",\"feature\",\"pval\",\"logFC\",\"pct_in\",\"pct_out\",\"padj\"), to = c(\"datasets\",\"features\",\"pvalues\",\"logFC\",\"pct.1\", \"pct.2\",\"pvalues.adj\"), warn_missing = TRUE)\n genes.de$logFC_abs <- abs(genes.de$logFC)\n pct.max <- apply(genes.de[, c(\"pct.1\", \"pct.2\"), drop = FALSE], MARGIN = 1, FUN = max)\n genes.de$pct.max <- pct.max\n markers.all <- dplyr::filter(genes.de, pvalues < thresh.p, logFC_abs >= thresh.fc, pct.max > thresh.pc*100) %>% arrange(pvalues)\n\n }\n markers.all <- dplyr::select(markers.all, -c(\"logFC_abs\",\"statistic\",\"pct.max\"))\n\n if (only.pos & nrow(markers.all) > 0) {\n markers.all <- subset(markers.all, subset = logFC > 0)\n }\n markers.all$features <- as.character(markers.all$features)\n\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- unique(features.sig)\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n\n } else {\n\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n\n mean.fxn <- function(x) {\n return(log(x = mean(x = expm1(x = x)) + 1))\n }\n labels <- as.character(labels)\n genes.de <- vector(\"list\", length = numCluster)\n for (i in 1:numCluster) {\n features <- features.use\n if (is.null(group.dataset)) {\n cell.use1 <- which(labels == level.use[i])\n cell.use2 <- base::setdiff(1:length(labels), cell.use1)\n } else if ((!is.null(group.dataset)) & (group.DE.combined == FALSE)) {\n cell.use1 <- which((labels == level.use[i]) & (labels.dataset == pos.dataset))\n cell.use2 <- which((labels == level.use[i]) & (labels.dataset != pos.dataset))\n } else if ((!is.null(group.dataset)) & (group.DE.combined == TRUE)) {\n cell.use1 <- which(labels.dataset == pos.dataset)\n cell.use2 <- which(labels.dataset != pos.dataset)\n }\n\n # feature selection (based on percentages)\n thresh.min <- 0\n pct.1 <- round(\n x = rowSums(data.use[features, cell.use1, drop = FALSE] > thresh.min) /\n length(x = cell.use1),\n digits = 3\n )\n pct.2 <- round(\n x = rowSums(data.use[features, cell.use2, drop = FALSE] > thresh.min) /\n length(x = cell.use2),\n digits = 3\n )\n data.alpha <- cbind(pct.1, pct.2)\n colnames(x = data.alpha) <- c(\"pct.1\", \"pct.2\")\n alpha.min <- apply(X = data.alpha, MARGIN = 1, FUN = max)\n names(x = alpha.min) <- rownames(x = data.alpha)\n features <- names(x = which(x = alpha.min > thresh.pc))\n if (length(x = features) == 0) {\n #stop(\"No features pass thresh.pc threshold\")\n next\n }\n\n # feature selection (based on average difference)\n data.1 <- apply(X = data.use[features, cell.use1, drop = FALSE],MARGIN = 1,FUN = mean.fxn)\n data.2 <- apply(X = data.use[features, cell.use2, drop = FALSE],MARGIN = 1,FUN = mean.fxn)\n FC <- (data.1 - data.2)\n if (only.pos) {\n features.diff <- names(which(FC > thresh.fc))\n } else {\n features.diff <- names(which(abs(FC) > thresh.fc))\n }\n\n features <- intersect(x = features, y = features.diff)\n if (length(x = features) == 0) {\n # stop(\"No features pass thresh.fc threshold\")\n next\n }\n\n data1 <- data.use[features, cell.use1, drop = FALSE]\n data2 <- data.use[features, cell.use2, drop = FALSE]\n\n pvalues <- unlist(\n x = my.sapply(\n X = 1:nrow(x = data1),\n FUN = function(x) {\n # return(wilcox.test(data1[x, ], data2[x, ], alternative = \"greater\")$p.value)\n return(wilcox.test(data1[x, ], data2[x, ])$p.value)\n }\n )\n )\n\n pval.adj = stats::p.adjust(\n p = pvalues,\n method = \"bonferroni\",\n n = nrow(X)\n )\n genes.de[[i]] <- data.frame(clusters = level.use[i], features = as.character(rownames(data1)), pvalues = pvalues, logFC = FC[features], data.alpha[features,, drop = F],pvalues.adj = pval.adj, stringsAsFactors = FALSE)\n }\n\n markers.all <- data.frame()\n for (i in 1:numCluster) {\n gde <- genes.de[[i]]\n if (!is.null(gde)) {\n gde <- gde[order(gde$pvalues, -gde$logFC), ]\n gde <- subset(gde, subset = pvalues < thresh.p)\n if (nrow(gde) > 0) {\n markers.all <- rbind(markers.all, gde)\n }\n }\n }\n if (only.pos & nrow(markers.all) > 0) {\n markers.all <- subset(markers.all, subset = logFC > 0)\n }\n if (!is.null(group.dataset)) {\n markers.all$datasets[markers.all$logFC > 0] <- pos.dataset\n markers.all$datasets[markers.all$logFC < 0] <- setdiff(unique(labels.dataset), pos.dataset)\n markers.all$datasets <- factor(markers.all$datasets, levels = levels(labels.dataset))\n markers.all <- markers.all[order(markers.all$datasets, markers.all$pvalues, -markers.all$logFC), ]\n }\n markers.all$features <- as.character(markers.all$features)\n\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- features.sig\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n }\n\n } else {\n # select genes if they are exprssed in at least `min.cells` cells\n markers.all <- data.frame(features = as.character(rownames(data.use)), nCells = rowSums(data.use > 0))\n markers.all <- dplyr::filter(markers.all, nCells >= min.cells)\n features.sig <- markers.all$features\n object@var.features[[features.name]] <- unique(features.sig)\n features.name <- paste0(features.name, \".info\")\n object@var.features[[features.name]] <- markers.all\n }\n\n\n if (return.object) {\n return(object)\n } else {\n return(markers.all)\n }\n}\n\n\n#' Identify over-expressed ligands and (complex) receptors associated with each cell group\n#'\n#' This function identifies the over-expressed ligands and (complex) receptors based on the identified signaling genes from 'identifyOverExpressedGenes'.\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for storing the over-expressed ligands and receptors in `object@var.features[[paste0(features.name, \".LR\")]]`\n#' @param features a vector of features to use. default use all over-expressed genes in `object@var.features[[features.name]]`\n#' @param return.object whether returning a CellChat object. If FALSE, it will return a data frame containing over-expressed ligands and (complex) receptors associated with each cell group\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom dplyr select\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, a new element named paste0(features.name, \".LR\") will be added into the list `object@var.features`\n#' @export\n#'\nidentifyOverExpressedLigandReceptor <- function(object, features.name = \"features\", features = NULL, return.object = TRUE) {\n\n features.name.LR <- paste0(features.name, \".LR\")\n features.name <- paste0(features.name, \".info\")\n DB <- object@DB\n interaction_input <- DB$interaction\n complex_input <- DB$complex\n pairLR <- select(interaction_input, ligand, receptor)\n LR.use <- unique(c(pairLR$ligand, pairLR$receptor))\n if (is.null(features)) {\n if (is.list(object@var.features)) {\n markers.all <- object@var.features[[features.name]] # use the updated CellChat object 12/2020\n } else {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n\n } else {\n features.use <- features\n rm(features)\n markers.all <- subset(markers.all, subset = features %in% features.use)\n }\n\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n complexSubunits <- complex_input[, grepl(\"subunit\" , colnames(complex_input))]\n\n markers.all.new <- data.frame()\n for (i in 1:nrow(markers.all)) {\n if (markers.all$features[i] %in% LR.use) {\n markers.all.new <- rbind(markers.all.new, markers.all[i, , drop = FALSE])\n } else {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (markers.all$features[i] %in% complexsubunitsV) {\n return(x)\n }\n }\n )\n )\n complexSubunits.sig <- rownames(complexSubunits[index.sig,])\n markers.all.complex <- data.frame()\n for (j in 1:length(complexSubunits.sig)) {\n markers.all.complex <- rbind(markers.all.complex, markers.all[i, , drop = FALSE])\n }\n markers.all.complex$features <- complexSubunits.sig\n markers.all.new <- rbind(markers.all.new, markers.all.complex)\n }\n }\n\n object@var.features[[features.name.LR]] <- markers.all.new\n\n if (return.object) {\n return(object)\n } else {\n return(markers.all.new)\n }\n}\n\n\n\n#' Identify over-expressed ligand-receptor interactions (pairs) within the used CellChatDB\n#'\n#' @param object CellChat object\n#' @param features.name a char name used for assess the results in `object@var.features[[features.name]]`\n#' @param features a vector of features to use. default use all over-expressed genes in `object@var.features[[features.name]]`\n#' @param variable.both variable.both = TRUE will require that both ligand and receptor from one pair are over-expressed;\n#'\n#' variable.both = FALSE will only require that either ligand or receptor from one pair is over-expressed, leading to more over-expressed ligand-receptor interactions (pairs) for further analysis.\n#' @param return.object whether returning a CellChat object. If FALSE, it will return a data frame containing the over-expressed ligand-receptor pairs\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom dplyr select\n#'\n#' @return A CellChat object or a data frame. If returning a CellChat object, a new element named 'LRsig' will be added into the list `object@LR`\n#' @export\n#'\nidentifyOverExpressedInteractions <- function(object, features.name = \"features\", variable.both = TRUE, features = NULL, return.object = TRUE) {\n gene.use <- row.names(object@data.signaling)\n DB <- object@DB\n if (is.null(features)) {\n if (is.list(object@var.features)) {\n features.sig <- object@var.features[[features.name]] # use the updated CellChat object 12/2020\n } else {\n stop(\"Please update your CellChat object via `updateCellChat()`\")\n }\n\n } else {\n features.sig <- features\n }\n\n interaction_input <- DB$interaction\n complex_input <- DB$complex\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n complexSubunits <- complex_input[, grepl(\"subunit\" , colnames(complex_input))]\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (length(intersect(complexsubunitsV, features.sig)) > 0 & all(complexsubunitsV %in% gene.use)) {\n return(x)\n }\n }\n )\n )\n complexSubunits.sig <- complexSubunits[index.sig,]\n\n index.use <- unlist(\n x = my.sapply(\n X = 1:nrow(complexSubunits),\n FUN = function(x) {\n complexsubunitsV <- unlist(complexSubunits[x,], use.names = F)\n complexsubunitsV <- complexsubunitsV[complexsubunitsV != \"\"]\n if (all(complexsubunitsV %in% gene.use)) {\n return(x)\n }\n }\n )\n )\n complexSubunits.use <- complexSubunits[index.use,]\n\n pairLR <- select(interaction_input, ligand, receptor)\n\n if (variable.both) {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(pairLR),\n FUN = function(x) {\n if (all(unlist(pairLR[x,], use.names = F) %in% c(features.sig, rownames(complexSubunits.sig)))) {\n return(x)\n }\n }\n )\n )\n } else {\n index.sig <- unlist(\n x = my.sapply(\n X = 1:nrow(pairLR),\n FUN = function(x) {\n # if (all(unlist(pairLR[x,], use.names = F) %in% c(features.sig, rownames(complexSubunits.sig)))) {\n if (all(unlist(pairLR[x,], use.names = F) %in% c(gene.use, rownames(complexSubunits.use))) & (length(intersect(unlist(pairLR[x,], use.names = F), c(features.sig, rownames(complexSubunits.sig)))) > 0)) {\n return(x)\n }\n }\n )\n )\n }\n\n pairLRsig <- interaction_input[index.sig, ]\n object@LR$LRsig <- pairLRsig\n cat(\"The number of highly variable ligand-receptor pairs used for signaling inference is\", nrow(pairLRsig), '\\n')\n if (return.object) {\n return(object)\n } else {\n return(pairLRsig)\n }\n}\n\n\n#' Smooth the gene expression data\n#'\n#' A diffusion process is used to smooth genes’ expression values based on their neighbors’ defined in a high-confidence experimentally validated protein-protein network.\n#'\n#' This function is useful when analyzing single-cell data with shallow sequencing depth because the projection reduces the dropout effects of signaling genes, in particular for possible zero expression of subunits of ligands/receptors\n#'\n#' @param object CellChat object\n#' @param method When method = \"netSmooth\", smoothing a gene’s expression values based on its neighbors defined in a high-confidence experimentally validated protein-protein network.\n#' @param adj adjacency matrix of protein-protein interaction network to use\n#' @param alpha numeric in [0,1] alpha = 0: no smoothing; a larger value alpha results in increasing levels of smoothing.\n#' @param normalizeAdjMatrix how to normalize the adjacency matrix\n#' possible values are 'rows' (in-degree)\n#' and 'columns' (out-degree)\n#' @return a smoothed gene expression matrix\n#' @export\n#'\n# This function is adapted from https://github.com/BIMSBbioinfo/netSmooth\nsmoothData <- function(object, method = c(\"netSmooth\"), adj = NULL, alpha=0.5, normalizeAdjMatrix=c('rows','columns')){\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n stop(\"`object@data.smooth` is missing. Please update the CellChat object via `updateCellChat`! \\n\")\n }\n data <- as.matrix(object@data.signaling)\n normalizeAdjMatrix <- match.arg(normalizeAdjMatrix)\n if (method == \"netSmooth\") {\n if (is.null(adj)) stop(\"Please provide the `adj`. \\n\")\n stopifnot(is(adj, 'matrix') | is(adj, 'sparseMatrix'))\n stopifnot((is.numeric(alpha) & (alpha > 0 & alpha < 1)))\n if(sum(Matrix::rowSums(adj)==0)>0) stop(\"PPI cannot have zero rows/columns\")\n if(sum(Matrix::colSums(adj)==0)>0) stop(\"PPI cannot have zero rows/columns\")\n }\n if(is.numeric(alpha)) {\n if(alpha<0 | alpha > 1) {\n stop('alpha must be between 0 and 1')\n }\n data.projected <- projectAndRecombine(data, adj, alpha,normalizeAdjMatrix=normalizeAdjMatrix)\n } else stop(\"unsupported alpha value: \", class(alpha))\n object@data.smooth <- data.projected\n return(object)\n}\n\n#' Perform network projecting on network when the network genes and the\n#' experiment genes aren't exactly the same.\n#'\n#' The gene network might be defined only on a subset of genes that are\n#' measured in any experiment. Further, an experiment might not measure all\n#' genes that are present in the network. This function projects the experiment\n#' data onto the gene space defined by the network prior to projecting. Then,\n#' it projects the projected data back into the original dimansions.\n#'\n#' @param gene_expression gene expession data to be projected\n#' [N_genes x M_samples]\n#' @param adj_matrix adjacenty matrix of network to perform projecting over.\n#' Will be column-normalized.\n#' Rownames and colnames should be genes.\n#' @param alpha network projecting parameter (1 - restart probability in random\n#' walk model.\n#' @param projecting.function must be a function that takes in data, adjacency\n#' matrix, and alpha. Will be used to perform the\n#' actual projecting.\n#' @param normalizeAdjMatrix which dimension (rows or columns) should the\n#' adjacency matrix be normalized by. rows\n#' corresponds to in-degree, columns to\n#' out-degree.\n#' @return matrix with network-projected gene expression data. Genes that are\n#' not present in projecting network will retain original values.\n#' @keywords internal\n#'\nprojectAndRecombine <- function(gene_expression, adj_matrix, alpha,\n projecting.function=randomWalkBySolve,\n normalizeAdjMatrix=c('rows','columns')) {\n normalizeAdjMatrix <- match.arg(normalizeAdjMatrix)\n gene_expression_in_A_space <- projectOnNetwork(gene_expression,rownames(adj_matrix))\n gene_expression_in_A_space_project <- projecting.function(gene_expression_in_A_space, adj_matrix, alpha, normalizeAdjMatrix)\n gene_expression_project <- projectFromNetworkRecombine(gene_expression, gene_expression_in_A_space_project)\n return(gene_expression_project)\n}\n\n\n#' Project the gene expression matrix onto a lower space\n#' of the genes defined in the projecting network\n#' @param gene_expression gene expression matrix\n#' @param new_features the genes in the network, on which to project\n#' the gene expression matrix\n#' @param missing.value value to assign to genes that are in network,\n#' but missing from gene expression matrix\n#' @return the gene expression matrix projected onto the gene space defined by new_features\n#' @keywords internal\nprojectOnNetwork <- function(gene_expression, new_features, missing.value=0) {\n # data_in_new_space = matrix(rep(0, length(new_features)*dim(gene_expression)[2]),nrow=length(new_features))\n data_in_new_space = matrix(0, ncol=dim(gene_expression)[2], nrow=length(new_features))\n rownames(data_in_new_space) <- new_features\n colnames(data_in_new_space) <- colnames(gene_expression)\n genes_in_both <- intersect(rownames(data_in_new_space),rownames(gene_expression))\n data_in_new_space[genes_in_both,] <- gene_expression[genes_in_both,]\n genes_only_in_network <- setdiff(new_features, rownames(gene_expression))\n data_in_new_space[genes_only_in_network,] <- missing.value\n return(data_in_new_space)\n}\n\n#' project data on graph by solving the linear equation (I - alpha*A) * E_sm = E * (1-alpha)\n\n#' @param E initial data matrix [NxM]\n#' @param A adjacency matrix of graph to network project on will be column-normalized.\n#' @param alpha projecting coefficient (1 - restart probability of random walk)\n#' @return network-projected gene expression\n#' @keywords internal\nrandomWalkBySolve <- function(E, A, alpha, normalizeAjdMatrix=c('rows','columns')) {\n normalizeAjdMatrix <- match.arg(normalizeAjdMatrix)\n if (normalizeAjdMatrix=='rows') {\n Anorm <- l1NormalizeRows(A)\n } else if (normalizeAjdMatrix=='columns') {\n Anorm <- l1NormalizeColumns(A)\n }\n eye <- diag(dim(A)[1])\n AA <- eye - alpha*Anorm\n BB <- (1-alpha) * E\n return(solve(AA, BB))\n}\n\n#' Column-normalize a sparse, symmetric matrix (using the l1 norm) so that each\n#' column sums to 1.\n#'\n#' @param A matrix\n#' @usage l1NormalizeColumns(A)\n#' @return column-normalized sparse matrix object\n#' @keywords internal\nl1NormalizeColumns <- function(A) {\n return(Matrix::t(Matrix::t(A)/Matrix::colSums(A)))\n}\n\n#' Row-normalize a sparse, symmetric matrix (using the l1 norm) so that each\n#' row sums to 1.\n#'\n#' @param A matrix\n#' @usage l1NormalizeRows(A)\n#' @return row-normalized sparse matrix object\n#' @keywords internal\nl1NormalizeRows <- function(A) {\n return(A/Matrix::rowSums(A))\n}\n\n#' Combine gene expression from projected space (that of the network) with the\n#' expression of genes that were not projected (not present in network)\n#' @keywords internal\n#' @param original_expression the non-projected expression\n#' @param projected_expression the projected gene expression, in the space\n#' of the genes defined by the network\n#' @return a matrix in the dimensions of original_expression, where values that\n#' are present in projected_expression are copied from there.\nprojectFromNetworkRecombine <- function(original_expression, projected_expression) {\n data_in_original_space <- original_expression\n genes_in_both <- intersect(rownames(original_expression),rownames(projected_expression))\n data_in_original_space[genes_in_both,] <- as.matrix(projected_expression[genes_in_both,])\n return(data_in_original_space)\n}\n\n\n#' Dimension reduction using PCA\n#'\n#' @param data.use input data (samples in rows, features in columns)\n#' @param do.fast whether do fast PCA\n#' @param dimPC the number of components to keep\n#' @param seed.use set a seed\n#' @param weight.by.var whether use weighted pc.scores\n#' @importFrom stats prcomp\n#' @importFrom irlba irlba\n#' @return\n#' @export\n#'\n#' @examples\nrunPCA <- function(data.use, do.fast = T, dimPC = 50, seed.use = 42, weight.by.var = T) {\n set.seed(seed = seed.use)\n if (do.fast) {\n dimPC <- min(dimPC, ncol(data.use) - 1)\n pca.res <- irlba::irlba(data.use, nv = dimPC)\n sdev <- pca.res$d/sqrt(max(1, nrow(data.use) - 1))\n if (weight.by.var){\n pc.scores <- pca.res$u %*% diag(pca.res$d)\n } else {\n pc.scores <- pca.res$u\n }\n } else {\n dimPC <- min(dimPC, ncol(data.use) - 1)\n pca.res <- stats::prcomp(x = data.use, rank. = dimPC)\n sdev <- pca.res$sdev\n if (weight.by.var) {\n pc.scores <- pca.res$x %*% diag(pca.res$sdev[1:dimPC]^2)\n } else {\n pc.scores <- pca.res$x\n }\n }\n rownames(pc.scores) <- rownames(data.use)\n colnames(pc.scores) <- paste0('PC', 1:ncol(pc.scores))\n return(pc.scores)\n}\n\n\n#' Run UMAP\n#' @param data.use input data matrix\n#' @param n_neighbors This determines the number of neighboring points used in\n#' local approximations of manifold structure. Larger values will result in more\n#' global structure being preserved at the loss of detailed local structure. In general this parameter should often be in the range 5 to 50.\n#' @param n_components The dimension of the space to embed into.\n#' @param metric This determines the choice of metric used to measure distance in the input space.\n#' @param n_epochs the number of training epochs to be used in optimizing the low dimensional embedding. Larger values result in more accurate embeddings. If NULL is specified, a value will be selected based on the size of the input dataset (200 for large datasets, 500 for small).\n#' @param learning_rate The initial learning rate for the embedding optimization.\n#' @param min_dist This controls how tightly the embedding is allowed compress points together.\n#' Larger values ensure embedded points are moreevenly distributed, while smaller values allow the\n#' algorithm to optimise more accurately with regard to local structure. Sensible values are in the range 0.001 to 0.5.\n#' @param spread he effective scale of embedded points. In combination with min.dist this determines how clustered/clumped the embedded points are.\n#' @param set_op_mix_ratio Interpolate between (fuzzy) union and intersection as the set operation used to combine local fuzzy simplicial sets to obtain a global fuzzy simplicial sets.\n#' @param local_connectivity The local connectivity required - i.e. the number of nearest neighbors\n#' that should be assumed to be connected at a local level. The higher this value the more connected\n#' the manifold becomes locally. In practice this should be not more than the local intrinsic dimension of the manifold.\n#' @param repulsion_strength Weighting applied to negative samples in low dimensional embedding\n#' optimization. Values higher than one will result in greater weight being given to negative samples.\n#' @param negative_sample_rate The number of negative samples to select per positive sample in the\n#' optimization process. Increasing this value will result in greater repulsive force being applied, greater optimization cost, but slightly more accuracy.\n#' @param a More specific parameters controlling the embedding. If NULL, these values are set automatically as determined by min. dist and spread.\n#' @param b More specific parameters controlling the embedding. If NULL, these values are set automatically as determined by min. dist and spread.\n#' @param seed.use Set a random seed. By default, sets the seed to 42.\n#' @param metric_kwds,angular_rp_forest,verbose other parameters used in UMAP\n#' @import reticulate\n#' @export\n#'\nrunUMAP <- function(\n data.use,\n n_neighbors = 30L,\n n_components = 2L,\n metric = \"correlation\",\n n_epochs = NULL,\n learning_rate = 1.0,\n min_dist = 0.3,\n spread = 1.0,\n set_op_mix_ratio = 1.0,\n local_connectivity = 1L,\n repulsion_strength = 1,\n negative_sample_rate = 5,\n a = NULL,\n b = NULL,\n seed.use = 42L,\n metric_kwds = NULL,\n angular_rp_forest = FALSE,\n verbose = FALSE){\n if (!reticulate::py_module_available(module = 'umap')) {\n stop(\"Cannot find UMAP, please install through pip (e.g. pip install umap-learn or reticulate::py_install(packages = 'umap-learn')).\")\n }\n set.seed(seed.use)\n reticulate::py_set_seed(seed.use)\n umap_import <- reticulate::import(module = \"umap\", delay_load = TRUE)\n umap <- umap_import$UMAP(\n n_neighbors = as.integer(n_neighbors),\n n_components = as.integer(n_components),\n metric = metric,\n n_epochs = n_epochs,\n learning_rate = learning_rate,\n min_dist = min_dist,\n spread = spread,\n set_op_mix_ratio = set_op_mix_ratio,\n local_connectivity = local_connectivity,\n repulsion_strength = repulsion_strength,\n negative_sample_rate = negative_sample_rate,\n a = a,\n b = b,\n metric_kwds = metric_kwds,\n angular_rp_forest = angular_rp_forest,\n verbose = verbose\n )\n Rumap <- umap$fit_transform\n umap_output <- Rumap(t(data.use))\n colnames(umap_output) <- paste0('UMAP', 1:ncol(umap_output))\n rownames(umap_output) <- colnames(data.use)\n return(umap_output)\n}\n\n.error_if_no_Seurat <- function() {\n if (!requireNamespace(\"Seurat\", quietly = TRUE)) {\n stop(\"Seurat installation required for working with Seurat objects\")\n }\n}\n\n\n#' Color interpolation\n#'\n#' This function is modified from https://rdrr.io/cran/circlize/src/R/utils.R\n#' Colors are linearly interpolated according to break values and corresponding colors through CIE Lab color space (`colorspace::LAB`) by default.\n#' Values exceeding breaks will be assigned with corresponding maximum or minimum colors.\n#'\n#' @param breaks A vector indicating numeric breaks\n#' @param colors A vector of colors which correspond to values in ``breaks``\n#' @param transparency A single value in ``[0, 1]``. 0 refers to no transparency and 1 refers to full transparency\n#' @param space color space in which colors are interpolated. Value should be one of \"RGB\", \"HSV\", \"HLS\", \"LAB\", \"XYZ\", \"sRGB\", \"LUV\", see `colorspace::color-class` for detail.\n#' @importFrom colorspace coords RGB HSV HLS LAB XYZ sRGB LUV hex\n#' @importFrom grDevices col2rgb\n#' @return It returns a function which accepts a vector of numeric values and returns interpolated colors.\n#' @export\n#' @examples\n#' \\dontrun{\n#' col_fun = colorRamp3(c(-1, 0, 1), c(\"green\", \"white\", \"red\"))\n#' col_fun(c(-2, -1, -0.5, 0, 0.5, 1, 2))\n#' }\ncolorRamp3 = function(breaks, colors, transparency = 0, space = \"LAB\") {\n\n if(length(breaks) != length(colors)) {\n stop(\"Length of `breaks` should be equal to `colors`.\\n\")\n }\n\n colors = colors[order(breaks)]\n breaks = sort(breaks)\n\n l = duplicated(breaks)\n breaks = breaks[!l]\n colors = colors[!l]\n\n if(length(breaks) == 1) {\n stop(\"You should have at least two distinct break values.\")\n }\n\n\n if(! space %in% c(\"RGB\", \"HSV\", \"HLS\", \"LAB\", \"XYZ\", \"sRGB\", \"LUV\")) {\n stop(\"`space` should be in 'RGB', 'HSV', 'HLS', 'LAB', 'XYZ', 'sRGB', 'LUV'\")\n }\n\n colors = t(grDevices::col2rgb(colors)/255)\n\n attr = list(breaks = breaks, colors = colors, transparency = transparency, space = space)\n\n if(space == \"LUV\") {\n i = which(apply(colors, 1, function(x) all(x == 0)))\n colors[i, ] = 1e-5\n }\n\n transparency = 1-ifelse(transparency > 1, 1, ifelse(transparency < 0, 0, transparency))[1]\n transparency_str = sprintf(\"%X\", round(transparency*255))\n if(nchar(transparency_str) == 1) transparency_str = paste0(\"0\", transparency_str)\n\n fun = function(x = NULL, return_rgb = FALSE, max_value = 1) {\n if(is.null(x)) {\n stop(\"Please specify `x`\\n\")\n }\n\n att = attributes(x)\n if(is.data.frame(x)) x = as.matrix(x)\n\n l_na = is.na(x)\n if(all(l_na)) {\n return(rep(NA, length(l_na)))\n }\n\n x2 = x[!l_na]\n\n x2 = ifelse(x2 < breaks[1], breaks[1],\n ifelse(x2 > breaks[length(breaks)], breaks[length(breaks)],\n x2\n ))\n ibin = .bincode(x2, breaks, right = TRUE, include.lowest = TRUE)\n res_col = character(length(x2))\n for(i in unique(ibin)) {\n l = ibin == i\n res_col[l] = .get_color(x2[l], breaks[i], breaks[i+1], colors[i, ], colors[i+1, ], space = space)\n }\n res_col = paste(res_col, transparency_str[1], sep = \"\")\n\n if(return_rgb) {\n res_col = t(grDevices::col2rgb(as.vector(res_col), alpha = TRUE)/255)\n return(res_col)\n } else {\n res_col2 = character(length(x))\n res_col2[l_na] = NA\n res_col2[!l_na] = res_col\n\n attributes(res_col2) = att\n return(res_col2)\n }\n }\n\n attributes(fun) = attr\n return(fun)\n}\n\n.restrict_in = function(x, lower, upper) {\n x[x > upper] = upper\n x[x < lower] = lower\n x\n}\n\n# x: vector\n# break1 single value\n# break2 single value\n# rgb1 vector with 3 elements\n# rgb2 vector with 3 elements\n.get_color = function(x, break1, break2, col1, col2, space) {\n\n col1 = colorspace::coords(as(colorspace::sRGB(col1[1], col1[2], col1[3]), space))\n col2 = colorspace::coords(as(colorspace::sRGB(col2[1], col2[2], col2[3]), space))\n\n res_col = matrix(ncol = 3, nrow = length(x))\n for(j in 1:3) {\n xx = (x - break2)*(col2[j] - col1[j]) / (break2 - break1) + col2[j]\n res_col[, j] = xx\n }\n\n res_col = get(space)(res_col)\n res_col = colorspace::coords(as(res_col, \"sRGB\"))\n res_col[, 1] = .restrict_in(res_col[,1], 0, 1)\n res_col[, 2] = .restrict_in(res_col[,2], 0, 1)\n res_col[, 3] = .restrict_in(res_col[,3], 0, 1)\n colorspace::hex(colorspace::sRGB(res_col))\n}\n\n#' Update the cell-cell communication array from a customized cell-cell-communication scores between different cell groups\n#'\n#' Users may also check the `updateCellChatDB` function for integrating other resources or utilizing a custom database\n#'\n#' @param object CellChat object\n#' @param net a data frame with at least five columns named as `source`,`target`,`ligand`,`receptor` and `score`, which defines the customized cell-cell-communication scores between different cell groups.\n#' a p-value column named `pval`, and additional columns named `interaction_name` and `interaction_name_2` can be also provided.\n#' @return a CellChat object with updated slot `net` and slot `DB` if db is not NULL.\n#' @export\n\nupdateCCC_score <- function(object, net) {\n df.net <- net\n if (all(c(\"source\",\"target\",\"ligand\",\"receptor\",\"score\") %in% colnames(df.net)) == FALSE) {\n stop(\"The input `net` must contain at least five columns named as source,target,ligand,receptor,score\")\n }\n if (all(c(\"interaction_name\") %in% colnames(df.net)) == FALSE) {\n df.net$interaction_name <- paste0(toupper(df.net$ligand), \"_\", toupper(df.net$receptor))\n }\n if (all(c(\"interaction_name_2\") %in% colnames(df.net)) == FALSE) {\n df.net$interaction_name_2 <- paste0(df.net$ligand, \" - \", df.net$receptor)\n }\n if (all(c(\"pval\") %in% colnames(df.net)) == FALSE) {\n df.net$pval <- rep(0, nrow(df.net))\n }\n df.net$prob <- df.net$score\n\n LR <- unique(df.net$interaction_name)\n cell.levels <- levels(object@idents)\n numCluster <- length(cell.levels)\n mat.prob.all <- array(0, dim = c(numCluster,numCluster,length(LR)))\n mat.pval.all <- mat.prob.all\n for (i in 1:length(LR)) {\n df.i <- df.net[df.net$interaction_name == LR[i], , drop = FALSE]\n mat.prob <- matrix(0, nrow = numCluster, ncol = numCluster)\n mat.pval <- mat.prob\n for (j in 1:nrow(df.i)) {\n idx.s <- which(df.i$source[j] == cell.levels)\n idx.t <- which(df.i$target[j] == cell.levels)\n mat.prob[idx.s, idx.t] <- df.i$prob[j]\n mat.pval[idx.s, idx.t] <- df.i$pval[j]\n }\n mat.prob.all[,,i] <- mat.prob\n mat.pval.all[,,i] <- mat.pval\n }\n\n dimnames(mat.prob.all) <- list(cell.levels, cell.levels, LR)\n dimnames(mat.pval.all) <- dimnames(mat.prob.all)\n net <- list(\"prob\" = mat.prob.all, \"pval\" = mat.pval.all)\n object@net <- net\n\n return(object)\n}\n\n#' Preprocessing multi-omics data and preparing the L-R database\n#'\n#' @param data.list a list consisting of multi-omics data (e.g., RNA & ADT)\n#' @param db one of the CellChatDB databases: CellChatDB.human, CellChatDB.mouse, CellChatDB.zebrafish\n#' @param do.sparse whether to use sparse format\n#' @export\n#'\npreProcMultiomics <- function(data.list, db, do.sparse = TRUE) {\n # normalize the data\n data.input.rna <- data.list[[1]]\n data.input.adt <- data.list[[2]]\n data.input.rna = data.input.rna/max(data.input.rna)\n data.input.adt = data.input.adt/max(data.input.adt)\n data.input.adt.temp = data.input.adt\n X = data.input.adt\n for (i in 1:nrow(X)) {\n data.input.adt.temp[i,] = (X[i,]-min(X[i,]))/(max(X[i,])-min(X[i,]))\n }\n data.input.adt[data.input.adt.temp < 0.5] <- 0\n if (do.sparse) {\n data.input = rbind(data.input.rna, as(data.input.adt, \"dgCMatrix\"))\n } else {\n data.input = rbind(as.matrix(data.input.rna), as.matrix(data.input.adt))\n }\n\n # create a new L-R database\n proteins <- rownames(data.input.adt)\n geneInfo.subset <- db$geneInfo[db$geneInfo$AntibodyName %in% proteins, ]\n proteins.nonmapping <- setdiff(proteins, geneInfo.subset$AntibodyName)\n if (length(proteins.nonmapping) > 0) {\n warning(cat(\"The following antibodies are not found in `CellChatDB$geneInfo$AntibodyName`: \", toString(proteins.nonmapping), \"! Please manually add them via the function `updateCellChatDB`. \\n\"))\n }\n out <- extractLRfromGenes(geneSet = geneInfo.subset$Symbol, db)\n LR.use <- out$LR.use\n idx <- match(LR.use$ligand, geneInfo.subset$Symbol)\n LR.use$ligand[!is.na(idx)] <- geneInfo.subset$AntibodyName[idx[!is.na(idx)]]\n idx <- match(LR.use$receptor, geneInfo.subset$Symbol)\n LR.use$receptor[!is.na(idx)] <- geneInfo.subset$AntibodyName[idx[!is.na(idx)]]\n\n db.use <- db\n db.use$interaction <- LR.use\n db.use$geneInfo <- dplyr::add_row(db.use$geneInfo, Symbol = geneInfo.subset$AntibodyName)\n\n return(list(data.input = data.input, db.use = db.use))\n}\n\n\n \n"], ["/CellChat/R/modeling.R", "\n#' Compute the communication probability/strength between any interacting cell groups\n#'\n#' To further speed up on large-scale datasets, USER can downsample the data using the function 'subset' from Seurat package (e.g., pbmc.small <- subset(pbmc, downsample = 500)), or using the function `sketchData` from CellChat, in particular for the large cell clusters;\n#'\n#'\n#' @param object CellChat object\n#' @param type Methods for computing the average gene expression per cell group. By default = \"triMean\", producing fewer but stronger interactions;\n#' When setting `type = \"truncatedMean\"`, a value should be assigned to 'trim', producing more interactions.\n#' @param trim the fraction (0 to 0.25) of observations to be trimmed from each end of x before the mean is computed\n#' @param LR.use A subset of ligand-receptor interactions used in inferring communication network\n#' @param raw.use Whether use the raw data (i.e., `object@data.signaling`) or the smoothed data (i.e., `object@data.smooth`).\n#' Set raw.use = FALSE to use the projected data when analyzing single-cell data with shallow sequencing depth because the projected data could help to reduce the dropout effects of signaling genes, in particular for possible zero expression of subunits of ligands/receptors.\n#' @param population.size Whether consider the proportion of cells in each group across all sequenced cells.\n#' Set population.size = FALSE if analyzing sorting-enriched single cells, to remove the potential artifact of population size.\n#' Set population.size = TRUE if analyzing unsorted single-cell transcriptomes, with the reason that abundant cell populations tend to send collectively stronger signals than the rare cell populations.\n#'\n#' Parameters for spatial data analysis:\n#' @param distance.use Whether to use distance constraints to compute communication probability. Setting `distance.use = TRUE` indicates that the cell-cell communication probability is inversely proportional to the computed distance.\n#' Setting `distance.use = FALSE` will only filter out interactions between spatially distant regions, but not add distance constraints.\n#' @param interaction.range The maximum interaction/diffusion length of ligands (Unit: microns). This hard threshold is used to filter out the connections between spatially distant regions\n#' @param scale.distance A scale or normalization factor for the spatial distances when setting `distance.use = TRUE`. For example, scale.distance equals 1, 0.1, 0.01, 0.001, 0.11, or 0.011. We choose this values such that the minimum value of the scaled distances is in [1,2]. This value is not necessary when setting `distance.use = FALSE`.\n#'\n#' When comparing communication across different CellChat objects, the same scale factor should be used. For a single CellChat analysis, different scale factors will not affect the ranking of the signaling based on their interaction strength.\n#'\n#' @param k.min The minimum number of interacting cell pairs required for defining spatially proximal cell groups.\n#' @param contact.dependent Whether using the `contact-dependent` manner for inference signaling, that is determining interacting cell pairs by requiring cells to be in direct membrane-membrane contact. By default `contact.dependent = TRUE` when inferring contact-dependent and juxtacrine signaling (that is \"Cell-Cell Contact\" signaling classified in CellChatDB$interaction$annotation).\n#' If only focusing on `Secreted Signaling`, the `contact-dependent` manner will be not used except for setting `contact.dependent.forced = TRUE`.\n#' @param contact.range The interaction range (Unit: microns) to restrict the contact-dependent signaling when `contact.dependent = TRUE`.\n#' For spatial transcriptomics in a single-cell resolution, `contact.range` is approximately equal to the estimated cell diameter (i.e., the cell center-to-center distance), which means that contact-dependent and juxtacrine signaling can only happens when the two cells are contact to each other.\n#'\n#' Typically, `contact.range = 10`, which is a typical human cell size. However, for low-resolution spatial data such as 10X visium, it should be the cell center-to-center distance (i.e., `contact.range = 100` for visium data). The function `computeCellDistance` can compute the center-to-center distance.\n#'\n#' @param contact.knn.k Number of neighbors to restrict the contact-dependent signaling within the neatest neighbors when `contact.dependent = TRUE`. By default, CellChat uses `contact.range` to restrict the contact-dependent signaling; however, users can also provide a value of `contact.knn.k`, in order to determine interacting cell pairs based on the k-nearest neighbors (knn).\n#' For 10X visium, contact.knn.k = 6. For other spatial technologies, this value may be hard to determine because the sequenced cells/spots are usually not regularly arranged.\n#' @param do.symmetric Whether converting the adjacent matrix into symmetric one when determining spatially proximal cell groups. Default is TRUE, indicating that if adj(i,j) or adj(j,i) is zero, then both are zeros.\n#'\n#' @param contact.dependent.forced Whether forcing to use the `contact-dependent` manner for inference signaling for all L-R pairs including secreted signaling. Users can set `contact.dependent.forced = TRUE` if also preferring interactions within a contact manner for `Secreted Signaling`.\n#'\n#' @param nboot Threshold of p-values\n#' @param seed.use Set a random seed. By default, set the seed to 1.\n#' @param Kh Parameter in Hill function\n#' @param n Parameter in Hill function\n#'\n#'\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @importFrom stats aggregate\n#' @importFrom Matrix crossprod\n#' @importFrom utils txtProgressBar setTxtProgressBar\n#'\n#' @return A CellChat object with updated slot 'net':\n#'\n#' object@net$prob is the inferred communication probability (strength) array, where the first, second and third dimensions represent a source, target and ligand-receptor pair, respectively.\n#'\n#' USER can access all the inferred cell-cell communications using the function 'subsetCommunication(object)', which returns a data frame.\n#'\n#' object@net$pval is the corresponding p-values of each interaction\n#'\n#' @export\n#'\ncomputeCommunProb <- function(object, type = c(\"triMean\", \"truncatedMean\",\"thresholdedMean\", \"median\"), trim = 0.1, LR.use = NULL, raw.use = TRUE, population.size = FALSE,\n distance.use = TRUE, interaction.range = 250, scale.distance = 0.01, k.min = 10, contact.dependent = TRUE, contact.range = NULL, contact.knn.k = NULL, contact.dependent.forced = FALSE, do.symmetric = TRUE,\n nboot = 100, seed.use = 1L, Kh = 0.5, n = 1) {\n type <- match.arg(type)\n cat(type, \"is used for calculating the average gene expression per cell group.\", \"\\n\")\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n thresholdedMean = function(x) thresholdedMean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n if (raw.use) {\n data <- as.matrix(object@data.signaling)\n } else {\n data <- as.matrix(object@data.smooth)\n }\n if (is.null(LR.use)) {\n pairLR.use <- object@LR$LRsig\n } else {\n if (length(unique(LR.use$annotation)) > 1) {\n LR.use$annotation <- factor(LR.use$annotation, levels = c(\"Secreted Signaling\",\"ECM-Receptor\", \"Non-protein Signaling\", \"Cell-Cell Contact\"))\n LR.use <- LR.use[order(LR.use$annotation), , drop = FALSE]\n LR.use$annotation <- as.character(LR.use$annotation)\n }\n pairLR.use <- LR.use\n }\n complex_input <- object@DB$complex\n cofactor_input <- object@DB$cofactor\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n\n ptm = Sys.time()\n\n pairLRsig <- pairLR.use\n group <- object@idents\n geneL <- as.character(pairLRsig$ligand)\n geneR <- as.character(pairLRsig$receptor)\n nLR <- nrow(pairLRsig)\n numCluster <- nlevels(group)\n if (numCluster != length(unique(group))) {\n stop(\"Please check `unique(object@idents)` and ensure that the factor levels are correct!\n You may need to drop unused levels using 'droplevels' function. e.g.,\n `meta$labels = droplevels(meta$labels, exclude = setdiff(levels(meta$labels),unique(meta$labels)))`\")\n }\n\n data.use <- data/max(data)\n nC <- ncol(data.use)\n\n # compute the average expression per group\n data.use.avg <- aggregate(t(data.use), list(group), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n colnames(data.use.avg) <- levels(group)\n # compute the expression of ligand or receptor\n dataLavg <- computeExpr_LR(geneL, data.use.avg, complex_input)\n dataRavg <- computeExpr_LR(geneR, data.use.avg, complex_input)\n # take account into the effect of co-activation and co-inhibition receptors\n dataRavg.co.A.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avg, pairLRsig, type = \"A\")\n dataRavg.co.I.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avg, pairLRsig, type = \"I\")\n dataRavg <- dataRavg * dataRavg.co.A.receptor/dataRavg.co.I.receptor\n\n dataLavg2 <- t(replicate(nrow(dataLavg), as.numeric(table(group))/nC))\n dataRavg2 <- dataLavg2\n\n # compute the expression of agonist and antagonist\n index.agonist <- which(!is.na(pairLRsig$agonist) & pairLRsig$agonist != \"\")\n index.antagonist <- which(!is.na(pairLRsig$antagonist) & pairLRsig$antagonist != \"\")\n # quantify the communication probability\n\n # compute the spatial constraint\n if (object@options$datatype != \"RNA\") {\n data.spatial <- object@images$coordinates\n if (\"spatial.factors\" %in% names(object@images)) {\n ratio <- object@images$spatial.factors$ratio\n tol <- object@images$spatial.factors$tol\n } else {\n stop(\"`object@images$spatial.factors` is missing. Please update the object via `updateCellChat`! \\n\")\n }\n\n meta.t = data.frame(group = group, samples = object@meta$samples, row.names = rownames(object@meta))\n res <- computeRegionDistance(coordinates = data.spatial, meta = meta.t, interaction.range = interaction.range, ratio = ratio, tol = tol, k.min = k.min, contact.dependent = contact.dependent, contact.range = contact.range, contact.knn.k = contact.knn.k)\n d.spatial <- res$d.spatial # NaN if no nearby cell pairs\n adj.contact <- res$adj.contact # zeros if no nearby cell pairs\n if (distance.use) {\n print(paste0('>>> Run CellChat on spatial transcriptomics data using distances as constraints of the computed communication probability <<< [', Sys.time(),']'))\n d.spatial <- d.spatial * scale.distance\n diag(d.spatial) <- NaN\n d.min <- min(d.spatial, na.rm = TRUE)\n if (d.min < 1) {\n cat(\"The suggested minimum value of scaled distances is in [1,2], and the calculated value here is \", d.min,\"\\n\")\n stop(\"Please increase the value of `scale.distance` and use a value that is slighly smaller than \", format(1/d.min, digits = 2) ,\"\\n\")\n }\n P.spatial <- 1/d.spatial\n P.spatial[is.na(d.spatial)] <- 0\n diag(P.spatial) <- max(P.spatial) # if this value is 1, the self-connections will have more larger weight.\n d.spatial <- d.spatial/scale.distance # This is only for saving the data\n } else {\n print(paste0('>>> Run CellChat on spatial transcriptomics data without distance values as constraints of the computed communication probability <<< [', Sys.time(),']'))\n P.spatial <- matrix(1, nrow = numCluster, ncol = numCluster)\n P.spatial[is.na(d.spatial)] <- 0 # diagonal is 1\n }\n\n } else {\n print(paste0('>>> Run CellChat on sc/snRNA-seq data <<< [', Sys.time(),']'))\n d.spatial <- matrix(NaN, nrow = numCluster, ncol = numCluster)\n P.spatial <- matrix(1, nrow = numCluster, ncol = numCluster)\n adj.contact <- matrix(1, nrow = numCluster, ncol = numCluster)\n contact.dependent = FALSE; contact.dependent.forced = FALSE; contact.range = NULL; contact.knn.k = NULL;\n distance.use = NULL; interaction.range = NULL; ratio = NULL; tol = NULL; k.min = NULL;\n }\n\n if (object@options$datatype == \"RNA\") {\n nLR1 <- nLR\n } else {\n if (contact.dependent.forced == TRUE) {\n cat(\"Force to run CellChat in a `contact-dependent` manner for all L-R pairs including secreted signaling.\\n\")\n P.spatial <- P.spatial * adj.contact\n nLR1 <- nLR\n } else { # contact.dependent.forced == F\n if (contact.dependent == TRUE && length(unique(pairLRsig$annotation)) > 0) {\n if (all(unique(pairLRsig$annotation) %in% c(\"Cell-Cell Contact\"))) {\n cat(\"All the input L-R pairs are `Cell-Cell Contact` signaling. Run CellChat in a contact-dependent manner. \\n\")\n P.spatial <- P.spatial * adj.contact\n nLR1 <- nLR\n } else if (all(unique(pairLRsig$annotation) %in% c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\"))) {\n cat(\"Molecules of the input L-R pairs are diffusible. Run CellChat in a diffusion manner based on the `interaction.range`.\\n\")\n nLR1 <- nLR\n } else {\n cat(\"The input L-R pairs have both secreted signaling and contact-dependent signaling. Run CellChat in a contact-dependent manner for `Cell-Cell Contact` signaling, and in a diffusion manner based on the `interaction.range` for other L-R pairs. \\n\")\n nLR1 <- max(which(pairLRsig$annotation %in% c(\"Secreted Signaling\", \"ECM-Receptor\", \"Non-protein Signaling\")))\n }\n } else { # contact.dependent == F or there is no `annotation` column in the database\n cat(\"Run CellChat in a diffusion manner based on the `interaction.range` for all L-R pairs. Setting `contact.dependent = TRUE` if preferring a contact-dependent manner for `Cell-Cell Contact` signaling. \\n\")\n nLR1 <- nLR\n }\n }\n }\n\n Prob <- array(0, dim = c(numCluster,numCluster,nLR))\n Pval <- array(0, dim = c(numCluster,numCluster,nLR))\n\n set.seed(seed.use)\n permutation <- replicate(nboot, sample.int(nC, size = nC))\n data.use.avg.boot <- my.sapply(\n X = 1:nboot,\n FUN = function(nE) {\n groupboot <- group[permutation[, nE]]\n data.use.avgB <- aggregate(t(data.use), list(groupboot), FUN = FunMean)\n data.use.avgB <- t(data.use.avgB[,-1])\n return(data.use.avgB)\n },\n simplify = FALSE\n )\n pb <- txtProgressBar(min = 0, max = nLR, style = 3, file = stderr())\n\n for (i in 1:nLR) {\n # ligand/receptor\n dataLR <- Matrix::crossprod(matrix(dataLavg[i,], nrow = 1), matrix(dataRavg[i,], nrow = 1))\n P1 <- dataLR^n/(Kh^n + dataLR^n)\n P1_Pspatial <- P1*P.spatial\n if (sum(P1_Pspatial) == 0) {\n Pnull = P1_Pspatial\n Prob[ , , i] <- Pnull\n p = 1\n Pval[, , i] <- matrix(p, nrow = numCluster, ncol = numCluster, byrow = FALSE)\n } else {\n if (i > nLR1) {\n P.spatial <- P.spatial * adj.contact\n }\n # agonist and antagonist\n if (is.element(i, index.agonist)) {\n data.agonist <- computeExpr_agonist(data.use = data.use.avg, pairLRsig, cofactor_input, index.agonist = i, Kh = Kh, n = n)\n P2 <- Matrix::crossprod(matrix(data.agonist, nrow = 1))\n } else {\n P2 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n if (is.element(i, index.antagonist)) {\n data.antagonist <- computeExpr_antagonist(data.use = data.use.avg, pairLRsig, cofactor_input, index.antagonist = i, Kh = Kh, n = n)\n P3 <- Matrix::crossprod(matrix(data.antagonist, nrow = 1))\n } else {\n P3 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n # number of cells\n if (population.size) {\n P4 <- Matrix::crossprod(matrix(dataLavg2[i,], nrow = 1), matrix(dataRavg2[i,], nrow = 1))\n } else {\n P4 <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n # Pnull = P1*P2*P3*P4\n Pnull = P1*P2*P3*P4*P.spatial\n Prob[ , , i] <- Pnull\n\n Pnull <- as.vector(Pnull)\n\n #Pboot <- foreach(nE = 1:nboot) %dopar% {\n Pboot <- sapply(\n X = 1:nboot,\n FUN = function(nE) {\n data.use.avgB <- data.use.avg.boot[[nE]]\n dataLavgB <- computeExpr_LR(geneL[i], data.use.avgB, complex_input)\n dataRavgB <- computeExpr_LR(geneR[i], data.use.avgB, complex_input)\n # take account into the effect of co-activation and co-inhibition receptors\n dataRavgB.co.A.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avgB, pairLRsig[i, , drop = FALSE], type = \"A\")\n dataRavgB.co.I.receptor <- computeExpr_coreceptor(cofactor_input, data.use.avgB, pairLRsig[i, , drop = FALSE], type = \"I\")\n dataRavgB <- dataRavgB * dataRavgB.co.A.receptor/dataRavgB.co.I.receptor\n dataLRB = Matrix::crossprod(dataLavgB, dataRavgB)\n P1.boot <- dataLRB^n/(Kh^n + dataLRB^n)\n # agonist and antagonist\n if (is.element(i, index.agonist)) {\n data.agonist <- computeExpr_agonist(data.use = data.use.avgB, pairLRsig, cofactor_input, index.agonist = i, Kh = Kh, n = n)\n P2.boot <- Matrix::crossprod(matrix(data.agonist, nrow = 1))\n } else {\n P2.boot <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n if (is.element(i, index.antagonist)) {\n data.antagonist <- computeExpr_antagonist(data.use = data.use.avgB, pairLRsig, cofactor_input, index.antagonist = i, Kh = Kh, n= n)\n P3.boot <- Matrix::crossprod(matrix(data.antagonist, nrow = 1))\n } else {\n P3.boot <- matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n if (population.size) {\n groupboot <- group[permutation[, nE]]\n dataLavg2B <- as.numeric(table(groupboot))/nC\n dataLavg2B <- matrix(dataLavg2B, nrow = 1)\n dataRavg2B <- dataLavg2B\n P4.boot = Matrix::crossprod(dataLavg2B, dataRavg2B)\n } else {\n P4.boot = matrix(1, nrow = numCluster, ncol = numCluster)\n }\n\n # Pboot = P1.boot*P2.boot*P3.boot*P4.boot\n Pboot = P1.boot*P2.boot*P3.boot*P4.boot*P.spatial\n return(as.vector(Pboot))\n }\n )\n Pboot <- matrix(unlist(Pboot), nrow=length(Pnull), ncol = nboot, byrow = FALSE)\n nReject <- rowSums(Pboot - Pnull > 0)\n p = nReject/nboot\n Pval[, , i] <- matrix(p, nrow = numCluster, ncol = numCluster, byrow = FALSE)\n }\n setTxtProgressBar(pb = pb, value = i)\n }\n close(con = pb)\n Pval[Prob == 0] <- 1\n dimnames(Prob) <- list(levels(group), levels(group), rownames(pairLRsig))\n dimnames(Pval) <- dimnames(Prob)\n net <- list(\"prob\" = Prob, \"pval\" = Pval)\n execution.time = Sys.time() - ptm\n object@options$run.time <- as.numeric(execution.time, units = \"secs\")\n\n object@options$parameter <- list(type.mean = type, trim = trim, raw.use = raw.use, population.size = population.size, nboot = nboot, seed.use = seed.use, Kh = Kh, n = n,\n distance.use = distance.use, interaction.range = interaction.range, ratio = ratio, tol = tol, k.min = k.min,\n contact.dependent = contact.dependent, contact.range = contact.range, contact.knn.k = contact.knn.k, contact.dependent.forced = contact.dependent.forced\n )\n if (object@options$datatype != \"RNA\") {\n object@images$distance <- d.spatial\n }\n object@net <- net\n print(paste0('>>> CellChat inference is done. Parameter values are stored in `object@options$parameter` <<< [', Sys.time(),']'))\n return(object)\n}\n\n\n#' Compute the communication probability on signaling pathway level by summarizing all related ligands/receptors\n#'\n#' @param object CellChat object\n#' @param net A list from object@net; If net = NULL, net = object@net\n#' @param pairLR.use A dataframe giving the ligand-receptor interactions; If pairLR.use = NULL, pairLR.use = object@LR$LRsig\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @return A CellChat object with updated slot 'netP':\n#'\n#' object@netP$prob is the communication probability array on signaling pathway level; USER can convert this array to a data frame using the function 'reshape2::melt()',\n#'\n#' e.g., `df.netP <- reshape2::melt(object@netP$prob, value.name = \"prob\"); colnames(df.netP)[1:3] <- c(\"source\",\"target\",\"pathway_name\")` or access all significant interactions using the function \\code{\\link{subsetCommunication}}\n#'\n#' object@netP$pathways list all the signaling pathways with significant communications.\n#'\n#' From version >= 1.1.0, pathways are ordered based on the total communication probabilities. NB: pathways with small total communication probabilities might be also very important since they might be specifically activated between only few cell types.\n#'\n#' @export\n#'\ncomputeCommunProbPathway <- function(object = NULL, net = NULL, pairLR.use = NULL, thresh = 0.05) {\n if (is.null(net)) {\n net <- object@net\n }\n if (is.null(pairLR.use)) {\n pairLR.use <- object@LR$LRsig\n }\n prob <- net$prob\n prob[net$pval > thresh] <- 0\n\n LR <- dimnames(prob)[[3]]\n LR.sig <- LR[apply(prob, 3, sum) != 0]\n\n pathways <- unique(pairLR.use$pathway_name)\n group <- factor(pairLR.use$pathway_name, levels = pathways)\n prob.pathways <- aperm(apply(prob, c(1, 2), by, group, sum), c(2, 3, 1))\n pathways.sig <- pathways[apply(prob.pathways, 3, sum) != 0]\n prob.pathways.sig <- prob.pathways[,,pathways.sig, drop = FALSE]\n idx <- sort(apply(prob.pathways.sig, 3, sum), decreasing=TRUE, index.return = TRUE)$ix\n pathways.sig <- pathways.sig[idx]\n prob.pathways.sig <- prob.pathways.sig[, , idx]\n\n if (is.null(object)) {\n netP = list(pathways = pathways.sig, prob = prob.pathways.sig)\n return(netP)\n } else {\n object@net$LRs <- LR.sig\n object@netP$pathways <- pathways.sig\n object@netP$prob <- prob.pathways.sig\n return(object)\n }\n}\n\n\n#' Calculate the aggregated network by counting the number of links or summarizing the communication probability\n#'\n#' @param object CellChat object\n#' @param sources.use,targets.use,signaling,pairLR.use Please check the description in function \\code{\\link{subsetCommunication}}\n#' @param remove.isolate whether removing the isolate cell groups without any interactions when applying \\code{\\link{subsetCommunication}}\n#' @param thresh threshold of the p-value for determining significant interaction\n#' @param return.object whether return an updated CellChat object\n#' @importFrom dplyr group_by summarize groups\n#' @importFrom stringr str_split\n#'\n#' @return Return an updated CellChat object:\n#'\n#' `object@net$count` is a matrix: rows and columns are sources and targets respectively, and elements are the number of interactions between any two cell groups. USER can convert a matrix to a data frame using the function `reshape2::melt()`\n#'\n#' `object@net$weight` is also a matrix containing the interaction weights between any two cell groups\n#'\n#' `object@net$sum` is deprecated. Use `object@net$weight`\n#'\n#' @export\n#'\naggregateNet <- function(object, sources.use = NULL, targets.use = NULL, signaling = NULL, pairLR.use = NULL, remove.isolate = TRUE, thresh = 0.05, return.object = TRUE) {\n net <- object@net\n if (is.null(sources.use) & is.null(targets.use) & is.null(signaling) & is.null(pairLR.use)) {\n prob <- net$prob\n pval <- net$pval\n pval[prob == 0] <- 1\n prob[pval >= thresh] <- 0\n net$count <- apply(prob > 0, c(1,2), sum)\n net$weight <- apply(prob, c(1,2), sum)\n net$weight[is.na(net$weight)] <- 0\n net$count[is.na(net$count)] <- 0\n } else {\n df.net <- subsetCommunication(object, slot.name = \"net\",\n sources.use = sources.use, targets.use = targets.use,\n signaling = signaling,\n pairLR.use = pairLR.use,\n thresh = thresh)\n df.net$source_target <- paste(df.net$source, df.net$target, sep = \"_\")\n df.net2 <- df.net %>% group_by(source_target) %>% summarize(count = n(), .groups = 'drop')\n df.net3 <- df.net %>% group_by(source_target) %>% summarize(prob = sum(prob), .groups = 'drop')\n df.net2$prob <- df.net3$prob\n a <- stringr::str_split(df.net2$source_target, \"_\", simplify = T)\n df.net2$source <- as.character(a[, 1])\n df.net2$target <- as.character(a[, 2])\n cells.level <- levels(object@idents)\n if (remove.isolate) {\n message(\"Isolate cell groups without any interactions are removed. To block it, set `remove.isolate = FALSE`\")\n df.net2$source <- factor(df.net2$source, levels = cells.level[cells.level %in% unique(df.net2$source)])\n df.net2$target <- factor(df.net2$target, levels = cells.level[cells.level %in% unique(df.net2$target)])\n } else {\n df.net2$source <- factor(df.net2$source, levels = cells.level)\n df.net2$target <- factor(df.net2$target, levels = cells.level)\n }\n\n count <- tapply(df.net2[[\"count\"]], list(df.net2[[\"source\"]], df.net2[[\"target\"]]), sum)\n prob <- tapply(df.net2[[\"prob\"]], list(df.net2[[\"source\"]], df.net2[[\"target\"]]), sum)\n net$count <- count\n net$weight <- prob\n net$weight[is.na(net$weight)] <- 0\n net$count[is.na(net$count)] <- 0\n }\n if (return.object) {\n object@net <- net\n return(object)\n } else {\n return(net)\n }\n\n}\n\n\n#' Compute averaged expression values for each cell group\n#'\n#' @param object CellChat object\n#' @param features a char vector giving the used features. default use all features\n#' @param group.by cell group information; default is `object@idents` when input is a single object and `object@idents$joint` when input is a merged object; otherwise it should be one of the column names of the meta slot\n#' @param type methods for computing the average gene expression per cell group.\n#'\n#' By default = \"triMean\", defined as a weighted average of the distribution's median and its two quartiles (https://en.wikipedia.org/wiki/Trimean);\n#'\n#' When setting `type = \"truncatedMean\"`, a value should be assigned to 'trim'. See the function `base::mean`.\n#'\n#' @param trim the fraction (0 to 0.25) of observations to be trimmed from each end of x before the mean is computed.\n#' @param slot.name the data in the slot.name to use\n#' @param data.use a customed data matrix. Default: data.use = NULL and the expression matrix in the 'slot.name' is used\n#'\n#' @return Returns a matrix with genes as rows, cell groups as columns.\n\n#' @export\n#'\ncomputeAveExpr <- function(object, features = NULL, group.by = NULL, type = c(\"triMean\", \"truncatedMean\", \"median\"), trim = NULL,\n slot.name = c(\"data.signaling\", \"data\"), data.use = NULL) {\n type <- match.arg(type)\n slot.name <- match.arg(slot.name)\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n if (is.null(data.use)) {\n data.use <- slot(object, slot.name)\n }\n if (is.null(features)) {\n features.use <- row.names(data.use)\n } else {\n features.use <- intersect(features, row.names(data.use))\n }\n data.use <- data.use[features.use, , drop = FALSE]\n data.use <- as.matrix(data.use)\n\n if (is.null(group.by)) {\n labels <- object@idents\n if (!is.factor(labels)) {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n # compute the average expression per group\n data.use.avg <- aggregate(t(data.use), list(labels), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n rownames(data.use.avg) <- features.use\n colnames(data.use.avg) <- levels(labels)\n return(data.use.avg)\n}\n\n\n\n#' Compute the expression of complex in individual cells using geometric mean\n#' @param complex_input the complex_input from CellChatDB\n#' @param data.use data matrix (row are genes and columns are cells or cell groups)\n#' @param complex the names of complex\n#' @return\n#' @importFrom dplyr select starts_with\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @export\ncomputeExpr_complex <- function(complex_input, data.use, complex) {\n Rsubunits <- complex_input[complex,] %>% dplyr::select(starts_with(\"subunit\"))\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n data.complex = my.sapply(\n X = 1:nrow(Rsubunits),\n FUN = function(x) {\n RsubunitsV <- unlist(Rsubunits[x,], use.names = F)\n RsubunitsV <- RsubunitsV[RsubunitsV != \"\"]\n return(geometricMean(data.use[RsubunitsV, , drop = FALSE]))\n }\n )\n data.complex <- t(data.complex)\n return(data.complex)\n}\n\n# Compute the average expression of complex per cell group using geometric mean\n# @param complex_input the complex_input from CellChatDB\n# @param data.use data matrix (rows are genes and columns are cells)\n# @param complex the names of complex\n# @param group a factor defining the cell groups\n# @param FunMean the function for computing mean expression per group\n# @return\n# @importFrom dplyr select starts_with\n# @importFrom future nbrOfWorkers\n# @importFrom future.apply future_sapply\n# @importFrom pbapply pbsapply\n# #' @export\n.computeExprGroup_complex <- function(complex_input, data.use, complex, group, FunMean) {\n Rsubunits <- complex_input[complex,] %>% dplyr::select(starts_with(\"subunit\"))\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n data.complex = my.sapply(\n X = 1:nrow(Rsubunits),\n FUN = function(x) {\n RsubunitsV <- unlist(Rsubunits[x,], use.names = F)\n RsubunitsV <- RsubunitsV[RsubunitsV != \"\"]\n RsubunitsV <- intersect(RsubunitsV, rownames(data.use))\n if (length(RsubunitsV) > 1) {\n data.avg <- aggregate(t(data.use[RsubunitsV, ,drop = FALSE]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n } else if (length(RsubunitsV) == 1) {\n data.avg <- aggregate(matrix(data.use[RsubunitsV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n } else {\n data.avg = matrix(0, nrow = 1, ncol = length(unique(group)))\n }\n return(geometricMean(data.avg))\n }\n )\n data.complex <- t(data.complex)\n return(data.complex)\n}\n\n#' Compute the expression of ligands or receptors using geometric mean\n#' @param geneLR a char vector giving a set of ligands or receptors\n#' @param data.use data matrix (row are genes and columns are cells or cell groups)\n#' @param complex_input the complex_input from CellChatDB\n# #' @param group a factor defining the cell groups; If NULL, compute the expression of ligands or receptors in individual cells; otherwise, compute the average expression of ligands or receptors per cell group\n# #' @param FunMean the function for computing average expression per cell group\n#' @return\n#' @export\ncomputeExpr_LR <- function(geneLR, data.use, complex_input){\n nLR <- length(geneLR)\n numCluster <- ncol(data.use)\n index.singleL <- which(geneLR %in% rownames(data.use))\n dataL1avg <- data.use[geneLR[index.singleL],]\n dataLavg <- matrix(nrow = nLR, ncol = numCluster)\n dataLavg[index.singleL,] <- dataL1avg\n index.complexL <- setdiff(1:nLR, index.singleL)\n if (length(index.complexL) > 0) {\n complex <- geneLR[index.complexL]\n data.complex <- computeExpr_complex(complex_input, data.use, complex)\n dataLavg[index.complexL,] <- data.complex\n }\n return(dataLavg)\n}\n\n\n#' Modeling the effect of coreceptor on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig a data frame giving ligand-receptor interactions\n#' @param type when type == \"A\", computing expression of co-activation receptor; when type == \"I\", computing expression of co-inhibition receptor.\n#' @return\n#' @importFrom future nbrOfWorkers\n#' @importFrom future.apply future_sapply\n#' @importFrom pbapply pbsapply\n#' @export\ncomputeExpr_coreceptor <- function(cofactor_input, data.use, pairLRsig, type = c(\"A\", \"I\")) {\n type <- match.arg(type)\n if (type == \"A\") {\n coreceptor.all = pairLRsig$co_A_receptor\n } else if (type == \"I\"){\n coreceptor.all = pairLRsig$co_I_receptor\n }\n index.coreceptor <- which(!is.na(coreceptor.all) & coreceptor.all != \"\")\n if (length(index.coreceptor) > 0) {\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = sapply,\n no = future.apply::future_sapply\n )\n coreceptor <- coreceptor.all[index.coreceptor]\n coreceptor.ind <- cofactor_input[coreceptor, grepl(\"cofactor\" , colnames(cofactor_input) )]\n data.coreceptor.ind = my.sapply(\n X = 1:nrow(coreceptor.ind),\n FUN = function(x) {\n coreceptor.indV <- unlist(coreceptor.ind[x,], use.names = F)\n coreceptor.indV <- coreceptor.indV[coreceptor.indV != \"\"]\n coreceptor.indV <- intersect(coreceptor.indV, rownames(data.use))\n if (length(coreceptor.indV) == 1) {\n return(1 + data.use[coreceptor.indV, ])\n } else if (length(coreceptor.indV) > 1) {\n return(apply(1 + data.use[coreceptor.indV, ], 2, prod))\n } else {\n return(matrix(1, nrow = 1, ncol = ncol(data.use)))\n }\n }\n )\n data.coreceptor.ind <- t(data.coreceptor.ind)\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = ncol(data.use))\n data.coreceptor[index.coreceptor,] <- data.coreceptor.ind\n } else {\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = ncol(data.use))\n }\n return(data.coreceptor)\n}\n\n# Modeling the effect of coreceptor on the ligand-receptor interaction\n#\n# @param data.use data matrix\n# @param cofactor_input the cofactor_input from CellChatDB\n# @param pairLRsig a data frame giving ligand-receptor interactions\n# @param type when type == \"A\", computing expression of co-activation receptor; when type == \"I\", computing expression of co-inhibition receptor.\n# @param group a factor defining the cell groups\n# @param FunMean the function for computing mean expression per group\n# @return\n# @importFrom future nbrOfWorkers\n# @importFrom future.apply future_sapply\n# @importFrom pbapply pbsapply\n# #' @export\n.computeExprGroup_coreceptor <- function(cofactor_input, data.use, pairLRsig, type = c(\"A\", \"I\"), group, FunMean) {\n type <- match.arg(type)\n if (type == \"A\") {\n coreceptor.all = pairLRsig$co_A_receptor\n } else if (type == \"I\"){\n coreceptor.all = pairLRsig$co_I_receptor\n }\n index.coreceptor <- which(!is.na(coreceptor.all) & coreceptor.all != \"\")\n if (length(index.coreceptor) > 0) {\n my.sapply <- ifelse(\n test = future::nbrOfWorkers() == 1,\n yes = pbapply::pbsapply,\n no = future.apply::future_sapply\n )\n coreceptor <- coreceptor.all[index.coreceptor]\n coreceptor.ind <- cofactor_input[coreceptor, grepl(\"cofactor\" , colnames(cofactor_input) )]\n data.coreceptor.ind = my.sapply(\n X = 1:nrow(coreceptor.ind),\n FUN = function(x) {\n coreceptor.indV <- unlist(coreceptor.ind[x,], use.names = F)\n coreceptor.indV <- coreceptor.indV[coreceptor.indV != \"\"]\n coreceptor.indV <- intersect(coreceptor.indV, rownames(data.use))\n if (length(coreceptor.indV) > 1) {\n data.avg <- aggregate(t(data.use[coreceptor.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n return(apply(1 + data.avg, 2, prod))\n # return(1 + apply(data.avg, 2, mean))\n } else if (length(coreceptor.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[coreceptor.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n return(1 + data.avg)\n } else {\n return(matrix(1, nrow = 1, ncol = length(unique(group))))\n }\n }\n )\n data.coreceptor.ind <- t(data.coreceptor.ind)\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = length(unique(group)))\n data.coreceptor[index.coreceptor,] <- data.coreceptor.ind\n } else {\n data.coreceptor <- matrix(1, nrow = length(coreceptor.all), ncol = length(unique(group)))\n }\n\n return(data.coreceptor)\n}\n\n#' Modeling the effect of agonist on the ligand-receptor interaction\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n#' @param group a factor defining the cell groups\n#' @param index.agonist the index of agonist in the database\n#' @param Kh a parameter in Hill function\n#' @param FunMean the function for computing mean expression per group\n#' @param n Hill coefficient\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExprGroup_agonist <- function(data.use, pairLRsig, cofactor_input, group, index.agonist, Kh, FunMean, n) {\n agonist <- pairLRsig$agonist[index.agonist]\n agonist.ind <- cofactor_input[agonist, grepl(\"cofactor\" , colnames(cofactor_input))]\n agonist.indV <- unlist(agonist.ind, use.names = F)\n agonist.indV <- agonist.indV[agonist.indV != \"\"]\n agonist.indV <- intersect(agonist.indV, rownames(data.use))\n if (length(agonist.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[agonist.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.agonist <- 1 + data.avg^n/(Kh^n + data.avg^n)\n } else if (length(agonist.indV) > 1) {\n data.avg <- aggregate(t(data.use[agonist.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.agonist <- apply(1 + data.avg^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n data.agonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n }\n return(data.agonist)\n}\n\n#' Modeling the effect of antagonist on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n#' @param group a factor defining the cell groups\n#' @param index.antagonist the index of antagonist in the database\n#' @param Kh a parameter in Hill function\n#' @param n Hill coefficient\n#' @param FunMean the function for computing mean expression per group\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExprGroup_antagonist <- function(data.use, pairLRsig, cofactor_input, group, index.antagonist, Kh, FunMean, n) {\n antagonist <- pairLRsig$antagonist[index.antagonist]\n antagonist.ind <- cofactor_input[antagonist, grepl( \"cofactor\" , colnames(cofactor_input) )]\n antagonist.indV <- unlist(antagonist.ind, use.names = F)\n antagonist.indV <- antagonist.indV[antagonist.indV != \"\"]\n antagonist.indV <- intersect(antagonist.indV, rownames(data.use))\n if (length(antagonist.indV) == 1) {\n data.avg <- aggregate(matrix(data.use[antagonist.indV,], ncol = 1), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.antagonist <- Kh^n/(Kh^n + data.avg^n)\n } else if (length(antagonist.indV) > 1) {\n data.avg <- aggregate(t(data.use[antagonist.indV,]), list(group), FUN = FunMean)\n data.avg <- t(data.avg[,-1])\n data.antagonist <- apply(Kh^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n data.antagonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n }\n return(data.antagonist)\n}\n\n\n#' Modeling the effect of agonist on the ligand-receptor interaction\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n# #' @param group a factor defining the cell groups\n#' @param index.agonist the index of agonist in the database\n#' @param Kh a parameter in Hill function\n# #' @param FunMean the function for computing mean expression per group\n#' @param n Hill coefficient\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExpr_agonist <- function(data.use, pairLRsig, cofactor_input, index.agonist, Kh, n) {\n agonist <- pairLRsig$agonist[index.agonist]\n agonist.ind <- cofactor_input[agonist, grepl(\"cofactor\" , colnames(cofactor_input))]\n agonist.indV <- unlist(agonist.ind, use.names = F)\n agonist.indV <- agonist.indV[agonist.indV != \"\"]\n agonist.indV <- intersect(agonist.indV, rownames(data.use))\n if (length(agonist.indV) == 1) {\n # data.avg <- aggregate(matrix(data.use[agonist.indV,], ncol = 1), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[agonist.indV,, drop = FALSE]\n data.agonist <- 1 + data.avg^n/(Kh^n + data.avg^n)\n } else if (length(agonist.indV) > 1) {\n # data.avg <- aggregate(t(data.use[agonist.indV,]), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[agonist.indV,, drop = FALSE]\n data.agonist <- apply(1 + data.avg^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n # data.agonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n data.agonist = matrix(1, nrow = 1, ncol = ncol(data.use))\n }\n return(data.agonist)\n}\n\n#' Modeling the effect of antagonist on the ligand-receptor interaction\n#'\n#' @param data.use data matrix\n#' @param cofactor_input the cofactor_input from CellChatDB\n#' @param pairLRsig the L-R interactions\n# #' @param group a factor defining the cell groups\n#' @param index.antagonist the index of antagonist in the database\n#' @param Kh a parameter in Hill function\n#' @param n Hill coefficient\n# #' @param FunMean the function for computing mean expression per group\n#' @return\n#' @export\n#' @importFrom stats aggregate\ncomputeExpr_antagonist <- function(data.use, pairLRsig, cofactor_input, index.antagonist, Kh, n) {\n antagonist <- pairLRsig$antagonist[index.antagonist]\n antagonist.ind <- cofactor_input[antagonist, grepl( \"cofactor\" , colnames(cofactor_input) )]\n antagonist.indV <- unlist(antagonist.ind, use.names = F)\n antagonist.indV <- antagonist.indV[antagonist.indV != \"\"]\n antagonist.indV <- intersect(antagonist.indV, rownames(data.use))\n if (length(antagonist.indV) == 1) {\n # data.avg <- aggregate(matrix(data.use[antagonist.indV,], ncol = 1), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[antagonist.indV,, drop = FALSE]\n data.antagonist <- Kh^n/(Kh^n + data.avg^n)\n } else if (length(antagonist.indV) > 1) {\n # data.avg <- aggregate(t(data.use[antagonist.indV,]), list(group), FUN = FunMean)\n # data.avg <- t(data.avg[,-1])\n data.avg <- data.use[antagonist.indV,, drop = FALSE]\n data.antagonist <- apply(Kh^n/(Kh^n + data.avg^n), 2, prod)\n } else {\n # data.antagonist = matrix(1, nrow = 1, ncol = length(unique(group)))\n data.antagonist = matrix(1, nrow = 1, ncol = ncol(data.use))\n }\n return(data.antagonist)\n}\n\n\n#' Compute the geometric mean\n#' @param x a numeric vector\n#' @param na.rm whether remove na\n#' @return\n#' @export\ngeometricMean <- function(x,na.rm=TRUE){\n if (is.null(nrow(x))) {\n exp(mean(log(x),na.rm=na.rm))\n } else {\n exp(apply(log(x),2,mean,na.rm=na.rm))\n }\n}\n\n\n#' Compute the Tukey's trimean\n#' @param x a numeric vector\n#' @param na.rm whether remove na\n#' @return\n#' @importFrom stats quantile\n#' @export\ntriMean <- function(x, na.rm = TRUE) {\n mean(stats::quantile(x, probs = c(0.25, 0.50, 0.50, 0.75), na.rm = na.rm))\n}\n\n#' Compute the average expression per cell group when the percent of expressing cells per cell group larger than a threshold\n#' @param x a numeric vector\n#' @param trim the percent of expressing cells per cell group to be considered as zero\n#' @param na.rm whether remove na\n#' @return\n#' @importFrom Matrix nnzero\n# #' @export\nthresholdedMean <- function(x, trim = 0.1, na.rm = TRUE) {\n percent <- Matrix::nnzero(x)/length(x)\n if (percent < trim) {\n return(0)\n } else {\n return(mean(x, na.rm = na.rm))\n }\n}\n\n#' Filter cell-cell communication if there are only few number of cells in certain cell groups or inconsistent cell-cell communication across samples\n#'\n#' @param object CellChat object\n#' @param min.cells The minmum number of cells required in each cell group for cell-cell communication\n#' @param min.samples The minmum number of samples required for consistent cell-cell communication across samples (that is an interaction present in at least `min.samples` samples) when mutiple samples/replicates/batches are merged as an input for CellChat analysis.\n#' @param rare.keep Whether to keep the interactions associated with the rare populations when min.samples >= 2. When a rare population is identified in the merged samples (say 15 cells in this rare population from two samples), it is likely to filter out the interactions associated with this rare population when setting min.samples >= 2. Setting `rare.keep = TRUE` to retain the identified interactions associated with this rare population.\n#' @param nonFilter.keep Whether to keep the non-filtered cell-cell communication in the CellChat object. This is useful for avoiding re-running `computeCommunProb` if you want to adjust the parameters when running `filterCommunication`.\n#' @return CellChat object with an updated slot net\n#' @export\n#'\nfilterCommunication <- function(object, min.cells = 10, min.samples = NULL, rare.keep = FALSE, nonFilter.keep = FALSE) {\n net <- object@net\n if (nonFilter.keep == TRUE) {\n cat(\"The non-filtered cell-cell communication is stored in `object@net$prob.nonFilter` and `object@net$pval.nonFilter`. \\n\")\n object@net$prob.nonFilter <- net$prob\n object@net$pval.nonFilter <- net$pval\n }\n num.interaction0 <- sum(net$prob > 0)\n cell.excludes <- which(as.numeric(table(object@idents)) <= min.cells)\n if (length(cell.excludes) > 0) {\n cat(\"The cell-cell communication related with the following cell groups are excluded due to the few number of cells: \", toString(levels(object@idents)[cell.excludes]), \"!\",'\\t')\n net$prob[cell.excludes,,] <- 0\n net$prob[,cell.excludes,] <- 0\n num.interaction1 <- sum(net$prob > 0)\n pct.dicrease <- scales::percent((num.interaction0-num.interaction1)/num.interaction0, accuracy = .1)\n cat(paste0(pct.dicrease, \" interactions are removed!\",'\\n'))\n } else {\n num.interaction1 <- num.interaction0\n }\n\n sample.info <- object@meta$samples\n sample.id <- levels(sample.info)\n if (is.null(min.samples)) {\n min.samples <- 1\n } else if (min.samples > length(sample.id)) {\n stop(paste0(\"There are only \", length(sample.id), \" samples in the data. Please change the value of `min.samples`! \"))\n }\n if (length(sample.id) >= 2 & min.samples >= 2) {\n if (object@options$parameter$raw.use == TRUE) {\n data <- as.matrix(object@data.signaling)\n } else {\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n stop(\"`object@data.smooth` is missing. Please update the CellChat object via `updateCellChat`! \\n\")\n }\n data <- as.matrix(object@data.smooth)\n }\n data.use <- data/max(data)\n group <- object@idents\n type <- object@options$parameter$type.mean\n trim <- object@options$parameter$trim\n FunMean <- switch(type,\n triMean = triMean,\n truncatedMean = function(x) mean(x, trim = trim, na.rm = TRUE),\n thresholdedMean = function(x) thresholdedMean(x, trim = trim, na.rm = TRUE),\n median = function(x) median(x, na.rm = TRUE))\n\n LR <- dimnames(net$prob)[[3]]\n idx.nonzero <- which(apply(net$prob, 3, sum) != 0)\n LR.nonzero <- LR[idx.nonzero] # only examine the L-R pairs with nonzero communication probabilities.\n\n interaction_input <- object@DB$interaction\n complex_input <- object@DB$complex\n geneIfo <- object@DB$geneInfo\n idx <- match(LR.nonzero, interaction_input$interaction_name)\n geneL <- as.character(interaction_input$ligand[idx])\n geneR <- as.character(interaction_input$receptor[idx])\n\n geneLR <- c(unique(geneL), unique(geneR))\n geneLR <- extractGeneSubset(geneLR, complex_input, geneIfo)\n data.use <- data.use[rownames(data.use) %in% geneLR, ]\n\n score.LR <- array(0, dim = c(nlevels(group),nlevels(group),length(LR.nonzero), length(sample.id)))\n LR.nonzero.all <- c()\n cell.excludes.sample <- c()\n for (i in 1:length(sample.id)) {\n cell.use <- which(sample.info == sample.id[i])\n group.use <- group[cell.use]\n group.use <- droplevels(group.use)\n # get the rare populations with few cells in each sample\n cell.excludes.sample.i <- which(as.numeric(table(object@idents[cell.use])) <= min.cells)\n cell.excludes.sample <- c(cell.excludes.sample, cell.excludes.sample.i)\n # compute average expression per cell group\n data.use.i <- data.use[, cell.use]\n data.use.avg <- aggregate(t(data.use.i), list(group.use), FUN = FunMean)\n data.use.avg <- t(data.use.avg[,-1])\n group.exist <- which(levels(group) %in% unique(group.use))\n if (length(group.exist) < nlevels(group)) {\n data.use.avg.temp <- matrix(0, nrow = nrow(data.use), ncol = nlevels(group))\n data.use.avg.temp[ , group.exist] <- data.use.avg\n rownames(data.use.avg.temp) <- rownames(data.use.avg)\n data.use.avg <- data.use.avg.temp\n }\n colnames(data.use.avg) <- levels(group)\n # compute the average expression of ligand or receptor in each cell group\n dataLavg <- computeExpr_LR(geneL, data.use.avg, complex_input)\n dataRavg <- computeExpr_LR(geneR, data.use.avg, complex_input)\n # compute the interaction scores for each ligand-receptor pair based on their expression\n for (jj in 1:length(LR.nonzero)) { # It is not good to use parallel here because it will change the order of LR\n score.LR[,,jj,i] <- Matrix::crossprod(matrix(dataLavg[jj, ], nrow = 1), matrix(dataRavg[jj, ], nrow = 1))\n }\n if (length(cell.excludes.sample.i) > 0) {\n cat(paste0(\"The number of cells of the following cell groups in \", sample.id[i], \" sample are less than \", min.cells, \" cells: \",toString(levels(object@idents)[cell.excludes.sample.i]), \"!\",'\\n'))\n score.LR[cell.excludes.sample.i, , , i] <- 0\n score.LR[ ,cell.excludes.sample.i, , i] <- 0\n }\n #LR.nonzero.all <- c(LR.nonzero.all, LR.nonzero[apply(score.LR[ , , , i], 3, sum) != 0])\n }\n #LR.nonzero.jointOnly <- setdiff(LR.nonzero, unique(LR.nonzero.all))\n\n # get the excluded cell groups that are not observed in the merged data, which is very possible for rare populations\n cell.excludes.sample <- unique(cell.excludes.sample)\n if (length(cell.excludes.sample) > 0) {\n cell.excludes.sample <- setdiff(cell.excludes.sample, cell.excludes)\n }\n\n score.LR[score.LR > 0] <- 1 # binarize the interaction score\n score.LR.consitent <- array(0, dim = c(nlevels(group),nlevels(group),length(LR.nonzero)))\n LR.inconsitent <- c()\n for (jj in 1:length(LR.nonzero)) {\n score.LR.sum <- apply(score.LR[ , , jj, ], c(1,2), sum) # elements 2 and 1 means consistent and inconsistent interactions across samples, respectively.\n # set communication probability to be zero for inconsistent interactions across samples\n if (sum((score.LR.sum > 0) * (score.LR.sum < min.samples)) > 0) {\n #LR.inconsitent <- c(LR.inconsitent, LR.nonzero[jj])\n score.LR.consitent <- (score.LR.sum >= min.samples) * 1\n if (rare.keep == TRUE & length(cell.excludes.sample) > 0) {\n score.LR.consitent[cell.excludes.sample, ] <- 1\n score.LR.consitent[ ,cell.excludes.sample] <- 1\n }\n net$prob[ , , LR.nonzero[jj]] <- net$prob[ , , LR.nonzero[jj]] * score.LR.consitent\n }\n }\n num.interaction2 <- sum(net$prob > 0)\n pct.dicrease <- scales::percent((num.interaction1-num.interaction2)/num.interaction1, accuracy = .1)\n cat(paste0(pct.dicrease, \" interactions are removed due to their inconsistence across \", min.samples, \" samples!\",'\\n'))\n }\n\n object@net <- net\n return(object)\n}\n\n\n#' Identify all the significant interactions (L-R pairs) from some cell groups to other cell groups\n#'\n#' @param object CellChat object\n#' @param from a vector giving the index or the name of source cell groups\n#' @param to a corresponding vector giving the index or the name of target cell groups. Note: The length of 'from' and 'to' must be the same, giving the corresponding pair of cell groups for communication.\n#' @param bidirection whether show the bidirectional communication, i.e., both 'from'->'to' and 'to'->'from'.\n#' @param pair.only whether only return ligand-receptor pairs without pathway names and communication strength\n#' @param pairLR.use0 ligand-receptor pairs to use; default is all the significant interactions\n#' @param thresh threshold of the p-value for determining significant interaction\n#'\n#' @return\n#' @export\n#'\nidentifyEnrichedInteractions <- function(object, from, to, bidirection = FALSE, pair.only = TRUE, pairLR.use0 = NULL, thresh = 0.05){\n pairwiseLR <- object@net$pairwiseRank\n if (is.null(pairwiseLR)) {\n stop(\"The interactions between pairwise cell groups have not been extracted!\n Please first run `object <- rankNetPairwise(object)`\")\n }\n group.names.all <- names(pairwiseLR)\n if (!is.numeric(from)) {\n from <- match(from, group.names.all)\n if (sum(is.na(from)) > 0) {\n message(\"Some input cell group names in 'from' do not exist!\")\n from <- from[!is.na(from)]\n }\n }\n if (!is.numeric(to)) {\n to <- match(to, group.names.all)\n if (sum(is.na(to)) > 0) {\n message(\"Some input cell group names in 'to' do not exist!\")\n to <- to[!is.na(to)]\n }\n }\n if (length(from) != length(to)) {\n stop(\"The length of 'from' and 'to' must be the same!\")\n }\n if (bidirection) {\n from2 <- c(from, to)\n to <- c(to, from)\n from <- from2\n }\n if (is.null(pairLR.use0)) {\n k <- 0\n pairLR.use0 <- list()\n for (i in 1:length(from)){\n pairwiseLR_ij <- pairwiseLR[[from[i]]][[to[i]]]\n idx <- pairwiseLR_ij$pval < thresh\n if (length(idx) > 0) {\n k <- k +1\n pairLR.use0[[k]] <- pairwiseLR_ij[idx,]\n }\n }\n pairLR.use0 <- do.call(rbind, pairLR.use0)\n }\n\n k <- 0\n pval <- matrix(nrow = length(rownames(pairLR.use0)), ncol = length(from))\n prob <- pval\n group.names <- c()\n for (i in 1:length(from)) {\n k <- k+1\n pairwiseLR_ij <- pairwiseLR[[from[i]]][[to[i]]]\n pairwiseLR_ij <- pairwiseLR_ij[rownames(pairLR.use0),]\n pval_ij <- pairwiseLR_ij$pval\n prob_ij <- pairwiseLR_ij$prob\n pval_ij[pval_ij > 0.05] = 1\n pval_ij[pval_ij > 0.01 & pval_ij <= 0.05] = 2\n pval_ij[pval_ij <= 0.01] = 3\n prob_ij[pval_ij ==1] <- 0\n pval[,k] <- pval_ij\n prob[,k] <- prob_ij\n group.names <- c(group.names, paste(group.names.all[from[i]], group.names.all[to[i]], sep = \" - \"))\n }\n prob[which(prob == 0)] <- NA\n # remove rows that are entirely NA\n pval <- pval[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n pairLR.use0 <- pairLR.use0[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n prob <- prob[rowSums(is.na(prob)) != ncol(prob), ,drop = FALSE]\n if (pair.only) {\n pairLR.use0 <- dplyr::select(pairLR.use0, ligand, receptor)\n }\n return(pairLR.use0)\n}\n\n\n#' Compute the region distance based on the spatial locations of each splot/cell of the spatial transcriptomics\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param meta a data frame including at least two columns named `group` and `samples`. `meta$group` is a factor vector defining the regions/labels of each cell/spot. `meta$samples` is a factor vector defining the sample labels of each dataset.\n#' @param interaction.range The maximum interaction/diffusion range of ligands. This hard threshold is used to filter out the connections between spatially distant regions\n#' @param ratio a numerical vector giving the conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns).\n#'\n#' For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates.\n#' For 10X visium, it is the ratio of the theoretical spot size (i.e., 65um) over the number of pixels that span the diameter of a theoretical spot size in the full-resolution image (i.e., 'spot.size.fullres' in the 'scalefactors_json.json' file).\n#' @param tol a numerical vector giving the tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um.\n#'\n#' For example, for 10X visium, `tol` can be set as `65/2`; for slide-seq, `tol` can be set as `10/2`.\n#' If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance.\n#' @param k.min the minimum number of interacting cell pairs required for defining adjacent cell groups\n#' @param contact.dependent Whether determining spatially proximal cell groups based on either the contact.range or the k-nearest neighbors (knn). By default `contact.dependent = TRUE` when inferring contact-dependent and juxtacrine signaling (including ECM-Receptor and Cell-Cell Contact signaling classified in CellChatDB$interaction$annotation).\n#' If only focusing on `Secreted Signaling`, the `contact.dependent` will be automatically set as FALSE except for `contact.dependent.forced = TRUE`.\n#' @param contact.range The interaction range (Unit: microns) to restrict the contact-dependent signaling.\n#' For spatial transcriptomics in a single-cell resolution, `contact.range` is approximately equal to the estimated cell diameter (i.e., the cell center-to-center distance), which means that contact-dependent and juxtacrine signaling can only happens when the two cells are contact to each other.\n#'\n#' Typically, `contact.range = 10`, which is a typical human cell size. However, for low-resolution spatial data such as 10X visium, it should be the cell center-to-center distance (i.e., `contact.range = 100` for visium data). The function `computeCellDistance` can compute the center-to-center distance.\n#'\n#' @param contact.knn.k Number of neighbors to restrict the contact-dependent signaling within the neatest neighbors. By default, CellChat uses `contact.range` to restrict the contact-dependent signaling; however, users can also provide a value of `contact.knn.k`, in order to determine spatially proximal cell groups based on the k-nearest neighbors (knn).\n#' For 10X visium, contact.knn.k = 6. For other spatial technologies, this value may be hard to determine because the sequenced cells/spots are usually not regularly arranged.\n#' @param do.symmetric Whether converting the adjacent matrix into symmetric one when determining spatially proximal cell groups. Default is TRUE, indicating that if adj(i,j) or adj(j,i) is zero, then both are zeros.\n#'\n#' @importFrom BiocNeighbors queryKNN AnnoyParam\n#' @return A list including a square matrix giving the pairwise region distances and an adjacent matrix indicating physically contacting cell groups based on either the contact.range or the k-nearest neighbors\n#'\n#' @export\ncomputeRegionDistance <- function(coordinates, meta,\n interaction.range = NULL, ratio = NULL, tol = NULL, k.min = 10,\n contact.dependent = TRUE, contact.range = NULL, contact.knn.k = NULL, do.symmetric = TRUE\n) {\n trim <- 0.1\n FunMean <- function(x) mean(x, trim = trim, na.rm = TRUE) # This is used for computing the average distance between two cell groups\n group <- meta$group\n numCluster <- nlevels(group)\n level.use <- levels(group)\n level.use <- level.use[level.use %in% unique(group)]\n samples <- meta$samples\n samples.use <- levels(samples)\n d.spatial <- array(NaN, dim = c(numCluster,numCluster,length(samples.use)))\n adj.spatial <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n adj.contact <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n adj.contact.knn <- array(0, dim = c(numCluster,numCluster,length(samples.use)))\n\n if (contact.dependent == TRUE & !is.null(contact.knn.k)) {\n ## find the k-nearest neighbors for each single cell\n # my.knn <- FNN::get.knn(coordinates, k = contact.knn.k)\n # nn.ranked <- my.knn$nn.index # this is a matrix with the size of nCell * contact.knn.k\n nn.ranked <- matrix(NA, nrow = nrow(coordinates), ncol = contact.knn.k)\n for (k in 1:length(samples.use)) {\n idx.k <- which(samples == samples.use[k])\n my.knn <- suppressWarnings(BiocNeighbors::findKNN(coordinates[idx.k, ], k = contact.knn.k, BNPARAM = BiocNeighbors::AnnoyParam(), get.index = TRUE))\n nn.ranked[idx.k, ] <- my.knn$index # this is a matrix with the size of nCell * contact.knn.k\n }\n k.min.contact <- k.min\n } else {\n nn.ranked <- matrix(1, nrow = nrow(coordinates), ncol = 1)\n k.min.contact <- -1 # this produces adj.contact.knn with all elements being 1\n }\n if (contact.dependent == TRUE) {\n if (is.null(contact.range) & is.null(contact.knn.k)) {\n stop(\"Please check the documentation of `computeCommunProb` and provide the value of either `contact.range` or `contact.knn.k`\")\n }\n } else {\n contact.range <- 10000 # this produces adj.contact with all elements being 1\n }\n\n for (k in 1:length(samples.use)) {\n idx.k <- samples == samples.use[k]\n for (i in 1:numCluster) {\n for (j in 1:numCluster) {\n idx.i <- which((group == level.use[i]) & idx.k)\n idx.j <- which((group == level.use[j]) & idx.k)\n if (length(idx.i) == 0 | length(idx.j) == 0) {\n next # if one cell group is missing in one sample, just goes to next loop\n }\n data.spatial.i <- coordinates[idx.i, , drop = FALSE]\n data.spatial.j <- coordinates[idx.j, , drop = FALSE]\n # for each point in the i-th cell group, find its 1-nearest neighbor in the j-th cell group\n #qout <- suppressWarnings(BiocNeighbors::queryKNN(data.spatial.j, data.spatial.i, k = 1, BNPARAM = BiocNeighbors::KmknnParam(), get.index = TRUE))\n qout <- suppressWarnings(BiocNeighbors::queryKNN(data.spatial.j, data.spatial.i, k = 1, BNPARAM = BiocNeighbors::AnnoyParam(), get.index = TRUE))\n # qout$index is an one column matrix with length being `length(idx.i)`, which is the index of the 1-nearest neighbor in the j-th cell group defined by `idx.j`\n # qout$distance is an one column matrix with length being `length(idx.i)`, which is the distance to the 1-nearest neighbor in the j-th cell group defined by `idx.j`\n\n # conver the calculated distance into the distance in micrometers\n qout$distance <- qout$distance*ratio[k]\n # long-range distance\n idx <- qout$distance - interaction.range < tol[k]\n adj.spatial[i,j,k] <- (length(unique(qout$index[idx])) >= k.min) * 1\n # short-range distance based on contact.range\n idx2 <- qout$distance - contact.range < tol[k]\n adj.contact[i,j,k] <- (length(unique(qout$index[idx2])) >= k.min) * 1\n # short-range distance based on knn\n knn.i <- unique(as.vector(nn.ranked[idx.i, ]))\n #adj.contact.knn[i,j,k] <- (length(intersect(knn.i, idx.j)) >= k.min.contact) * 1\n adj.contact.knn[i,j,k] <- (length(intersect(knn.i, unique(qout$index[idx]))) >= k.min.contact) * 1 # knn within the long-range distance\n # computing the average distance between two cell groups\n d.spatial[i,j,k] <- FunMean(qout$distance) # since distances are positive values, different ways for computing the mean have little effects.\n\n }\n }\n }\n\n # merged spatial information from different samples\n d.spatial <- apply(d.spatial, c(1,2), function(x) mean(x, na.rm = TRUE))\n adj.spatial <- apply(adj.spatial, c(1,2), mean)\n adj.contact <- apply(adj.contact, c(1,2), mean)\n adj.contact.knn <- apply(adj.contact.knn, c(1,2), mean)\n # for multi-samples analysis, the following is needed\n adj.spatial[adj.spatial > 0] <- 1\n adj.contact[adj.contact > 0] <- 1\n adj.contact.knn[adj.contact.knn > 0] <- 1\n\n # make these adjacent matrix as symmetric\n if (do.symmetric) {\n adj.spatial <- adj.spatial * t(adj.spatial) # if one is zero, then both are zeros.\n adj.contact <- adj.contact * t(adj.contact) # if one is zero, then both are zeros.\n adj.contact.knn <- adj.contact.knn * t(adj.contact.knn) # if one is zero, then both are zeros.\n }\n d.spatial <- (d.spatial + t(d.spatial))/2\n\n # filter out the spatially distant cell groups\n adj.spatial[adj.spatial == 0] <- NaN\n d.spatial <- d.spatial * adj.spatial\n\n rownames(d.spatial) <- levels(group); colnames(d.spatial) <- levels(group)\n\n if (length(contact.knn.k) > 0) {\n adj.contact = adj.contact.knn\n }\n res <- list(d.spatial = d.spatial, adj.contact = adj.contact)\n return(res)\n\n}\n\n#' Compute cell-cell distance based on the spatial coordinates\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param interaction.range The maximum interaction/diffusion range of ligands. This hard threshold is used to filter out the connections between spatially distant cells\n#' @param ratio The conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns).\n#'\n#' For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates.\n#' For 10X visium, it is the ratio of the theoretical spot size (i.e., 65um) over the number of pixels that span the diameter of a theoretical spot size in the full-resolution image (i.e., 'spot.size.fullres' in the 'scalefactors_json.json' file).\n#' @param tol The tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um.\n#'\n#' For example, for 10X visium, `tol` can be set as `65/2`; for slide-seq, `tol` can be set as `10/2`.\n#' If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance.\n#'\n#' @return an object of class \"dist\" giving the pairwise cell-cell distance\n#' @export\n#'\ncomputeCellDistance <- function(coordinates, interaction.range = NULL, ratio = NULL, tol = NULL){\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n\n d.spatial <- stats::dist(coordinates)\n if (!is.null(ratio)) {\n d.spatial <- d.spatial*ratio\n }\n\n if(!is.null(interaction.range) & !is.null(tol)){\n message(\"\\n Apply a predefined spatial distance threshold based on the interaction length...\")\n d.spatial[d.spatial > (interaction.range + tol)] <- NaN\n }\n return(d.spatial)\n}\n\n\n"], ["/CellChat/R/database.R", "#' Show the description of CellChatDB databse\n#'\n#' @param CellChatDB CellChatDB databse\n#' @param nrow the number of rows in the plot\n#' @importFrom dplyr group_by summarise n %>%\n#'\n#' @return\n#' @export\n#'\nshowDatabaseCategory <- function(CellChatDB, nrow = 1) {\n interaction_input <- CellChatDB$interaction\n geneIfo <- CellChatDB$geneInfo\n df <- interaction_input %>% group_by(annotation) %>% summarise(value=n())\n #df$group <- factor(df$annotation, levels = unique(df$annotation))\n df$group <- factor(df$annotation, levels = c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\"))\n gg1 <- pieChart(df)\n binary <- (interaction_input$ligand %in% geneIfo$Symbol) & (interaction_input$receptor %in% geneIfo$Symbol)\n df <- data.frame(group = rep(\"Heterodimers\", dim(interaction_input)[1]),stringsAsFactors = FALSE)\n df$group[binary] <- rep(\"Others\",sum(binary),1)\n df <- df %>% group_by(group) %>% summarise(value=n())\n df$group <- factor(df$group, levels = c(\"Heterodimers\",\"Others\"))\n gg2 <- pieChart(df)\n\n kegg <- grepl(\"KEGG\", interaction_input$evidence)\n df <- data.frame(group = rep(\"Literature\", dim(interaction_input)[1]),stringsAsFactors = FALSE)\n df$group[kegg] <- rep(\"KEGG\",sum(kegg),1)\n df <- df %>% group_by(group) %>% summarise(value=n())\n df$group <- factor(df$group, levels = c(\"KEGG\",\"Literature\"))\n gg3 <- pieChart(df)\n\n gg <- cowplot::plot_grid(gg1, gg2, gg3, nrow = nrow, align = \"h\", rel_widths = c(1, 1,1))\n return(gg)\n}\n\n\n#' Plot pie chart\n#'\n#' @param df a dataframe\n#' @param label.size a character\n#' @param color.use the name of the variable in CellChatDB interaction_input\n#' @param title the title of plot\n#' @import ggplot2\n#' @importFrom scales percent\n#' @importFrom dplyr arrange desc mutate\n#' @importFrom ggrepel geom_text_repel\n#' @return\n#' @export\n#'\npieChart <- function(df, label.size = 2.5, color.use = NULL, title = \"\") {\n df %>% arrange(dplyr::desc(value)) %>%\n mutate(prop = scales::percent(value/sum(value))) -> df\n\n gg <- ggplot(df, aes(x=\"\", y=value, fill=group)) +\n geom_bar(stat=\"identity\", width=1) +\n coord_polar(\"y\", start=0)+theme_void() +\n ggrepel::geom_text_repel(aes(label = prop), size= label.size, show.legend = F, position = position_stack(vjust=0.5))\n # ggrepel::geom_text_repel(aes(label = prop), size= label.size, show.legend = F, nudge_x = 0)\n gg <- gg + theme(legend.position=\"bottom\", legend.direction = \"vertical\")\n\n if(!is.null(color.use)) {\n gg <- gg + scale_fill_manual(values=color.use)\n # gg <- gg + scale_color_manual(color.use)\n }\n\n if (!is.null(title)) {\n gg <- gg + guides(fill = guide_legend(title = title))\n }\n gg\n}\n\n\n#' Subset the ligand-receptor interactions for given specific signals in CellChatDB\n#'\n#' @param signaling a character vector\n#' @param pairLR.use a dataframe containing ligand-receptor interactions\n#' @param key the keyword to match\n#' @param matching.exact whether perform exact matching\n#' @param pair.only whether only return ligand-receptor pairs without cofactors\n#' @importFrom future.apply future_sapply\n#' @importFrom dplyr select\n#' @return\n#' @export\nsearchPair <- function(signaling = c(), pairLR.use, key = c(\"pathway_name\",\"ligand\"), matching.exact = FALSE, pair.only = TRUE) {\n key <- match.arg(key)\n pairLR = future.apply::future_sapply(\n X = 1:length(signaling),\n FUN = function(x) {\n if (!matching.exact) {\n index <- grep(signaling[x], pairLR.use[[key]])\n } else {\n index <- which(pairLR.use[[key]] %in% signaling[x])\n }\n if (length(index) > 0) {\n if (pair.only) {\n pairLR <- dplyr::select(pairLR.use[index, ], interaction_name, pathway_name, ligand, receptor)\n } else {\n pairLR <- pairLR.use[index, ]\n }\n return(pairLR)\n } else {\n stop(cat(paste(\"Cannot find \", signaling[x], \".\", \"Please input a correct name!\"),'\\n'))\n }\n }\n )\n if (pair.only) {\n pairLR0 <- vector(\"list\", length(signaling))\n for (i in 1:length(signaling)) {\n pairLR0[[i]] <- matrix(unlist(pairLR[c(4*i-3, 4*i-2, 4*i-1, 4*i)]), ncol=4, byrow=F)\n }\n pairLR <- do.call(rbind, pairLR0)\n dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]][1:4]\n rownames(pairLR) <- pairLR[,1]\n } else {\n pairLR0 <- vector(\"list\", length(signaling))\n for (i in 1:length(signaling)) {\n pairLR0[[i]] <- matrix(unlist(pairLR[(i*ncol(pairLR.use)-(ncol(pairLR.use)-1)):(i*ncol(pairLR.use))]), ncol=ncol(pairLR.use), byrow=F)\n }\n pairLR <- do.call(rbind, pairLR0)\n dimnames(pairLR)[[2]] <- dimnames(pairLR.use)[[2]]\n rownames(pairLR) <- pairLR[,1]\n }\n return(as.data.frame(pairLR, stringsAsFactors = FALSE))\n}\n\n#' Subset CellChatDB databse by only including interactions of interest\n#'\n#' @param CellChatDB CellChatDB databse\n#' @param search a character vector, which is a subset of c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\"); Setting search = NULL & non_protein = FALSE will return all signaling except for \"Non-protein Signaling\".\n#'\n#' When `key` is a vector, the `search` should be a list with the size being `length(key)`, where each element is a character vector.\n#' @param key a character vector and each element should be one of the column names of the interaction_input from CellChatDB.\n#' @param non_protein whether to use the non-protein signaling for CellChat analysis. By default, non_protein = FALSE because most of non-protein signaling are the special synaptic signaling interactions that can only be used when inferring neuron-neuron communication.\n#'\n#' @return\n#' @export\n#'\nsubsetDB <- function(CellChatDB, search = c(), key = \"annotation\", non_protein = FALSE) {\n interaction_input <- CellChatDB$interaction\n if (is.null(search) & non_protein == FALSE & any(key == \"annotation\")) {\n search <- c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\")\n } else if (is.null(search) & non_protein == TRUE & any(key == \"annotation\")) {\n search <- c(\"Secreted Signaling\",\"ECM-Receptor\",\"Cell-Cell Contact\",\"Non-protein Signaling\")\n }\n\n if (\"Non-protein Signaling\" %in% unlist(search)) {\n non_protein = TRUE\n message(\"The non-protein signaling is now included for CellChat analysis, which is usually used for neuron-neuron and metabolic communication!\")\n }\n if (non_protein == FALSE) {\n interaction_input <- subset(interaction_input, annotation != \"Non-protein Signaling\")\n }\n if (all(key %in% colnames(interaction_input)) == FALSE) {\n stop(\"Each element of the `key` should be one of the column names of the interaction_input from CellChatDB\")\n }\n if (length(key) == 1) {\n interaction_input <- interaction_input[interaction_input[[key]] %in% search, ]\n } else {\n if (!is.list(search)) {\n stop(\"When `key` is a vector, the `search` should be a list. \")\n }\n idx.use <- TRUE\n for (i in 1:length(key)) {\n idx.use <- idx.use & (interaction_input[[key[i]]] %in% search[[i]])\n }\n interaction_input <- interaction_input[idx.use, , drop = FALSE]\n }\n\n CellChatDB$interaction <- interaction_input\n return(CellChatDB)\n}\n\n\n\n#' Extract the genes involved in CellChatDB\n#'\n#' @param CellChatDB CellChatDB databse used in the analysis\n#'\n#' @return\n#' @export\n#' @importFrom dplyr select\n#'\nextractGene <- function(CellChatDB) {\n interaction_input <- CellChatDB$interaction\n complex_input <- CellChatDB$complex\n cofactor_input <- CellChatDB$cofactor\n geneIfo <- CellChatDB$geneInfo\n # check whether all gene names in complex_input and cofactor_input are official gene symbol in geneIfo\n checkGeneSymbol(geneSet = unlist(complex_input), geneIfo)\n checkGeneSymbol(geneSet = unlist(cofactor_input), geneIfo)\n\n geneL <- unique(interaction_input$ligand)\n geneR <- unique(interaction_input$receptor)\n geneLR <- c(geneL, geneR)\n checkGeneSymbol(geneSet = geneLR[geneLR %in% rownames(complex_input) == \"FALSE\"], geneIfo)\n\n geneL <- extractGeneSubset(geneL, complex_input, geneIfo)\n geneR <- extractGeneSubset(geneR, complex_input, geneIfo)\n geneLR <- c(geneL, geneR)\n\n cofactor <- c(interaction_input$agonist, interaction_input$antagonist, interaction_input$co_A_receptor, interaction_input$co_I_receptor)\n cofactor <- unique(cofactor[cofactor != \"\"])\n cofactorsubunits <- select(cofactor_input[match(cofactor, rownames(cofactor_input), nomatch=0),], starts_with(\"cofactor\"))\n cofactorsubunitsV <- unlist(cofactorsubunits)\n geneCofactor <- unique(cofactorsubunitsV[cofactorsubunitsV != \"\"])\n\n gene.use <- unique(c(geneLR, geneCofactor))\n return(gene.use)\n\n}\n\n\n#' Extract the gene name\n#'\n#' @param geneSet gene set\n#' @param complex_input complex in CellChatDB databse\n#' @param geneIfo official gene symbol\n#'\n#' @return\n#' @importFrom dplyr select starts_with\n#' @export\nextractGeneSubset <- function(geneSet, complex_input, geneIfo) {\n complex <- geneSet[which(geneSet %in% geneIfo$Symbol == \"FALSE\")]\n geneSet <- intersect(geneSet, geneIfo$Symbol)\n complexsubunits <- dplyr::select(complex_input[match(complex, rownames(complex_input), nomatch=0),], starts_with(\"subunit\"))\n complex <- intersect(complex, rownames(complexsubunits))\n complexsubunitsV <- unlist(complexsubunits)\n complexsubunitsV <- unique(complexsubunitsV[complexsubunitsV != \"\"])\n geneSet <- unique(c(geneSet, complexsubunitsV))\n return(geneSet)\n}\n\n\n#' Extract the signaling gene names from ligand-receptor pairs\n#'\n#' @param pairLR data frame must contain columns named `ligand` and `receptor`\n#' @param object a CellChat object\n#' @param complex_input complex in CellChatDB databse\n#' @param geneInfo official gene symbol\n#' @param combined whether combining the ligand genes and receptor genes\n#'\n#' @return\n#' @export\nextractGeneSubsetFromPair <- function(pairLR, object = NULL, complex_input = NULL, geneInfo = NULL, combined = TRUE) {\n if (!all(c(\"ligand\", \"receptor\") %in% colnames(pairLR))) {\n stop(\"The input data frame must contain columns named `ligand` and `receptor`\")\n }\n if (is.null(object)) {\n if (is.null(complex_input) | is.null(geneInfo)) {\n stop(\"Either `object` or `complex_input` and `geneInfo` should be provided!\")\n } else {\n complex <- complex_input\n }\n } else {\n complex <- object@DB$complex\n geneInfo <- object@DB$geneInfo\n }\n geneL <- unique(pairLR$ligand)\n geneR <- unique(pairLR$receptor)\n geneL <- extractGeneSubset(geneL, complex, geneInfo)\n geneR <- extractGeneSubset(geneR, complex, geneInfo)\n geneLR <- c(geneL, geneR)\n if (combined) {\n return(geneLR)\n } else {\n return(list(geneL = geneL, geneR = geneR))\n }\n}\n\n\n\n#' check the official Gene Symbol\n#'\n#' @param geneSet gene set to check\n#' @param geneIfo official Gene Symbol\n#' @return\n#' @export\n#'\ncheckGeneSymbol <- function(geneSet, geneIfo) {\n geneSet <- unique(geneSet[geneSet != \"\"])\n genes_notOfficial <- geneSet[geneSet %in% geneIfo$Symbol == \"FALSE\"]\n if (length(genes_notOfficial) > 0) {\n cat(\"Issue identified!! Please check the official Gene Symbol of the following genes: \", \"\\n\", genes_notOfficial, \"\\n\")\n }\n return(FALSE)\n}\n\n#' Extract L-R pairs associated with a given gene set\n#'\n#' @param geneSet a vector of genes\n#' @param db one of the CellChatDB databases (e.g., CellChatDB.human, CellChatDB.mouse...)\n#' @export\n#'\nextractLRfromGenes <- function(geneSet, db) {\n interaction_input <- db$interaction\n complex_input <- db$complex\n geneIfo <- db$geneInfo\n geneSet1 <- intersect(geneSet, geneIfo$Symbol)\n idx1 <- which(interaction_input$ligand %in% geneSet1)\n idx2 <- which(interaction_input$receptor %in% geneSet1)\n idx <- unique(c(idx1, idx2)); idx <- setdiff(idx,0)\n LR.use <- interaction_input[idx,,drop = FALSE]\n genes.use <- extractGeneSubsetFromPair(LR.use, complex_input = complex_input, geneInfo = geneIfo)\n return(list(LR.use = LR.use, genes.use=genes.use))\n}\n\n\n#' Update CellChatDB by integrating new L-R pairs from other resources or adding more information\n#'\n#' @param db a data frame of the customized ligand-receptor database with at least two columns named as `ligand` and `receptor`. We highly suggest users to provide a column of pathway information named `pathway_name` associated with each L-R pair.\n#' Other optional columns include `interaction_name` and `interaction_name_2`. The default columns of CellChatDB can be checked via `colnames(CellChatDB.human$interaction)`.\n#' @param gene_info a data frame with at least one column named as `Symbol`. \"When setting gene_info = NULL, the input `species_target` should be provided: either `human` or `mouse`.\n#' @param other_info a list consisting of other information including a dataframe named as `complex` and a dataframe named as `cofactor`. This additional information is not necessary. If other_info is provided, the `complex` and `cofactor` are dataframes with defined rownames.\n#' @param gene_info_columnNew a data frame with at least two columns named as `Symbol` and `AntibodyName`, which will add a new column named `AntibodyName` into `db$geneInfo`.\n#' @param trim.pathway whether to delete the interactions with missing pathway names when the column `pathway_name` is provided in `db`.\n#' @param merged whether merging the input database with the existing CellChatDB. setting merged = TRUE, the input `species_target` should be provided: either `human` or `mouse`.\n#' @param species_target the target species for output: either `human` or `mouse`.\n#' @return a list consisting of the customized L-R database for further CellChat analysis\n#' @export\n#'\n#' @examples\n#'\\dontrun{\n#' # integrating new L-R pairs from other resources or utilizing a custom database `db.user`\n#' db.new <- updateCellChatDB(db = db.user, gene_info = gene_info)\n#' db.new <- updateCellChatDB(db = db.user, gene_info = NULL, species_target = \"human\")\n#' # Alternatively, users can integrate the customized L-R pairs into the built-in CellChatDB\n#' db.new <- updateCellChatDB(db = db.user, merged = TRUE, species_target = \"human\")\n#' # Add new columns (e.g., AntibodyName) into gene_info\n#' db.new.human <- updateCellChatDB(db = CellChatDB.human$interaction, gene_info = CellChatDB.human$geneInfo, other_info=list(complex = CellChatDB.human$complex, cofactor = CellChatDB.human$cofactor),gene_info_columnNew = gene_info_columnNew)\n#'\n#' # Users can now use this new database in CellChat analysis\n#' cellchat@DB <- db.new\n#'}\nupdateCellChatDB <- function(db, gene_info = NULL, other_info = NULL, gene_info_columnNew = NULL, trim.pathway = FALSE, merged = FALSE, species_target = NULL) {\n db <- dplyr::mutate(db, across(everything(), as.character))\n if (all(c(\"ligand\",\"receptor\") %in% colnames(db)) == FALSE) {\n stop(\"The input `db` must contain at least two columns named as ligand,receptor\")\n }\n if (all(c(\"pathway_name\") %in% colnames(db)) == FALSE) {\n warning(\"The pathway_name associated with each L-R pair is not provided in `db`. We suggest to provide this information so that the versatile functionalities of CellChat can be fully used! \\n\")\n db$pathway_name <- rep(\"\", nrow(db))\n } else {\n pathway.missing <- which(db$pathway_name == \"\")\n if (length(pathway.missing) > 0) {\n if (trim.pathway) {\n cat(paste0(\"The pathway names of \", length(pathway.missing) ,\" interactions are missing and the corresponding interactions are now deleted. \\n\"))\n db <- db[-pathway.missing, , drop = FALSE]\n } else {\n warning(paste0(\"The pathway names of \", length(pathway.missing) ,\" interactions are missing and it may cause error in the downstream analysis. Setting `trim.pathway = TRUE` to avoid such possible errors. \\n\"))\n }\n }\n }\n if (all(c(\"interaction_name\") %in% colnames(db)) == FALSE) {\n db$interaction_name <- paste0(toupper(db$ligand), \"_\", toupper(db$receptor))\n }\n if (all(c(\"interaction_name_2\") %in% colnames(db)) == FALSE) {\n db$interaction_name_2 <- paste0(db$ligand, \" - \", db$receptor)\n }\n if (\"agonist\" %in% colnames(db) == FALSE) {\n db$agonist <- rep(\"\", nrow(db))\n }\n if (\"antagonist\" %in% colnames(db) == FALSE) {\n db$antagonist <- rep(\"\", nrow(db))\n }\n if (\"co_A_receptor\" %in% colnames(db) == FALSE) {\n db$co_A_receptor <- rep(\"\", nrow(db))\n }\n if (\"co_I_receptor\" %in% colnames(db) == FALSE) {\n db$co_I_receptor <- rep(\"\", nrow(db))\n }\n ## construct database\n idx.remove <- duplicated(db$interaction_name)\n if (sum(idx.remove) > 0) {\n warning(paste0(sum(idx.remove), \" duplicated interaction_names are identified and the corresponding interactions are now deleted. \\n\"))\n db <- db[-which(idx.remove), ]\n }\n\n # build the interaction file\n interaction_input <- db\n rownames(interaction_input) <- interaction_input$interaction_name\n cols.default <- c(\"interaction_name\",\"pathway_name\",\"ligand\",\"receptor\",\"agonist\",\"antagonist\",\"co_A_receptor\",\"co_I_receptor\",\"annotation\",\"interaction_name_2\")\n cols.common <- intersect(cols.default,colnames(interaction_input))\n cols.specific <- setdiff(colnames(interaction_input), cols.default)\n interaction_input <- dplyr::select(interaction_input, c(cols.common, cols.specific))\n\n # build the complex file\n if (!is.null(other_info)) {\n if (\"complex\" %in% names(other_info) == TRUE) {\n complex_input <- other_info$complex\n if (all(colnames(complex_input) %in% paste0(\"subunit_\", seq_len(100))) == FALSE) {\n stop(\"The colnames of the input `other_info$complex` should be `subunit_1`,`subunit_2`,...\")\n }\n } else {\n complex_input <- data.frame()\n }\n # build the cofactor file\n if (\"cofactor\" %in% names(other_info) == TRUE) {\n cofactor_input <- other_info$cofactor\n if (all(colnames(cofactor_input) %in% paste0(\"cofactor\", seq_len(100))) == FALSE) {\n stop(\"The colnames of the input `other_info$cofactor` should be `cofactor1`,`cofactor2`,...\")\n }\n } else {\n cofactor_input <- data.frame()\n }\n } else {\n complex_input <- data.frame()\n cofactor_input <- data.frame()\n }\n\n # build the geneInfo file\n if (!is.null(gene_info)) {\n if (\"Symbol\" %in% colnames(gene_info) == FALSE) {\n stop(\"The input `gene_info` must contain at least one column named as `Symbol`\")\n }\n } else {\n if (is.null(species_target)) {\n stop(\"When setting gene_info = NULL, the input `species_target` should be provided: either `human` or `mouse`. \")\n }\n if (species_target == \"human\") {\n gene_info <- CellChatDB.human$geneInfo\n } else if (species_target == \"mouse\") {\n gene_info <- CellChatDB.mouse$geneInfo\n }\n }\n geneInfo_input <- gene_info\n\n if (merged == TRUE) {\n if (is.null(species_target)) {\n stop(\"When setting merged = TRUE, the input `species_target` should be provided: either `human` or `mouse`. \")\n }\n if (species_target == \"human\") {\n db.cellchat <- CellChatDB.human\n cat(\"Starting to merge the input database with CellChatDB.human... \\n\")\n } else if (species_target == \"mouse\") {\n db.cellchat <- CellChatDB.mouse\n cat(\"Starting to merge the input database with CellChatDB.mouse... \\n\")\n }\n\n # build the interaction file\n interaction_input.cellchat <- db.cellchat$interaction\n interaction_input.cellchat$source.merged <- \"CellChatDB\"\n interaction_input$source.merged <- \"User\"\n cols.common <- intersect(colnames(interaction_input), colnames(interaction_input.cellchat))\n interaction_input <- interaction_input[, cols.common]\n interaction_input.cellchat <- interaction_input.cellchat[, cols.common]\n interaction_input.merged <- rbind(interaction_input.cellchat, interaction_input)\n idx.remove <- duplicated(interaction_input.merged$interaction_name)\n if (sum(idx.remove) > 0) {\n interaction_input.merged <- interaction_input.merged[-which(idx.remove), ]\n }\n\n # build the complex file\n complex_input.cellchat <- db.cellchat$complex\n num.subunit <- max(ncol(complex_input), ncol(complex_input.cellchat))\n if (ncol(complex_input) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(complex_input)))\n complex_input <- cbind(complex_input, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(complex_input)))))\n colnames(complex_input) <- paste0(\"subunit_\", seq_len(num.subunit))\n }\n if (ncol(complex_input.cellchat) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(complex_input.cellchat)))\n complex_input.cellchat <- cbind(complex_input.cellchat, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(complex_input.cellchat)))))\n colnames(complex_input.cellchat) <- paste0(\"subunit_\", seq_len(num.subunit))\n }\n complex_input.merged <- rbind(complex_input.cellchat, complex_input)\n idx.remove <- duplicated(rownames(complex_input.merged))\n if (sum(idx.remove) > 0) {\n complex_input.merged <- complex_input.merged[-which(idx.remove), ]\n }\n\n # build the cofactor file\n cofactor_input.cellchat <- db.cellchat$cofactor\n num.subunit <- max(ncol(cofactor_input), ncol(cofactor_input.cellchat))\n if (ncol(cofactor_input) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(cofactor_input)))\n cofactor_input <- cbind(cofactor_input, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(cofactor_input)))))\n colnames(cofactor_input) <- paste0(\"cofactor\", seq_len(num.subunit))\n }\n if (ncol(cofactor_input.cellchat) < num.subunit) {\n temp <- data.frame(rep(\"\", nrow(cofactor_input.cellchat)))\n cofactor_input.cellchat <- cbind(cofactor_input.cellchat, as.data.frame(do.call(cbind, rep(temp, num.subunit-ncol(cofactor_input.cellchat)))))\n colnames(cofactor_input.cellchat) <- paste0(\"cofactor\", seq_len(num.subunit))\n }\n cofactor_input.merged <- rbind(cofactor_input.cellchat, cofactor_input)\n idx.remove <- duplicated(rownames(cofactor_input.merged))\n if (sum(idx.remove) > 0) {\n cofactor_input.merged <- cofactor_input.merged[-which(idx.remove), ]\n }\n\n interaction_input <- interaction_input.merged\n complex_input <- complex_input.merged\n cofactor_input <- cofactor_input.merged\n }\n\n if (!is.null(gene_info_columnNew)) {\n checkGeneSymbol(gene_info_columnNew$Symbol, geneInfo_input)\n idx <- match(gene_info_columnNew$Symbol, geneInfo_input$Symbol)\n geneInfo_input$AntibodyName <- NA\n geneInfo_input$AntibodyName[idx[!is.na(idx)]] <- gene_info_columnNew$AntibodyName[!is.na(idx)]\n }\n db.new <- list()\n db.new$interaction <- interaction_input\n db.new$complex <- complex_input\n db.new$cofactor <- cofactor_input\n db.new$geneInfo <- geneInfo_input\n\n return(db.new)\n}\n"], ["/CellChat/R/CellChat_class.R", "\n#' The CellChat Class\n#'\n#' The CellChat object is created from a single-cell transcriptomic data matrix, Seurat V3 or SingleCellExperiment object.\n#' When inputting an data matrix, it takes a digital data matrices as input. Genes should be in rows and cells in columns. rownames and colnames should be included.\n#' The class provides functions for data preprocessing, intercellular communication network inference, communication network analysis, and visualization.\n#'\n#'\n#'# Class definitions\n#' @importFrom methods setClassUnion\n#' @importClassesFrom Matrix dgCMatrix\nsetClassUnion(name = 'AnyMatrix', members = c(\"matrix\", \"dgCMatrix\"))\nsetClassUnion(name = 'AnyFactor', members = c(\"factor\", \"list\"))\n\n#' The key slots used in the CellChat object are described below.\n#'\n#' @slot data.raw raw count data matrix\n#' @slot data normalized data matrix for CellChat analysis (Genes should be in rows and cells in columns)\n#' @slot data.signaling a subset of normalized matrix only containing signaling genes\n#' @slot data.scale scaled data matrix\n#' @slot data.smooth smoothed data\n#' @slot images a list of information of spatial transcriptomics data\n#' @slot net a three-dimensional array P (K×K×N), where K is the number of cell groups and N is the number of ligand-receptor pairs. Each row of P indicates the communication probability originating from the sender cell group to other cell groups.\n#' @slot netP a three-dimensional array representing cel-cell communication networks on a signaling pathway level\n#' @slot DB ligand-receptor interaction database used in the analysis (a subset of CellChatDB)\n#' @slot LR a list of information related with ligand-receptor pairs\n#' @slot meta data frame storing the information associated with each cell\n#' @slot idents a factor defining the cell identity used for all analysis. It becomes a list for a merged CellChat object\n#' @slot var.features A list: one element is a vector consisting of the identified over-expressed signaling genes; one element is a data frame returned from the differential expression analysis\n#' @slot dr List of the reduced 2D coordinates, one per method, e.g., umap/tsne/dm\n#' @slot options List of miscellaneous data, such as parameters used throughout analysis, and a indicator whether the CellChat object is a single or merged\n#'\n#' @exportClass CellChat\n#' @importFrom Rcpp evalCpp\n#' @importFrom methods setClass\n# #' @useDynLib CellChat\nCellChat <- methods::setClass(\"CellChat\",\n slots = c(data.raw = 'AnyMatrix',\n data = 'AnyMatrix',\n data.signaling = \"AnyMatrix\",\n data.scale = \"matrix\",\n data.smooth = \"AnyMatrix\",\n images = \"list\",\n net = \"list\",\n netP = \"list\",\n meta = \"data.frame\",\n idents = \"AnyFactor\",\n DB = \"list\",\n LR = \"list\",\n var.features = \"list\",\n dr = \"list\",\n options = \"list\")\n)\n#' show method for CellChat\n#'\n#' @param CellChat object\n#' @param show show the object\n#' @param object object\n#' @docType methods\n#'\nsetMethod(f = \"show\", signature = \"CellChat\", definition = function(object) {\n if (object@options$mode == \"single\") {\n cat(\"An object of class\", class(object), \"created from a single dataset\", \"\\n\", nrow(object@data), \"genes.\\n\", ncol(object@data), \"cells. \\n\")\n } else if (object@options$mode == \"merged\") {\n cat(\"An object of class\", class(object), \"created from a merged object with multiple datasets\", \"\\n\", nrow(object@data.signaling), \"signaling genes.\\n\", ncol(object@data.signaling), \"cells. \\n\")\n }\n if (object@options$datatype == \"RNA\") {\n cat(\"CellChat analysis of single cell RNA-seq data! \\n\")\n } else {\n cat(\"CellChat analysis of\", object@options$datatype, \"data! The input spatial locations are \\n\")\n print(head(object@images$coordinates))\n }\n\n\n invisible(x = NULL)\n})\n\n\n\n#' Create a new CellChat object from a data matrix, Seurat or SingleCellExperiment object\n#'\n#' @param object a normalized (NOT count) data matrix (genes by cells), Seurat or SingleCellExperiment object\n#' @param meta a data frame (rows are cells with rownames) consisting of cell information, which will be used for defining cell groups.\n#' If input is a Seurat or SingleCellExperiment object, the meta data in the object will be used\n#' @param group.by a char name of the variable in meta data, defining cell groups.\n#' If input is a data matrix and group.by is NULL, the input `meta` should contain a column named 'labels',\n#' If input is a Seurat or SingleCellExperiment object, USER must provide `group.by` to define the cell groups. e.g, group.by = \"ident\" for Seurat object\n#' @param datatype By default datatype = \"RNA\"; when running CellChat on spatial imaging data, set datatype = \"spatial\" and input `spatial.factors`\n#'\n#' @param coordinates a data matrix in which each row gives the spatial locations/coordinates of each cell/spot\n#' @param spatial.factors a data frame containing two distance factors `ratio` and `tol`, which is dependent on spatial transcriptomics technologies (and specific datasets).\n#'\n#' USER must input this data frame when datatype = \"spatial\". spatial.factors must contain an element named `ratio`, which is the conversion factor when converting spatial coordinates from Pixels or other units to Micrometers (i.e.,Microns). For example, setting `ratio = 0.18` indicates that 1 pixel equals 0.18um in the coordinates,\n#'\n#' and another element named `tol`, which is the tolerance factor to increase the robustness when comparing the center-to-center distance against the `interaction.range`. This can be the half value of cell/spot size in the unit of um. If the cell/spot size is not known, we provide a function `computeCellDistance` to compute the cell center-to-center distance. `tol` can be the the half value of the minimum center-to-center distance. Of note, CellChat does not need an accurate tolerance factor, which is used for determining whether considering the cell-pair as spatially proximal if their distance is greater than `interaction.range` but smaller than \"`interaction.range` + `tol`\".\n#'\n#'\n#' @param assay Assay to use when the input is a Seurat or SingleCellExperiment object. NB: The data in the `integrated` assay in Seurat is not suitable for CellChat analysis because it contains negative values.\n#' @param do.sparse whether use sparse format\n#'\n#' @return\n#' @export\n#' @importFrom methods as new\n#' @examples\n#' \\dontrun{\n#' Create a CellChat object from single-cell transcriptomics data\n#' # Input is a data matrix\n#' ## create a dataframe consisting of the cell labels\n#' meta = data.frame(labels = cell.labels, row.names = names(cell.labels))\n#' cellChat <- createCellChat(object = data.input, meta = meta, group.by = \"labels\")\n#'\n#' # input is a Seurat object\n#' ## use the default cell identities of Seurat object\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"ident\", assay = \"RNA\")\n#' ## use other meta information as cell groups\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"seurat.clusters\")\n#'\n#' # input is a SingleCellExperiment object\n#' cellChat <- createCellChat(object = sce.obj, group.by = \"sce.clusters\")\n#'\n#' # input is a AnnData object\n#' sce <- zellkonverter::readH5AD(file = \"adata.h5ad\")\n#' assayNames(sce) # retrieve all the available assays within sce object\n#' counts <- assay(sce, \"X\") # add a new assay entry \"logcounts\" if not available and make sure this is the original count data matrix\n#' library.size <- Matrix::colSums(counts)\n#' logcounts(sce) <- log1p(Matrix::t(Matrix::t(counts)/library.size) * 10000)\n#' meta <- as.data.frame(SingleCellExperiment::colData(sce))\n#' cellChat <- createCellChat(object = sce, group.by = \"sce.clusters\")\n#'\n#'\n#' Create a CellChat object from spatial transcriptomics data\n#' # Input is a data matrix\n#' cellChat <- createCellChat(object = data.input, meta = meta, group.by = \"labels\",\n#' datatype = \"spatial\", coordinates = coordinates, spatial.factors = spatial.factors)\n#'\n#' # input is a Seurat object\n#' cellChat <- createCellChat(object = seurat.obj, group.by = \"ident\", assay = \"SCT\",\n#' datatype = \"spatial\", spatial.factors = spatial.factors)\n#'\n#' }\ncreateCellChat <- function(object, meta = NULL, group.by = NULL,\n datatype = c(\"RNA\", \"spatial\"), coordinates = NULL, spatial.factors = NULL,\n assay = NULL, do.sparse = T) {\n datatype <- match.arg(datatype)\n # data matrix as input\n if (inherits(x = object, what = c(\"matrix\", \"Matrix\", \"dgCMatrix\", \"dgRMatrix\",\"CsparseMatrix\"))) {\n print(\"Create a CellChat object from a data matrix\")\n data <- object\n if (is.null(group.by)) {\n group.by <- \"labels\"\n }\n }\n # Seurat object as input\n if (is(object,\"Seurat\")) {\n .error_if_no_Seurat()\n print(\"Create a CellChat object from a Seurat object\")\n if (is.null(assay)) {\n assay = Seurat::DefaultAssay(object)\n if (assay == \"integrated\") {\n warning(\"The data in the `integrated` assay is not suitable for CellChat analysis! Please use the `RNA`, `SCT` or `Spatial` assay! \")\n }\n cat(paste0(\"The `data` slot in the default assay is used. The default assay is \", assay),'\\n')\n }\n if (packageVersion(\"Seurat\") < \"5.0.0\") {\n # data <- Seurat::GetAssayData(object, assay = assay, slot = \"data\") # normalized data matrix\n data <- object[[assay]]@data\n } else {\n data <- object[[assay]]$data\n }\n if (min(data) < 0) {\n stop(\"The data matrix contains negative values. Please ensure the normalized data matrix is used.\")\n }\n if (is.null(meta)) {\n cat(\"The `meta.data` slot in the Seurat object is used as cell meta information\",'\\n')\n meta <- object@meta.data\n meta$ident <- Seurat::Idents(object)\n }\n if (is.null(group.by)) {\n group.by <- \"ident\"\n }\n if (datatype %in% c(\"spatial\")) {\n if (is.null(coordinates)) {\n coordinates <- Seurat::GetTissueCoordinates(object, scale = NULL, cols = c(\"imagerow\", \"imagecol\"))\n }\n }\n\n\n }\n # SingleCellExperiment object as input\n if (is(object,\"SingleCellExperiment\")) {\n print(\"Create a CellChat object from a SingleCellExperiment object\")\n if (is.null(assay)) {\n assay = \"logcounts\"\n }\n if (assay %in% SummarizedExperiment::assayNames(object)) {\n cat(paste0(\"The data in the \", assay, \" assay is used! \"),'\\n')\n data <- SummarizedExperiment::assay(object, assay)\n } else {\n stop(\"SingleCellExperiment object must contain an assay named `logcounts` or the input assay name! Please check the available assaynames via `assayNames(object)`. \\n\")\n }\n if (is.null(meta)) {\n cat(\"The `colData` assay in the SingleCellExperiment object is used as cell meta information\",'\\n')\n meta <- as.data.frame(SingleCellExperiment::colData(object))\n }\n if (is.null(group.by)) {\n stop(\"`group.by` should be defined!\")\n }\n }\n\n if (!inherits(x = data, what = c(\"dgCMatrix\")) & do.sparse) {\n if (inherits(x = data, what = c(\"dgRMatrix\"))) {\n data <- as(data, \"CsparseMatrix\")\n }\n data <- as(data, \"dgCMatrix\")\n }\n\n if (!is.null(meta)) {\n if (inherits(x = meta, what = c(\"matrix\", \"Matrix\",\"DataFrame\"))) {\n meta <- as.data.frame(x = meta)\n }\n if (!is.data.frame(meta)) {\n stop(\"The input `meta` should be a data frame\")\n }\n if (!identical(rownames(meta), colnames(data))) {\n cat(\"The cell barcodes in 'meta' is \", head(rownames(meta)),'\\n')\n warning(\"The cell barcodes in 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of 'mata'!\")\n rownames(meta) <- colnames(data)\n }\n } else {\n meta <- data.frame()\n }\n if (datatype %in% c(\"spatial\")) {\n if (ncol(coordinates) == 2) {\n colnames(coordinates) <- c(\"x_cent\",\"y_cent\")\n } else {\n stop(\"Please check the input 'coordinates' and make sure it is a two column matrix.\")\n }\n if (is.null(spatial.factors) | !(\"ratio\" %in% names(spatial.factors)) | !(\"tol\" %in% names(spatial.factors))) {\n stop(\"spatial.factors with colnames `ratio` and `tol` should be provided!\")\n } else {\n images = list(\"coordinates\" = coordinates,\n \"spatial.factors\" = spatial.factors)\n }\n cat(\"Create a CellChat object from spatial transcriptomics data...\",'\\n')\n } else {\n images <- list()\n }\n\n object <- methods::new(Class = \"CellChat\",\n data = data,\n images = images,\n meta = meta)\n\n if (!is.null(meta) & nrow(meta) > 0) {\n if (!(\"samples\" %in% colnames(meta))) {\n warning(\"The 'meta' data does not have a column named `samples`. We now add this column and all cells are assumed to belong to `sample1`! \\n\")\n meta$samples <- \"sample1\"\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n } else if (is.factor(meta$samples) == FALSE) {\n warning(\"The 'meta$samples' is not a factor. We now force it as a factor! \\n\")\n meta$samples <- factor(meta$samples)\n object@meta <- meta\n }\n\n cat(\"Set cell identities for the new CellChat object\", '\\n')\n if (!(group.by %in% colnames(meta))) {\n stop(\"The 'group.by' is not a column name in the `meta`, which will be used for cell grouping.\")\n }\n object <- setIdent(object, ident.use = group.by) # set \"labels\" as default cell identity\n cat(\"The cell groups used for CellChat analysis are \", toString(levels(object@idents)), '\\n')\n }\n\n object@options$mode <- \"single\"\n object@options$datatype <- datatype\n return(object)\n}\n\n\n#' Merge CellChat objects\n#'\n#' @param object.list A list of multiple CellChat objects\n#' @param add.names A vector containing the name of each dataset\n#' @param merge.data whether merging the data for ALL genes. Default only merges the data of signaling genes\n#' @param cell.prefix whether prefix cell names\n#' @importFrom methods slot new\n#'\n#' @return\n#' @export\n#'\n#' @examples\nmergeCellChat <- function(object.list, add.names = NULL, merge.data = FALSE, cell.prefix = FALSE) {\n if (is.null(add.names)) {\n add.names <- paste(\"Dataset\",1:length(object.list),sep = \"_\")\n }\n slot.name <- c(\"net\", \"netP\", \"idents\" ,\"LR\", \"var.features\", \"images\")\n slot.combined <- vector(\"list\", length(slot.name))\n names(slot.combined) <- slot.name\n for (i in 1:length(slot.name)) {\n object.slot <- vector(\"list\", length(object.list))\n for (j in 1:length(object.list)) {\n object.slot[[j]] <- slot(object.list[[j]], slot.name[i])\n }\n slot.combined[[i]] <- object.slot\n names(slot.combined[[i]]) <- add.names\n }\n\n if (cell.prefix) {\n warning(\"Prefix cell names!\")\n for (i in 1:length(object.list)) {colnames(object.list[[i]]@data) <- paste(colnames(object.list[[i]]@data), add.names[i], sep = \"_\")}\n } else {\n cell.names <- c()\n for (i in 1:length(object.list)) {\n cell.names <- c(cell.names, colnames(object.list[[i]]@data))\n }\n if (sum(duplicated(cell.names))) {\n stop(\"Duplicated cell names were detected across datasets!! Please set cell.prefix = TRUE\")\n }\n }\n\n meta.use <- colnames(object.list[[1]]@meta)\n for (i in 2:length(object.list)) {\n meta.use <- meta.use[meta.use %in% colnames(object.list[[i]]@meta)]\n }\n\n dataset.name <- c()\n cell.names <- c()\n meta.joint <- data.frame()\n for (i in 1:length(object.list)) {\n dataset.name <- c(dataset.name, rep(add.names[i], length(colnames(object.list[[i]]@data))))\n cell.names <- c(cell.names, colnames(object.list[[i]]@data))\n meta.joint <- rbind(meta.joint, object.list[[i]]@meta[ , meta.use, drop = FALSE])\n }\n if (!identical(rownames(meta.joint), cell.names)) {\n cat(\"The cell barcodes in merged 'meta' is \", head(rownames(meta.joint)),'\\n')\n warning(\"The cell barcodes in merged 'meta' is different from those in the used data matrix.\n We now simply assign the colnames in the data matrix to the rownames of merged 'mata'!\")\n rownames(meta.joint) <- cell.names\n }\n\n #dataset.name <- data.frame(dataset.name = dataset.name, row.names = cell.names)\n meta.joint$datasets <- factor(dataset.name, levels = add.names)\n\n genes.use <- rownames(object.list[[1]]@data)\n for (i in 2:length(object.list)) {\n genes.use <- genes.use[genes.use %in% rownames(object.list[[i]]@data)]\n }\n data.joint <- c()\n for (i in 1:length(object.list)) {\n data.joint <- cbind(data.joint, object.list[[i]]@data[genes.use, ])\n }\n gene.signaling.joint = unique(unlist(lapply(object.list, function(x) rownames(x@data.signaling))))\n data.signaling.joint <- data.joint[rownames(data.joint) %in% gene.signaling.joint, ]\n\n idents.joint <- c()\n idents.levels <- c()\n for (i in 1:length(object.list)) {\n idents.joint <- c(idents.joint, as.character(object.list[[i]]@idents))\n idents.levels <- union(idents.levels, levels(object.list[[i]]@idents))\n }\n names(idents.joint) <- cell.names\n idents.joint <- factor(idents.joint, levels = idents.levels)\n slot.combined$idents$joint <- idents.joint\n\n if (merge.data) {\n message(\"Merge the following slots: 'data','data.signaling','images','net', 'netP','meta', 'idents', 'var.features', 'DB', and 'LR'.\")\n merged.object <- methods::new(\n Class = \"CellChat\",\n data = data.joint,\n data.signaling = data.signaling.joint,\n images = slot.combined$images,\n net = slot.combined$net,\n netP = slot.combined$netP,\n meta = meta.joint,\n idents = slot.combined$idents,\n var.features = slot.combined$var.features,\n LR = slot.combined$LR,\n DB = object.list[[1]]@DB)\n } else {\n message(\"Merge the following slots: 'data.signaling','images','net', 'netP','meta', 'idents', 'var.features' , 'DB', and 'LR'.\")\n merged.object <- methods::new(\n Class = \"CellChat\",\n data.signaling = data.signaling.joint,\n images = slot.combined$images,\n net = slot.combined$net,\n netP = slot.combined$netP,\n meta = meta.joint,\n idents = slot.combined$idents,\n var.features = slot.combined$var.features,\n LR = slot.combined$LR,\n DB = object.list[[1]]@DB)\n }\n merged.object@options$mode <- \"merged\"\n\n datatype.joint <- c()\n for (j in 1:length(object.list)) {\n datatype.joint <- union(datatype.joint, slot(object.list[[j]], \"options\")$datatype)\n }\n if (length(datatype.joint) == 1){\n merged.object@options$datatype <- datatype.joint\n } else {\n message(\"The data types in these objects are \", datatype.joint,'\\n')\n stop(\"Comparison analysis is not suggested for different types of data.\")\n }\n return(merged.object)\n}\n\n\n\n#' Update a single CellChat object\n#'\n#' Update a single previously calculated CellChat object for spatial transcriptomics data analysis (version < 2.1.0)\n#'\n#' Update a single previously calculated CellChat object (version < 1.6.0)\n#'\n#' version < 0.5.0: `object@var.features` is now `object@var.features$features`; `object@net$sum` is now `object@net$weight` if `aggregateNet` has been run.\n#'\n#' version 1.6.0: a `object@images` slot is added and `datatype` is added in `object@options$datatype`\n#'\n#' version 2.1.0: a column named `slices` is added in `meta` data for spatial transcriptomics data analysis.\n#'\n#' version 2.1.1: `images$scale.factors` is changed to `images$spatial.factors` for spatial transcriptomics data analysis.\n#'\n#' version 2.1.2: the column `slices` in `object@meta` is renamed as `samples` in order to identify consistent signaling across samples for cell-cell communication analysis.\n#'\n#' version 2.1.3: the slot `object@data.project` is renamed as `object@data.smooth`.\n#'\n#' @param object CellChat object\n#'\n#' @return a updated CellChat object\n#' @export\n#'\nupdateCellChat <- function(object) {\n DB <- object@DB\n # interaction_input <- DB$interaction\n # if ((\"category\" %in% colnames(interaction_input) == FALSE) & (\"annotation\" %in% colnames(interaction_input) == TRUE)) {\n # message(\"Change the column name `annotation` in object@DB$interaction to `category` since CellChat v2\")\n # colnames(interaction_input) <- plyr::mapvalues(colnames(interaction_input),from = c(\"annotation\"), to = c(\"category\"), warn_missing = TRUE)\n # DB$interaction <- interaction_input\n # }\n if (is.character(object@var.features)) {\n message(\"Update slot 'var.features' from a vector to a list\")\n var.features.new <- list(features = object@var.features)\n } else {\n var.features.new <- object@var.features\n }\n if (\"sum\" %in% names(object@net)) {\n net <- object@net\n net$weight <- net$sum\n } else {\n net <- object@net\n }\n if (!(\"mode\" %in% names(object@options))) {\n object@options$mode <- \"single\"\n }\n if (!(\"datatype\" %in% names(object@options))) {\n object@options$datatype <- \"RNA\"\n images = list()\n } else {\n images = object@images\n }\n meta = object@meta\n if (\"slices\" %in% colnames(meta)) {\n meta$samples <- meta$slices\n meta$slices = NULL\n }\n if (!(\"samples\" %in% colnames(meta))) {\n warning(\"The 'meta' data does not have a column named `samples`. We now add this column and all cells are assumed to belong to `sample1`!\")\n meta$samples <- \"sample1\"\n meta$samples <- factor(meta$samples)\n } else if (is.factor(meta$samples) == FALSE) {\n warning(\"The 'meta$samples' is not a factor. We now force it as a factor!\")\n meta$samples <- factor(meta$samples)\n }\n if (object@options$datatype %in% c(\"spatial\")) {\n if (\"scale.factors\" %in% names(object@images)) {\n images$spatial.factors <- as.data.frame(images$scale.factors)\n images$scale.factors <- NULL\n }\n }\n if (\"data.smooth\" %in% methods::slotNames(object) == FALSE) {\n data.smooth <- object@data.project\n } else {\n data.smooth <- object@data.smooth\n }\n object.new <- methods::new(\n Class = \"CellChat\",\n data.raw = object@data.raw,\n data = object@data,\n data.signaling = object@data.signaling,\n data.scale = object@data.scale,\n data.smooth = data.smooth,\n images = images,\n net = net,\n netP = object@netP,\n meta = meta,\n idents = object@idents,\n DB = DB,\n LR = object@LR,\n var.features = var.features.new,\n dr = object@dr,\n options = object@options\n )\n return(object.new)\n}\n\n#' Update a CellChat object by lifting up the cell groups to the same cell labels across all datasets\n#'\n#' This function is useful when comparing inferred communications across different datasets with different cellular compositions\n#'\n#' @param object A single or merged CellChat object\n#' @param group.new A char vector giving the cell labels to lift up. The order of cell labels in the vector will be used for setting the new cell identity.\n#'\n#' If the input is a merged CellChat object and group.new = NULL, it will use the cell labels from one dataset with the maximum number of cell groups\n#'\n#' If the input is a single CellChat object, `group.new` must be defined.\n#'\n#' @return a updated CellChat object\n#'\n#' @export\n#'\nliftCellChat <- function(object, group.new = NULL) {\n if (object@options$mode == \"merged\") {\n idents <- object@idents[1:(length(object@idents)-1)]\n if (is.null(group.new)) {\n group.max.all <- unique(unlist(sapply(idents, levels)))\n group.num <- sapply(idents, nlevels)\n group.num.max <- max(group.num)\n group.max <- levels(idents[[which(group.num == group.num.max)]])\n if (length(group.max) != length(group.max.all)) {\n stop(\"CellChat object cannot lift up due to the missing cell groups in any dataset. Please define the parameter `group.new`!\")\n }\n } else {\n group.max <- group.new\n group.num.max <- length(group.new)\n }\n message(paste0(\"The CellChat object will be lifted up using the cell labels \", paste(group.max, collapse=\", \")))\n for (i in 1:length(idents)) {\n cat(\"Update slots object@net, object@netP, object@idents in dataset \", names(object@idents)[i],'\\n')\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net[[i]]\n group.i <- levels(idents[[i]])\n # group.existing <- group.max[group.max %in% group.i]\n group.existing <- group.i[group.i %in% group.max]\n group.existing.index <- which(group.max %in% group.existing)\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max),\n dimnames = list(group.max, group.max))\n values.new[group.existing.index, group.existing.index] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"pairwiseRank\")) {\n for (k in 1:length(values)) {\n values.new1 <- vector(\"list\", group.num.max)\n values.new1[group.existing.index] <- values[[k]]\n temp <- values[[k]][[1]]\n temp$prob <- 0; temp$pval <- 1\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new1[[kk]] <- temp\n }\n names(values.new1) <- group.max\n values[[k]] <- values.new1\n }\n values.new <- vector(\"list\", group.num.max)\n values.new[group.existing.index] <- values\n temp <- lapply(values.new1, function(x) {\n x$prob <- 0; x$pval <- 1\n return(x)\n })\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new[[kk]] <- temp\n }\n names(values.new) <- group.max\n }\n net[[net.j]] <- values.new\n }\n object@net[[i]] <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n netP <- object@netP[[i]]\n for (netP.j in names(netP)) {\n values <- netP[[netP.j]]\n if (netP.j %in% c(\"pathways\")) {\n values.new <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"prob\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"centr\")) {\n for (k in 1:length(values)) {\n values.new <- lapply(values, function(x) {\n values.new2 <- lapply(x, function(x) {\n values.new1 = as.vector(matrix(0, nrow = 1, ncol = group.num.max))\n values.new1[group.existing.index] <- x\n names(values.new1) <- group.max\n return(values.new1)\n })\n names(values.new2) <- names(x)\n return(values.new2)\n })\n names(values.new) <- names(values)\n }\n netP[[netP.j]] <- values.new\n }\n\n }\n object@netP[[i]] <- netP\n # cat(\"Update slot object@idents...\", '\\n')\n # idents[[i]] <- factor(group.max, levels = group.max)\n idents[[i]] <- factor(idents[[i]], levels = group.max)\n }\n object@idents[1:(length(object@idents)-1)] <- idents\n } else {\n if (is.null(group.new)) {\n stop(\"Please define the parameter `group.new`!\")\n } else {\n group.max <- as.character(group.new)\n group.num.max <- length(group.new)\n message(paste0(\"The CellChat object will be lifted up using the cell labels \", paste(group.max, collapse=\", \")))\n }\n cat(\"Update slots object@net, object@netP, object@idents in a single dataset...\", '\\n')\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net\n idents <- object@idents\n group.i <- levels(idents)\n # group.existing <- group.max[group.max %in% group.i]\n group.existing <- group.i[group.i %in% group.max]\n group.existing.index <- which(group.max %in% group.existing)\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max),\n dimnames = list(group.max, group.max))\n values.new[group.existing.index, group.existing.index] <- values\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"pairwiseRank\")) {\n for (k in 1:length(values)) {\n values.new1 <- vector(\"list\", group.num.max)\n values.new1[group.existing.index] <- values[[k]]\n temp <- values[[k]][[1]]\n temp$prob <- 0; temp$pval <- 1\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new1[[kk]] <- temp\n }\n names(values.new1) <- group.max\n values[[k]] <- values.new1\n }\n values.new <- vector(\"list\", group.num.max)\n values.new[group.existing.index] <- values\n temp <- lapply(values.new1, function(x) {\n x$prob <- 0; x$pval <- 1\n return(x)\n })\n for (kk in setdiff(1:group.num.max, group.existing.index)) {\n values.new[[kk]] <- temp\n }\n names(values.new) <- group.max\n }\n net[[net.j]] <- values.new\n }\n object@net <- net\n\n\n # cat(\"Update slot object@netP...\", '\\n')\n netP <- object@netP\n for (netP.j in names(netP)) {\n values <- netP[[netP.j]]\n if (netP.j %in% c(\"pathways\")) {\n values.new <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"prob\")) {\n values.new <- array(data = 0, dim = c(group.num.max, group.num.max, dim(values)[3]),\n dimnames = list(group.max, group.max, dimnames(values)[[3]]))\n values.new[group.existing.index, group.existing.index, ] <- values\n netP[[netP.j]] <- values.new\n }\n if (netP.j %in% c(\"centr\")) {\n for (k in 1:length(values)) {\n values.new <- lapply(values, function(x) {\n values.new2 <- lapply(x, function(x) {\n values.new1 = as.vector(matrix(0, nrow = 1, ncol = group.num.max))\n values.new1[group.existing.index] <- x\n names(values.new1) <- group.max\n return(values.new1)\n })\n names(values.new2) <- names(x)\n return(values.new2)\n })\n names(values.new) <- names(values)\n }\n }\n netP[[netP.j]] <- values.new\n }\n object@netP <- netP\n\n # cat(\"Update slot object@idents...\", '\\n')\n idents <- factor(idents, levels = group.max)\n object@idents <- idents\n }\n\n return(object)\n}\n\n\n#' Subset CellChat object using a portion of cells\n#'\n#' @param object A CellChat object (either an object from a single dataset or a merged objects from multiple datasets)\n#' @param cells.use a char vector giving the cell barcodes to subset. If cells.use = NULL, USER must define `idents.use`\n#' @param idents.use a subset of cell groups used for analysis\n#' @param group.by cell group information; default is `object@idents`; otherwise it should be one of the column names of the meta slot\n#' @param invert whether invert the idents.use\n#' @param thresh threshold of the p-value for determining significant interaction. A parameter as an input of the function `computeCommunProbPathway`\n#' @importFrom methods slot new\n#'\n#' @return\n#' @export\n#'\nsubsetCellChat <- function(object, cells.use = NULL, idents.use = NULL, group.by = NULL, invert = FALSE, thresh = 0.05) {\n if (!is.null(idents.use)) {\n if (is.null(group.by)) {\n labels <- object@idents\n if (object@options$mode == \"merged\") {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n } else {\n labels <- object@meta[[group.by]]\n }\n if (!is.factor(labels)) {\n labels <- factor(labels)\n }\n level.use0 <- levels(labels)\n level.use <- levels(labels)[levels(labels) %in% unique(labels)]\n\n if (invert) {\n level.use <- level.use[!(level.use %in% idents.use)]\n } else {\n level.use <- level.use[level.use %in% idents.use]\n }\n cells.use.index <- which(as.character(labels) %in% level.use)\n cells.use <- names(labels)[cells.use.index]\n } else if (!is.null(cells.use)) {\n labels <- object@idents\n if (object@options$mode == \"merged\") {\n message(\"Use the joint cell labels from the merged CellChat object\")\n labels <- object@idents$joint\n }\n level.use0 <- levels(labels)\n level.use <- levels(labels)[levels(labels) %in% unique(as.character(labels[cells.use]))]\n cells.use.index <- which(names(labels) %in% cells.use)\n } else {\n stop(\"USER should define either `cells.use` or `idents.use`!\")\n }\n cat(\"The subset of cell groups used for CellChat analysis are \", level.use, '\\n')\n\n if (nrow(object@data) > 0) {\n data.subset <- object@data[, cells.use.index]\n } else {\n data.subset <- matrix(0, nrow = 0, ncol = 0)\n }\n if (nrow(object@data.smooth) > 0) {\n data.smooth.subset <- object@data.smooth[, cells.use.index]\n } else {\n data.smooth.subset <- matrix(0, nrow = 0, ncol = 0)\n }\n data.signaling.subset <- object@data.signaling[, cells.use.index]\n\n meta.subset <- object@meta[cells.use.index, , drop = FALSE]\n\n\n if (object@options$mode == \"merged\") {\n idents <- object@idents[1:(length(object@idents)-1)]\n group.existing <- level.use0[level.use0 %in% level.use]\n group.existing.index <- which(level.use0 %in% level.use)\n net.subset <- vector(\"list\", length = length(object@net))\n netP.subset <- vector(\"list\", length = length(object@netP))\n idents.subset <- vector(\"list\", length = length(idents))\n names(net.subset) <- names(object@net)\n names(netP.subset) <- names(object@netP)\n names(idents.subset) <- names(object@idents[1:(length(object@idents)-1)])\n images.subset <- vector(\"list\", length = length(idents))\n names(images.subset) <- names(object@idents[1:(length(object@idents)-1)])\n\n for (i in 1:length(idents)) {\n cat(\"Update slots object@images, object@net, object@netP, object@idents in dataset \", names(object@idents)[i],'\\n')\n images <- object@images[[i]]\n for (images.j in names(images)) {\n values <- images[[images.j]]\n if (images.j %in% c(\"coordinates\")) {\n values.new <- values[cells.use.index, ]\n images[[images.j]] <- values.new\n }\n if (images.j %in% c(\"distance\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n images[[images.j]] <- values.new\n }\n }\n images.subset[[i]] <- images\n\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net[[i]]\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- values[group.existing.index, group.existing.index, , drop = FALSE]\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n net[[net.j]] <- values.new\n }\n # net[[net.j]] <- values.new\n }\n net.subset[[i]] <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n # netP <- object@netP[[i]]\n # for (netP.j in names(netP)) {\n # values <- netP[[netP.j]]\n # if (netP.j %in% c(\"pathways\")) {\n # values.new <- values\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"prob\")) {\n # values.new <- values[group.existing.index, group.existing.index, ]\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"centr\")) {\n # for (k in 1:length(values)) {\n # values.new <- lapply(values, function(x) {\n # values.new2 <- lapply(x, function(x) {\n # values.new1 <- x[group.existing.index]\n # names(values.new1) <- group.existing\n # return(values.new1)\n # })\n # names(values.new2) <- names(x)\n # return(values.new2)\n # })\n # names(values.new) <- names(values)\n # }\n # }\n # netP[[netP.j]] <- values.new\n # }\n netP = computeCommunProbPathway(net = net.subset[[i]], pairLR.use = object@LR[[i]]$LRsig, thresh = thresh)\n netP$centr = netAnalysis_computeCentrality(net = net.subset[[i]]$prob)\n netP.subset[[i]] <- netP\n idents.subset[[i]] <- idents[[i]][names(idents[[i]]) %in% cells.use]\n idents.subset[[i]] <- factor(idents.subset[[i]], levels = levels(idents[[i]])[levels(idents[[i]]) %in% level.use])\n }\n idents.subset$joint <- factor(object@idents$joint[cells.use.index], levels = level.use)\n\n } else {\n cat(\"Update slots object@images, object@net, object@netP in a single dataset...\", '\\n')\n\n group.existing <- level.use0[level.use0 %in% level.use]\n group.existing.index <- which(level.use0 %in% level.use)\n\n images <- object@images\n for (images.j in names(images)) {\n values <- images[[images.j]]\n if (images.j %in% c(\"coordinates\")) {\n values.new <- values[cells.use.index, ]\n images[[images.j]] <- values.new\n }\n if (images.j %in% c(\"distance\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n images[[images.j]] <- values.new\n }\n }\n images.subset <- images\n\n\n # cat(\"Update slot object@net...\", '\\n')\n net <- object@net\n for (net.j in names(net)) {\n values <- net[[net.j]]\n if (net.j %in% c(\"prob\",\"pval\")) {\n values.new <- values[group.existing.index, group.existing.index, , drop = FALSE]\n net[[net.j]] <- values.new\n }\n if (net.j %in% c(\"count\",\"sum\",\"weight\")) {\n values.new <- values[group.existing.index, group.existing.index, drop = FALSE]\n net[[net.j]] <- values.new\n }\n }\n net.subset <- net\n\n # cat(\"Update slot object@netP...\", '\\n')\n # netP <- object@netP\n # for (netP.j in names(netP)) {\n # values <- netP[[netP.j]]\n # if (netP.j %in% c(\"pathways\")) {\n # values.new <- values\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"prob\")) {\n # values.new <- values[group.existing.index, group.existing.index, ]\n # netP[[netP.j]] <- values.new\n # }\n # if (netP.j %in% c(\"centr\")) {\n # for (k in 1:length(values)) {\n # values.new <- lapply(values, function(x) {\n # values.new2 <- lapply(x, function(x) {\n # values.new1 <- x[group.existing.index]\n # names(values.new1) <- group.existing\n # return(values.new1)\n # })\n # names(values.new2) <- names(x)\n # return(values.new2)\n # })\n # names(values.new) <- names(values)\n # }\n # }\n # netP[[netP.j]] <- values.new\n # }\n netP = computeCommunProbPathway(net = net.subset, pairLR.use = object@LR$LRsig, thresh = thresh)\n netP$centr = netAnalysis_computeCentrality(net = net.subset$prob)\n netP.subset <- netP\n idents.subset <- object@idents[cells.use.index]\n idents.subset <- factor(idents.subset, levels = level.use)\n }\n\n\n object.subset <- methods::new(\n Class = \"CellChat\",\n data = data.subset,\n data.signaling = data.signaling.subset,\n data.smooth = data.smooth.subset,\n images = images.subset,\n net = net.subset,\n netP = netP.subset,\n meta = meta.subset,\n idents = idents.subset,\n var.features = object@var.features,\n LR = object@LR,\n DB = object@DB,\n options = object@options\n )\n return(object.subset)\n}\n\n\n"], ["/CellChat/R/RcppExports.R", "# Generated by using Rcpp::compileAttributes() -> do not edit by hand\n# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393\n\nComputeSNN <- function(nn_ranked, prune) {\n .Call(`_CellChat_ComputeSNN`, nn_ranked, prune)\n}\n\n"], ["/CellChat/R/data.R", "#' Ligand-receptor interactions in CellChat database for mouse\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.mouse\"\n\n#' Ligand-receptor interactions in CellChat database for human\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.human\"\n\n#' Mouse Protein-Protein interactions\n#'\n#' An adjacency matrix of the high confidence known experimental interactions\n#' between mouse proteins on STRINGdb.\n#'\n#' @format A square matrix where A_{ij}=1 if protein i interacts with protein j\n#' @source \\url{http://www.string-db.org/}\n\"PPI.mouse\"\n\n#' Ligand-receptor interactions in CellChat database for Zebrafish\n#'\n#' The ligand-receptor interaction database curated in CellChat tool\n#'\n#' @format A list includes the ligand-receptor interactions\n#' @source \\url{https://github.com/sqjin/CellChat/}\n\"CellChatDB.zebrafish\"\n\n#' Human Protein-Protein interactions\n#'\n#' An adjacency matrix of the high confidence known experimental interactions\n#' between human proteins on STRINGdb.\n#'\n#' @format A square matrix where A_{ij}=1 if protein i interacts with protein j\n#' @source \\url{http://www.string-db.org/}\n\"PPI.human\"\n"], ["/CellChat/R/CellChat-package.R", "## usethis namespace: start\n#' @useDynLib CellChat, .registration = TRUE\n## usethis namespace: end\nNULL\n\n## usethis namespace: start\n#' @importFrom Rcpp sourceCpp\n## usethis namespace: end\nNULL\n"]], "task_instance_info": {"created_time": "2025-08-21 00:57:36", "created_task_model": "DeepSeek-R1", "function_skeleton": "function(object, signaling, signaling.name = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max.individual = NULL, edge.weight.max.aggregate = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, pt.title = 12, title.space = 6, vertex.label.cex = 0.8,from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n out.format = c(\"svg\",\"png\"),\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20, nCol = NULL,\n ...) {}", "code_description": "This code segment functions to: Generate visual representations of cell-cell communication networks using multiple layout options, process interaction probabilities and significance thresholds, and output the results in various image formats for both individual and aggregated signaling pathways."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```r\nnetVisual <- function(object, signaling, signaling.name = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max.individual = NULL, edge.weight.max.aggregate = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, pt.title = 12, title.space = 6, vertex.label.cex = 0.8,from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n out.format = c(\"svg\",\"png\"),\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n out.format <- match.arg(out.format)\n \n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n \n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n \n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n \n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n if (!is.null(pairLR.use)) {\n pairLR.name <- intersect(pairLR.name, pairLR.use.name)\n if (length(pairLR.name) == 0) {\n stop(\"No significant communication for the input L-R pairs!\")\n }\n }\n \n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n \n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n \n if (length(pairLR.name.use) == 0) {\n stop(paste0('No significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n \n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n \n if (length(dim(prob)) == 2) {\n prob <- array(prob, dim = c(dim(prob), 1))\n pval <- array(pval, dim = c(dim(pval), 1))\n }\n \n if (layout == \"hierarchy\") {\n prob.sum <- apply(prob, c(1,2), sum)\n if (is.null(edge.weight.max.individual)) {\n edge.weight.max.individual <- max(prob.sum)\n }\n par(mfrow = c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, \n remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, \n vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, \n edge.weight.max = edge.weight.max.individual, edge.width.max = edge.width.max, title.name = NULL, \n vertex.label.cex = vertex.label.cex, ...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum), vertex.receiver), sources.use = sources.use, \n targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, \n vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, \n weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max = edge.width.max, \n title.name = NULL, vertex.label.cex = vertex.label.cex, ...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n gg <- recordPlot()\n } else if (layout == \"circle\") {\n prob.sum <- apply(prob, c(1,2), sum)\n gg <- netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, \n top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, \n vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, \n edge.width.max = edge.width.max, title.name = paste0(signaling.name, \" signaling pathway network\"), \n vertex.label.cex = vertex.label.cex, ...)\n } else if (layout == \"chord\") {\n if (!is.null(group) & !is.null(cell.order)) {\n warning(\"'cell.order' is ignored when 'group' is provided\")\n }\n prob.sum <- apply(prob, c(1,2), sum)\n gg <- netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, \n remove.isolate = remove.isolate, group = group, cell.order = cell.order, lab.cex = vertex.label.cex, \n small.gap = small.gap, big.gap = big.gap, scale = scale, reduce = reduce, \n title.name = paste0(signaling.name, \" signaling pathway network\"), \n show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y)\n } else if (layout == \"spatial\") {\n prob.sum <- apply(prob, c(1,2), sum)\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, \n point.size = point.size, sources.use = sources.use, targets.use = targets.use, \n remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, \n vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, \n edge.weight.max = edge.weight.max.aggregate, edge.width.max = edge.width.max, \n title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex, ...)\n }\n \n if (out.format == \"svg\") {\n svglite::svglite(file = paste0(signaling.name, \"_\", layout, \"_plot.svg\"), width = height, height = height)\n print(gg)\n dev.off()\n } else if (out.format == \"png\") {\n png(file = paste0(signaling.name, \"_\", layout, \"_plot.png\"), width = height*100, height = height*100)\n print(gg)\n dev.off()\n }\n \n return(gg)\n}\n```", "inference_time": "2025-08-21 00-59-17"}, "editdistance_info": {"edit_distance": 19.6084, "calculate_time": "2025-08-21 00:59:17", "true_code_clean": "function(object, signaling, signaling.name = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max.individual = NULL, edge.weight.max.aggregate = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, pt.title = 12, title.space = 6, vertex.label.cex = 0.8,from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n out.format = c(\"svg\",\"png\"),\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.weight)) {\n vertex.weight <- as.numeric(table(object@idents))\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = F)\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n if (length(pairLR.name.use) == 0) {\n stop(paste0('There is no significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n nRow <- length(pairLR.name.use)\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n if (is.null(nCol)) {\n nCol <- min(length(pairLR.name.use), 2)\n }\n if (length(dim(prob)) == 2) {\n prob <- replicate(1, prob, simplify=\"array\")\n pval <- replicate(1, pval, simplify=\"array\")\n }\n if (is.null(edge.weight.max.individual)) {\n edge.weight.max.individual = max(prob)\n }\n prob.sum <- apply(prob, c(1,2), sum)\n if (is.null(edge.weight.max.aggregate)) {\n edge.weight.max.aggregate = max(prob.sum)\n }\n if (layout == \"hierarchy\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_individual.svg\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_individual.png\"), width = 8, height = nRow*height, units = \"in\",res = 300)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_individual.pdf\"), width = 8, height = nRow*height)\n par(mfrow=c(nRow,2), mar = c(5, 4, 4, 2) +0.1)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_hierarchy1(prob.i, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.i, vertex.receiver = setdiff(1:nrow(prob.i),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max =edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name, \"_hierarchy_aggregate.svg\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name, \"_hierarchy_aggregate.png\"), width = 7, height = 1*height, units = \"in\",res = 300)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name, \"_hierarchy_aggregate.pdf\"), width = 7, height = 1*height)\n par(mfrow=c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum),vertex.receiver), sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = NULL, vertex.label.cex = vertex.label.cex,...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n dev.off()\n }\n } else if (layout == \"circle\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max, title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_circle(prob.i, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, edge.width.max=edge.width.max, title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"spatial\") {\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n signalName_i <- pairLR$interaction_name_2[i]\n prob.i <- prob[,,i]\n netVisual_spatial(prob.i, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = signalName_i, vertex.label.cex = vertex.label.cex,...)\n }\n dev.off()\n }\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, point.size = point.size, sources.use = sources.use, targets.use = targets.use, idents.use = idents.use, remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max, edge.width.max=edge.width.max,title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex,...)\n dev.off()\n }\n } else if (layout == \"chord\") {\n if (is.element(\"svg\", out.format)) {\n svglite::svglite(file = paste0(signaling.name,\"_\", layout, \"_individual.svg\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_individual.png\"), width = height, height = nRow*height, units = \"in\",res = 300)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_individual.pdf\"), width = height, height = nRow*height)\n par(mfrow = c(ceiling(length(pairLR.name.use)/nCol), nCol), xpd=TRUE)\n for (i in 1:length(pairLR.name.use)) {\n title.name <- pairLR$interaction_name_2[i]\n net <- prob[,,i]\n netVisual_chord_cell_internal(net, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = title.name, show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n }\n dev.off()\n }\n if (is.element(\"svg\", out.format)) {\n svglite(file = paste0(signaling.name,\"_\", layout, \"_aggregate.svg\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"png\", out.format)) {\n grDevices::png(paste0(signaling.name,\"_\", layout, \"_aggregate.png\"), width = height, height = 1*height, units = \"in\",res = 300)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n if (is.element(\"pdf\", out.format)) {\n grDevices::cairo_pdf(paste0(signaling.name,\"_\", layout, \"_aggregate.pdf\"), width = height, height = 1*height)\n netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate,\n group = group, cell.order = cell.order,\n lab.cex = vertex.label.cex,small.gap = small.gap, big.gap = big.gap,\n scale = scale, reduce = reduce,\n title.name = paste0(signaling.name, \" signaling pathway network\"), show.legend = show.legend, legend.pos.x = legend.pos.x,legend.pos.y=legend.pos.y)\n dev.off()\n }\n }\n}", "predict_code_clean": "netVisual <- function(object, signaling, signaling.name = NULL, color.use = NULL, vertex.receiver = NULL, sources.use = NULL, targets.use = NULL, top = 1, remove.isolate = FALSE,\n vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = NULL,\n weight.scale = TRUE, edge.weight.max.individual = NULL, edge.weight.max.aggregate = NULL, edge.width.max=8,\n layout = c(\"circle\",\"hierarchy\",\"chord\",\"spatial\"), height = 5, thresh = 0.05, pt.title = 12, title.space = 6, vertex.label.cex = 0.8,from = NULL, to = NULL, bidirection = NULL,vertex.size = NULL,\n out.format = c(\"svg\",\"png\"),\n sample.use = NULL, alpha.image = 0.15, point.size = 1.5,\n group = NULL,cell.order = NULL,small.gap = 1, big.gap = 10, scale = FALSE, reduce = -1, show.legend = FALSE, legend.pos.x = 20,legend.pos.y = 20, nCol = NULL,\n ...) {\n layout <- match.arg(layout)\n out.format <- match.arg(out.format)\n if (!is.null(vertex.size)) {\n warning(\"'vertex.size' is deprecated. Use `vertex.weight`\")\n }\n if (is.null(vertex.size.max)) {\n if (length(unique(vertex.weight)) == 1) {\n vertex.size.max <- 5\n } else {\n vertex.size.max <- 15\n }\n }\n pairLR <- searchPair(signaling = signaling, pairLR.use = object@LR$LRsig, key = \"pathway_name\", matching.exact = T, pair.only = T)\n if (is.null(signaling.name)) {\n signaling.name <- signaling\n }\n net <- object@net\n pairLR.use.name <- dimnames(net$prob)[[3]]\n pairLR.name <- intersect(rownames(pairLR), pairLR.use.name)\n if (!is.null(pairLR.use)) {\n pairLR.name <- intersect(pairLR.name, pairLR.use.name)\n if (length(pairLR.name) == 0) {\n stop(\"No significant communication for the input L-R pairs!\")\n }\n }\n pairLR <- pairLR[pairLR.name, ]\n prob <- net$prob\n pval <- net$pval\n prob[pval > thresh] <- 0\n if (length(pairLR.name) > 1) {\n pairLR.name.use <- pairLR.name[apply(prob[,,pairLR.name], 3, sum) != 0]\n } else {\n pairLR.name.use <- pairLR.name[sum(prob[,,pairLR.name]) != 0]\n }\n if (length(pairLR.name.use) == 0) {\n stop(paste0('No significant communication of ', signaling.name))\n } else {\n pairLR <- pairLR[pairLR.name.use,]\n }\n prob <- prob[,,pairLR.name.use]\n pval <- pval[,,pairLR.name.use]\n if (length(dim(prob)) == 2) {\n prob <- array(prob, dim = c(dim(prob), 1))\n pval <- array(pval, dim = c(dim(pval), 1))\n }\n if (layout == \"hierarchy\") {\n prob.sum <- apply(prob, c(1,2), sum)\n if (is.null(edge.weight.max.individual)) {\n edge.weight.max.individual <- max(prob.sum)\n }\n par(mfrow = c(1,2), ps = pt.title)\n netVisual_hierarchy1(prob.sum, vertex.receiver = vertex.receiver, sources.use = sources.use, targets.use = targets.use, \n remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, \n vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, \n edge.weight.max = edge.weight.max.individual, edge.width.max = edge.width.max, title.name = NULL, \n vertex.label.cex = vertex.label.cex, ...)\n netVisual_hierarchy2(prob.sum, vertex.receiver = setdiff(1:nrow(prob.sum), vertex.receiver), sources.use = sources.use, \n targets.use = targets.use, remove.isolate = remove.isolate, top = top, color.use = color.use, \n vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, \n weight.scale = weight.scale, edge.weight.max = edge.weight.max.individual, edge.width.max = edge.width.max, \n title.name = NULL, vertex.label.cex = vertex.label.cex, ...)\n graphics::mtext(paste0(signaling.name, \" signaling pathway network\"), side = 3, outer = TRUE, cex = 1, line = -title.space)\n gg <- recordPlot()\n } else if (layout == \"circle\") {\n prob.sum <- apply(prob, c(1,2), sum)\n gg <- netVisual_circle(prob.sum, sources.use = sources.use, targets.use = targets.use, remove.isolate = remove.isolate, \n top = top, color.use = color.use, vertex.weight = vertex.weight, vertex.weight.max = vertex.weight.max, \n vertex.size.max = vertex.size.max, weight.scale = weight.scale, edge.weight.max = edge.weight.max.aggregate, \n edge.width.max = edge.width.max, title.name = paste0(signaling.name, \" signaling pathway network\"), \n vertex.label.cex = vertex.label.cex, ...)\n } else if (layout == \"chord\") {\n if (!is.null(group) & !is.null(cell.order)) {\n warning(\"'cell.order' is ignored when 'group' is provided\")\n }\n prob.sum <- apply(prob, c(1,2), sum)\n gg <- netVisual_chord_cell_internal(prob.sum, color.use = color.use, sources.use = sources.use, targets.use = targets.use, \n remove.isolate = remove.isolate, group = group, cell.order = cell.order, lab.cex = vertex.label.cex, \n small.gap = small.gap, big.gap = big.gap, scale = scale, reduce = reduce, \n title.name = paste0(signaling.name, \" signaling pathway network\"), \n show.legend = show.legend, legend.pos.x = legend.pos.x, legend.pos.y = legend.pos.y)\n } else if (layout == \"spatial\") {\n prob.sum <- apply(prob, c(1,2), sum)\n coordinates <- object@images$coordinates\n labels <- object@idents\n meta.t <- object@meta\n meta.t$labels <- labels\n gg <- netVisual_spatial(prob.sum, coordinates = coordinates, meta = meta.t, sample.use = sample.use, alpha.image = alpha.image, \n point.size = point.size, sources.use = sources.use, targets.use = targets.use, \n remove.isolate = remove.isolate, top = top, color.use = color.use, vertex.weight = vertex.weight, \n vertex.weight.max = vertex.weight.max, vertex.size.max = vertex.size.max, weight.scale = weight.scale, \n edge.weight.max = edge.weight.max.aggregate, edge.width.max = edge.width.max, \n title.name = paste0(signaling.name, \" signaling pathway network\"), vertex.label.cex = vertex.label.cex, ...)\n }\n if (out.format == \"svg\") {\n svglite::svglite(file = paste0(signaling.name, \"_\", layout, \"_plot.svg\"), width = height, height = height)\n print(gg)\n dev.off()\n } else if (out.format == \"png\") {\n png(file = paste0(signaling.name, \"_\", layout, \"_plot.png\"), width = height*100, height = height*100)\n print(gg)\n dev.off()\n }\n return(gg)\n}"}}