├── .DS_Store ├── .Rbuildignore ├── .Rhistory ├── .gitattributes ├── .gitignore ├── DESCRIPTION ├── LICENSE ├── NAMESPACE ├── NeuronChat.Rproj ├── R ├── NeuronChat_source_file.R ├── network_analysis.R ├── spatial_analysis_visualization.R ├── update_NeuronChatDB.R └── visualization.R ├── README.md ├── data ├── cortex_data.rda ├── df_interactionDB_human.rda ├── df_interactionDB_mouse.rda ├── interactionDB_human.rda └── interactionDB_mouse.rda ├── man ├── AnyMatrix-class.Rd ├── NeuronChat-class.Rd ├── barplot_proximity.Rd ├── cal_expr_by_group.Rd ├── cal_prob_mtx_downstream.Rd ├── cell_proximity_enrichment_score.Rd ├── cell_proximity_enrichment_score_multiple.Rd ├── cell_proximity_enrichment_score_single.Rd ├── compareInteractions_Neuron.Rd ├── computeNetSimilarityPairwise_Neuron.Rd ├── computeNetSimilarity_Neuron.Rd ├── createNeuronChat.Rd ├── heatmap_aggregated.Rd ├── heatmap_single.Rd ├── identifyCommunicationPatterns_Neuron.Rd ├── lig_tar_heatmap.Rd ├── mergeNeuronChat.Rd ├── netAnalysis_river_Neuron.Rd ├── netVisual_chord_neuron.Rd ├── netVisual_circle_compare.Rd ├── netVisual_circle_neuron.Rd ├── netVisual_embeddingPairwiseZoomIn_Neuron.Rd ├── netVisual_embeddingPairwise_Neuron.Rd ├── netVisual_embeddingZoomIn_Neuron.Rd ├── netVisual_embedding_Neuron.Rd ├── netVisual_proximity.Rd ├── net_aggregation.Rd ├── neuron_chat_downstream.Rd ├── rankNet_Neuron.Rd ├── run_NeuronChat.Rd ├── selectK_Neuron.Rd ├── spatialDistribution.Rd ├── spatialMap.Rd └── update_interactionDB.Rd ├── tmp.R └── vignettes ├── .gitignore ├── NeuronChat-Tutorial.Rmd ├── NeuronChat-Tutorial.html ├── Spatial_analysis.Rmd ├── Spatial_analysis.html ├── Update_NeuronChat_database.Rmd ├── Update_NeuronChat_database.html ├── comparison.Rmd └── comparison.html /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wei-BioMath/NeuronChat/36e06b29397558ba2433bd5deccacd7f2071170e/.DS_Store -------------------------------------------------------------------------------- /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | -------------------------------------------------------------------------------- /.Rhistory: -------------------------------------------------------------------------------- 1 | for(i in 1:length(receptor_subunit_coeff)){ 2 | ind_i <- which(receptor_subunit_group==i) 3 | if(length(ind_i)==1){ 4 | receptor_subunit_expr_tmp[1:cellgroup_number,i] <- expr_gene[1:cellgroup_number,length(lig_contributor_new)+ind_i] 5 | } else if(length(ind_i)>1) { 6 | receptor_subunit_expr_tmp[1:cellgroup_number,i] <- apply(expr_gene[1:cellgroup_number,length(lig_contributor_new)+ind_i],MARGIN = 1, function(x) mean(x)) 7 | } else { 8 | receptor_subunit_expr_tmp[1:cellgroup_number,i] <- 1 9 | } 10 | } 11 | if(length(receptor_subunit_coeff)>1){ 12 | rep_coeff <- rep(1:length(receptor_subunit_coeff),receptor_subunit_coeff) 13 | receptor_subunit_expr <- apply(receptor_subunit_expr_tmp[,rep_coeff], MARGIN = 1, function(x) exp(mean(log(x))))} else { 14 | receptor_subunit_expr <- receptor_subunit_expr_tmp 15 | } 16 | names(receptor_subunit_expr) <- cell.rownames 17 | # # targets_up 18 | # if(length(targets_up)>0){ 19 | # targets_up_expr <- as.data.frame(cal_expr_by_group(df,targets_up,mean_method)) 20 | # targets_up_max <- apply(targets_up_expr,2,FUN = max) 21 | # targets_up_nonzero <- which(targets_up_max>0) 22 | # if(length(targets_up_nonzero)>0){ 23 | # targets_up_avg <- apply(targets_up_expr[,targets_up_nonzero,drop=FALSE],1,FUN = mean)} 24 | # } 25 | # # targets_down 26 | # if(length(targets_down)>0){ 27 | # targets_down_expr <- as.data.frame(cal_expr_by_group(df,targets_down,mean_method )) 28 | # targets_down_max <- apply(targets_down_expr,2,FUN = max) 29 | # targets_down_nonzero <- which(targets_down_max>0) 30 | # if(length(targets_down_nonzero)>0){ 31 | # targets_down_avg <- apply(targets_down_expr[,targets_down_nonzero,drop=FALSE],1,FUN = mean)} 32 | # } 33 | # 34 | # # targets_nichenet_avg <- rep(0,cellgroup_number) 35 | # if(length(targets_nichenet)>0){ 36 | # targets_nichenet <- targets_nichenet[1:N] 37 | # targets_nichenet_expr <- cal_expr_by_group(df,names(targets_nichenet),mean_method) 38 | # targets_nichenet_max <- apply(targets_nichenet_expr,2,FUN = max) 39 | # # targets_nichenet_nonzero <- which(targets_nichenet_max>0) 40 | # # if(length(targets_nichenet_nonzero)>0){ 41 | # targets_nichenet_avg <- as.matrix(targets_nichenet_expr[,names(targets_nichenet),with=FALSE]) %*% as.matrix(targets_nichenet/sum(targets_nichenet))#} 42 | # } 43 | # compute prob_mtx without downstream weight 44 | prob_mtx0 <- ((as.matrix(lig_contributor_expr))%*%t(as.matrix(receptor_subunit_expr))) 45 | colnames(prob_mtx0) <- cell.rownames 46 | rownames(prob_mtx0) <- cell.rownames 47 | # # downstream weight 48 | # exp_prob_mtx0 <- prob_mtx0^2/(prob_mtx0^2+1) #exp(-1/prob_mtx0); 49 | # targets_up_weight <- rep(1,cellgroup_number)%*%t(targets_up_avg); 50 | # # exp_targets_up_weight <- exp(-1/targets_up_weight) 51 | # # exp_targets_up_weight <- 0.01+exp_targets_up_weight*exp_prob_mtx0/(exp_prob_mtx0+exp_targets_up_weight+1e-16) 52 | # targets_up_weight <- 1+prob_mtx0*targets_up_weight^1/(targets_up_weight^1+prob_mtx0+1e-6)#*(length(targets_up_avg))^0.5 53 | # targets_down_weight <- rep(1,cellgroup_number)%*%t(targets_down_avg); 54 | # # exp_targets_down_weight <- exp(-targets_down_weight) 55 | # # exp_targets_down_weight <- exp_targets_down_weight*exp_prob_mtx0/(exp_prob_mtx0+exp_targets_down_weight+1e-16) 56 | # targets_down_weight <- 1-targets_down_weight^1/(targets_down_weight^1+prob_mtx0+1e-6) 57 | # targets_nichenet_weight <- rep(1,cellgroup_number)%*%t(targets_nichenet_avg); 58 | # targets_nichenet_weight <- 1+1*prob_mtx0*targets_nichenet_weight^1/(targets_nichenet_weight^1+prob_mtx0+1e-6) 59 | # #targets_nichenet_weight <- prob_mtx0*targets_nichenet_weight^1/(targets_nichenet_weight^1+prob_mtx0+1e-6) 60 | # # compute prob_mtx with downstream weight 61 | # # prob_mtx <- prob_mtx0^1*targets_up_weight*targets_down_weight 62 | # prob_mtx <- prob_mtx0^1*targets_nichenet_weight 63 | prob_mtx <- prob_mtx0 64 | } else if(method=='CellChat'){ 65 | if(length(lig_contributor_new)>1){ 66 | lig_contributor_expr <- apply(expr_gene[1:cellgroup_number,lig_contributor_new],MARGIN = 1, function(x) exp(mean(log(x)))) 67 | } else { lig_contributor_expr <- expr_gene[1:cellgroup_number,lig_contributor_new] } 68 | if(length(receptor_subunit_new)>1){ 69 | receptor_subunit_expr <- apply(expr_gene[1:cellgroup_number,receptor_subunit_new], MARGIN = 1, function(x) exp(mean(log(x)))) 70 | } else { receptor_subunit_expr <- expr_gene[1:cellgroup_number,receptor_subunit_new]} 71 | names(lig_contributor_expr) <- cell.rownames 72 | names(receptor_subunit_expr) <- cell.rownames 73 | prob_mtx0 <- ((as.matrix(lig_contributor_expr))%*%t(as.matrix(receptor_subunit_expr))) 74 | hill <- function(x,K){ 75 | return(x^2/(x^2+K^2)) 76 | } 77 | prob_mtx0 <- hill((as.matrix(lig_contributor_expr)),K)%*%hill(t(as.matrix(receptor_subunit_expr)),K) 78 | colnames(prob_mtx0) <- cell.rownames 79 | rownames(prob_mtx0) <- cell.rownames 80 | prob_mtx <- prob_mtx0 81 | } else if(method=='CellPhoneDB'){ 82 | if(length(lig_contributor_new)>1){ 83 | lig_contributor_expr <- apply(expr_gene[1:cellgroup_number,lig_contributor_new],MARGIN = 1, function(x) min(x)) 84 | } else { lig_contributor_expr <- expr_gene[1:cellgroup_number,lig_contributor_new] } 85 | if(length(receptor_subunit_new)>1){ 86 | receptor_subunit_expr <- apply(expr_gene[1:cellgroup_number,receptor_subunit_new], MARGIN = 1, function(x) min(x)) 87 | } else { receptor_subunit_expr <- expr_gene[1:cellgroup_number,receptor_subunit_new]} 88 | names(lig_contributor_expr) <- cell.rownames 89 | names(receptor_subunit_expr) <- cell.rownames 90 | prob_mtx0_lig <- as.matrix(lig_contributor_expr)%*%matrix(rep(1,length(cell.rownames)),nrow = 1,ncol = length(cell.rownames)) 91 | prob_mtx0_rec <- matrix(rep(1,length(cell.rownames)),nrow = length(cell.rownames),ncol =1 )%*%t(as.matrix(receptor_subunit_expr)) 92 | # prob_mtx0 <- ((as.matrix(lig_contributor_expr))%*%matrix(rep(1,length(cell.rownames)),nrow = 1,ncol = length(cell.rownames))+ matrix(rep(1,length(cell.rownames)),nrow = length(cell.rownames),ncol =1 )%*%t(as.matrix(receptor_subunit_expr))) 93 | prob_mtx0 <- (prob_mtx0_lig+ prob_mtx0_rec)/2 94 | prob_mtx0 <- prob_mtx0*(prob_mtx0_lig>0)*(prob_mtx0_rec>0) 95 | colnames(prob_mtx0) <- cell.rownames 96 | rownames(prob_mtx0) <- cell.rownames 97 | prob_mtx <- prob_mtx0 98 | } 99 | rownames(prob_mtx) <- cell.rownames 100 | colnames(prob_mtx) <- cell.rownames 101 | prob_mtx <- prob_mtx[sender,receiver] 102 | prob_mtx0 <- prob_mtx0[sender,receiver] 103 | # prob_mtx <- exp_prob_mtx0*targets_up_weight*targets_down_weight 104 | # prob_mtx <- exp_prob_mtx0*exp_targets_up_weight*exp_targets_down_weight 105 | my_list <- list("prob_mtx" = prob_mtx, "ligand_score" = lig_contributor_expr, "receptor_score" = receptor_subunit_expr, "cell_group"=rownames(expr_gene), 106 | "prob_mtx0" = prob_mtx0, "targets_up_score" = targets_up_avg, "targets_down_score" = targets_down_avg, "targets_nichenet_score"=targets_nichenet_avg) 107 | return(my_list) 108 | } 109 | #' Calculate the communication strength matrix for a single ligand-target pair (with permutation test) 110 | #' @param df a data frame or data.table containing signaling gene expression (row: cell; column: genes; the last column is cell group labels) 111 | #' @param sender sending cell groups 112 | #' @param receiver receiving cell groups 113 | #' @param interaction_name name of the ligand-target interaction 114 | #' @param lig_contributor a vector with gene symbols that are regarded as ligand contributors 115 | #' @param lig_contributor_group a vector indicating the grouping of ligand contributors 116 | #' @param lig_contributor_coeff a vector with stoichiometry of each group of ligand contributors for calculating ligand abundance 117 | #' @param receptor_subunit_new a vector with updated gene symbols (removing those excluded from the expression data) that are regarded as target subunits 118 | #' @param receptor_subunit_group a vector indicating the grouping of target subunits 119 | #' @param receptor_subunit_coeff a vector with stoichiometry of each group of target subunits for calculating target abundance 120 | #' @param M number of permutation tests 121 | #' @param fdr cutoff value that determines the significance of detected link 122 | #' @param targets_up deprecated 123 | #' @param targets_down deprecated 124 | #' @param targets_nichenet deprecated 125 | #' @param N deprecated 126 | #' @param K deprecated 127 | #' 128 | #' @return 129 | #' @export 130 | #' 131 | #' @examples 132 | neuron_chat_downstream <- function(df,sender,receiver,interaction_name,lig_contributor,lig_contributor_group,lig_contributor_coeff, 133 | receptor_subunit,receptor_subunit_group,receptor_subunit_coeff,targets_up,targets_down,targets_nichenet,N,M,fdr,K=0.5,method=NULL,mean_method=NULL){ 134 | ind_lig <- which(lig_contributor %in% colnames(df));lig_contributor_new <- lig_contributor[ind_lig] 135 | ind_re <- which(receptor_subunit %in% colnames(df));receptor_subunit_new <- receptor_subunit[ind_re] 136 | lig_contributor_group <- lig_contributor_group[ind_lig] 137 | receptor_subunit_group <- receptor_subunit_group[ind_re] 138 | targets_up <- targets_up[which(targets_up %in% colnames(df))] 139 | targets_down <- targets_down[which(targets_down %in% colnames(df))] 140 | targets_nichenet <- targets_nichenet[which(names(targets_nichenet) %in% colnames(df))] 141 | my_list <- cal_prob_mtx_downstream(df,sender,receiver,lig_contributor_new,lig_contributor_group,lig_contributor_coeff, receptor_subunit_new,receptor_subunit_group,receptor_subunit_coeff,targets_up,targets_down,targets_nichenet,N,K,method,mean_method) 142 | prob_mtx <- my_list$prob_mtx 143 | # FC.lig <- log2(max(my_list$ligand_score+1e-3)/min(my_list$ligand_score+1e-3)) 144 | # FC.rec <- log2(max(my_list$receptor_score+1e-3)/min(my_list$receptor_score+1e-3)) 145 | FC.lig <- max(my_list$ligand_score) - min(my_list$ligand_score) 146 | FC.rec <- max(my_list$receptor_score) - min(my_list$receptor_score) 147 | FC <- max(FC.lig,FC.rec) 148 | #FC <- min(FC.lig,FC.rec) 149 | ## permutation 150 | if(M==0 | max(prob_mtx)==0){net <- prob_mtx;pvalue <- NA*net} else { 151 | #prob_mtx_permutation <- array(0,c(dim(prob_mtx)[1],dim(prob_mtx)[2],M)) 152 | pvalue <- matrix(0, dim(prob_mtx)[1],dim(prob_mtx)[2]); 153 | # for(j in 1:M){ 154 | # df_j <- df; 155 | # df_j$cell_subclass[df$cell_subclass %in% sender] <- sample(df$cell_subclass[df$cell_subclass %in% sender],length(df$cell_subclass[df$cell_subclass %in% sender]), FALSE) 156 | # df_j$cell_subclass[df$cell_subclass %in% receiver] <- sample(df$cell_subclass[df$cell_subclass %in% receiver],length(df$cell_subclass[df$cell_subclass %in% receiver]), FALSE) 157 | # my_list_temp <- cal_prob_mtx_downstream(df_j,sender,receiver,lig_contributor_new,lig_contributor_group,lig_contributor_coeff,receptor_subunit_new,receptor_subunit_group,receptor_subunit_coeff,targets_up,targets_down,targets_nichenet,N) 158 | # prob_mtx_permutation[,,j] <- my_list_temp$prob_mtx 159 | # pvalue <- pvalue+1*(prob_mtx_permutation[,,j]>prob_mtx) 160 | # } 161 | df_j <- df; 162 | prob_mtx_permutation <- sapply(seq_along(1:M), function(j) { 163 | df_j$cell_subclass[df$cell_subclass %in% sender] <- sample(df$cell_subclass[df$cell_subclass %in% sender],length(df$cell_subclass[df$cell_subclass %in% sender]), FALSE) 164 | df_j$cell_subclass[df$cell_subclass %in% receiver] <- sample(df$cell_subclass[df$cell_subclass %in% receiver],length(df$cell_subclass[df$cell_subclass %in% receiver]), FALSE) 165 | my_list_temp <- cal_prob_mtx_downstream(df_j,sender,receiver,lig_contributor_new,lig_contributor_group,lig_contributor_coeff,receptor_subunit_new,receptor_subunit_group,receptor_subunit_coeff,targets_up,targets_down,targets_nichenet,N,K,method,mean_method) 166 | prob_mtx_permutation_j <- (my_list_temp$prob_mtx > prob_mtx)*1 167 | prob_mtx_permutation_j 168 | },simplify = 'array') 169 | pvalue <- apply(prob_mtx_permutation,1:2,sum) 170 | pvalue <- pvalue/M 171 | pvalue_v <- c(pvalue) 172 | ## FDR correction Benjamini-Hochberg Procedure 173 | pvalue_v_sort <- sort.int(pvalue_v, decreasing = FALSE, index.return = TRUE) 174 | alpha_i <- fdr*(1:length(pvalue_v))/length(pvalue_v) 175 | k <- which(pvalue_v_sort$x0)){ 179 | # net <- prob_mtx/max(prob_mtx)} else {net <- prob_mtx} 180 | net <- prob_mtx_sig; 181 | # net_old <-net 182 | # net[pvalue>0.05] <- 0 183 | # net.rownames <- rownames(prob_mtx) 184 | } 185 | # net.rownames <- sort(unique(target_df$cell_subclass)) 186 | # rownames(net)<- net.rownames;colnames(net)<- net.rownames 187 | # plot 188 | # library(GGally);library(network);library(sna);library(ggplot2);library(reshape2);library(circlize) 189 | # # q90 <- quantile(net,0.95);net[net0){ 212 | # h1 <- Heatmap(net, name = "Prob", left_annotation =left_Annotation,bottom_annotation = bottom_Annotation, 213 | # top_annotation = column_ha, right_annotation = row_ha,col = col_map, 214 | # cluster_rows = FALSE,cluster_columns=FALSE, 215 | # split= big_group[rownames(net)],column_split = big_group[rownames(net)], 216 | # row_names_side='left',column_names_side='bottom', 217 | # row_title='Sender',row_title_side='left',row_title_gp = gpar(fontsize = 16), 218 | # column_title='Receiver',column_title_side = "bottom",column_title_gp = gpar(fontsize = 16))#, 219 | # # width = unit(11,'cm'), 220 | # # height = unit(11,'cm')) 221 | # # print(h1) 222 | # draw(h1, column_title = interaction_name, column_title_gp = gpar(fontsize = 16))} 223 | list_return <- list(net=net,FC=FC,pvalue=pvalue,net0=my_list$prob_mtx, info=sum(net),ligand.abundance = my_list$ligand_score, target.abundance = my_list$receptor_score) 224 | return(list_return) 225 | # net; color.use = NULL;title.name = NULL; sources.use = NULL; targets.use = NULL; remove.isolate = FALSE; top = 1; 226 | # weight.scale = FALSE; vertex.weight = 20; vertex.weight.max = NULL; vertex.size.max = NULL; vertex.label.cex=1;vertex.label.color= "black"; 227 | # edge.weight.max = NULL; edge.width.max=8; alpha.edge = 0.6; label.edge = FALSE;edge.label.color='black';edge.label.cex=0.8; 228 | # edge.curved=0.2;shape='circle';layout=in_circle(); margin=0.2; vertex.size = NULL; 229 | # arrow.width=1;arrow.size = 0.2 230 | # CellChat::netVisual_chord_cell_internal(net, color.use = scPalette(nrow(net)), sources.use = net.rownames, targets.use = net.rownames, 231 | # group=group,remove.isolate = FALSE,scale = FALSE, 232 | # title.name = interaction_name) 233 | # chordDiagram(net, group = group, grid.col = group, 234 | # reduce=-1,scale=FALSE,link.visible = net > 0.05, 235 | # small.gap=1, big.gap=10, 236 | # directional = -1, direction.type = c("diffHeight","arrows"), 237 | # link.arr.type = 'big.arrow') 238 | } 239 | #' Calculate the communication strength matrix for all ligand-target pairs 240 | #' @param object a NeuronChat object 241 | #' @param sender sending cell groups 242 | #' @param receiver receiving cell groups 243 | #' @param M number of permutation tests 244 | #' @param fdr cutoff value that determines the significance of detected link 245 | #' @param N deprecated 246 | #' @param K deprecated 247 | #' @param strict indicating whether the calculation of communication score for an ligand-target pair requires that input data include at least one gene for each contributing gene group. strict=1 means 'require', strict=0 means not 'require'. Default value is 1 248 | #' 249 | #' @return 250 | #' @export 251 | #' 252 | #' @examples 253 | run_NeuronChat <- function(object=object,sender=NULL,receiver=NULL,N=0,M=100,fdr=0.05,K=0.5,method=NULL,mean_method=NULL,strict=1){ 254 | start.time <- Sys.time() 255 | # interactionDB <- readRDS('interactionDB_interactor.rds') 256 | # interactionDB <- interactionDB_interactor_full_synGO 257 | interactionDB <- object@DB 258 | # ligand_target_matrix_mgi <- readRDS('~/Documents/CellChat/Rcode_cellchat_VISp_ALM/ligand_target_matrix_mgi.rds') 259 | net0_all <- list() # original probability mtx 260 | net_all <- list() # probability mtx filtered by pvalue with cutoff 0.05 261 | pvalue_all <- list() 262 | FC_all <- rep(0,length(interactionDB)) 263 | info_all <- rep(0,length(interactionDB)) 264 | net.rownames <- sort(unique(object@data.signaling$cell_subclass),method='radix') 265 | if(is.null(sender)){sender <- net.rownames};if(is.null(receiver)){receiver <- net.rownames} 266 | ligand.abundance_all <- matrix(0,nrow=length(net.rownames),ncol=length(interactionDB)) 267 | target.abundance_all <- ligand.abundance_all 268 | for(j in 1:length(interactionDB)){ 269 | interaction_name <- names(interactionDB)[j] 270 | lig_contributor <- interactionDB[[j]]$lig_contributor 271 | receptor_subunit <- interactionDB[[j]]$receptor_subunit 272 | lig_contributor_group <- interactionDB[[j]]$lig_contributor_group 273 | lig_contributor_coeff <- interactionDB[[j]]$lig_contributor_coeff 274 | receptor_subunit_group <- interactionDB[[j]]$receptor_subunit_group 275 | receptor_subunit_coeff <- interactionDB[[j]]$receptor_subunit_coeff 276 | # targets_up <- interactionDB[[j]]$targets_up 277 | # targets_up <- interactionDB[[j]]$interactors 278 | # targets_down <- interactionDB[[j]]$targets_down 279 | # targets_up <- character(0)# interactionDB[[j]]$interactors 280 | targets_up <- character(0) 281 | targets_down <- character(0) 282 | #if(receptor_subunit %in% colnames(ligand_target_matrix_mgi)){ 283 | # targets_nichenet <- sort(ligand_target_matrix_mgi[,receptor_subunit],decreasing = T) 284 | targets_nichenet <- character(0) 285 | #} else {targets_nichenet <- character(0)} 286 | lig_boolean_group <- (lig_contributor %in% names(object@data.signaling))*lig_contributor_group; 287 | rec_boolean_group <- (receptor_subunit %in% names(object@data.signaling))*receptor_subunit_group; 288 | if(strict==1){ 289 | lig_boolean <- prod(unique(lig_contributor_group) %in% lig_boolean_group) 290 | rec_boolean <- prod(unique(receptor_subunit_group) %in% rec_boolean_group) 291 | } else { 292 | lig_boolean <- sum(unique(lig_contributor_group) %in% lig_boolean_group)>0 293 | rec_boolean <- sum(unique(receptor_subunit_group) %in% rec_boolean_group)>0 294 | } 295 | if(prod(lig_boolean,rec_boolean)==0){net_all[[j]]=matrix(0,nrow=length(sender),ncol=length(receiver), 296 | dimnames=list(sender,receiver)) 297 | #if(prod((c(lig_contributor,receptor_subunit) %in% names(object@data.signaling)))==0){net_all[[j]]=matrix(0,nrow=length(sender),ncol=length(receiver), 298 | # dimnames=list(sender,receiver)) 299 | net0_all[[j]] <- net_all[[j]] 300 | pvalue_all[[j]] <- net_all[[j]] 301 | } else 302 | {tmp <- neuron_chat_downstream(object@data.signaling,sender,receiver,interaction_name,lig_contributor,lig_contributor_group,lig_contributor_coeff,receptor_subunit,receptor_subunit_group,receptor_subunit_coeff,targets_up,targets_down,targets_nichenet,N,M,fdr,K,method,mean_method) 303 | net_all[[j]] <- tmp$net 304 | net0_all[[j]] <- tmp$net0 305 | pvalue_all[[j]] <- tmp$pvalue 306 | FC_all[j] <- tmp$FC 307 | info_all[j] <- tmp$info 308 | ligand.abundance_all[1:length(net.rownames),j] <- tmp$ligand.abundance 309 | target.abundance_all[1:length(net.rownames),j] <- tmp$target.abundance 310 | } 311 | } 312 | rownames(ligand.abundance_all) <- names(tmp$ligand.abundance);colnames(ligand.abundance_all) <- names(interactionDB) 313 | rownames(target.abundance_all) <- names(tmp$target.abundance);colnames(target.abundance_all) <- names(interactionDB) 314 | names(net_all) <- names(interactionDB) 315 | names(net0_all) <- names(interactionDB) 316 | # tmp_list <- future_lapply(seq_along(1:length(interactionDB)),function(j){ 317 | # interaction_name <- names(interactionDB)[j] 318 | # lig_contributor <- interactionDB[[j]]$lig_contributor 319 | # receptor_subunit <- interactionDB[[j]]$receptor_subunit 320 | # lig_contributor_group <- interactionDB[[j]]$lig_contributor_group 321 | # lig_contributor_coeff <- interactionDB[[j]]$lig_contributor_coeff 322 | # receptor_subunit_group <- interactionDB[[j]]$receptor_subunit_group 323 | # receptor_subunit_coeff <- interactionDB[[j]]$receptor_subunit_coeff 324 | # # targets_up <- interactionDB[[j]]$targets_up 325 | # # targets_down <- interactionDB[[j]]$targets_down 326 | # targets_up <- character(0)# interactionDB[[j]]$interactors 327 | # targets_down <- character(0) 328 | # if(receptor_subunit %in% colnames(ligand_target_matrix_mgi)){ 329 | # # targets_nichenet <- sort(ligand_target_matrix_mgi[,receptor_subunit],decreasing = T) 330 | # targets_nichenet <- character(0) 331 | # } else {targets_nichenet <- character(0)} 332 | # if(prod((c(lig_contributor,receptor_subunit) %in% names(object@data.signaling)))==0){tmp$net <- matrix(0,nrow=length(sender),ncol=length(receiver), 333 | # dimnames=list(sender,receiver)) 334 | # tmp$net0 <- tmp$net 335 | # tmp$pvalue<- tmp$net0 336 | # tmp$FC <- FC_all[j] 337 | # tmp$info <- 0 338 | # tmp$ligand.abundance <- ligand.abundance_all[1:length(net.rownames),j] 339 | # tmp$target.abundance <- ligand.abundance_all[1:length(net.rownames),j] 340 | # } else 341 | # {tmp <- neuron_chat_downstream(object@data.signaling,sender,receiver,interaction_name,lig_contributor,lig_contributor_group,lig_contributor_coeff,receptor_subunit,receptor_subunit_group,receptor_subunit_coeff,targets_up,targets_down,targets_nichenet,N,M) 342 | # } 343 | # tmp 344 | # },future.seed = TRUE) 345 | # for(j in length(tmp_list)){ 346 | # net_all[[j]] <- tmp_list[[j]]$net 347 | # net0_all[[j]] <- tmp_list[[j]]$net0 348 | # pvalue_all[[j]] <- tmp_list[[j]]$pvalue 349 | # FC_all[j] <- tmp_list[[j]]$FC 350 | # info_all[j] <- tmp_list[[j]]$info 351 | # ligand.abundance_all[1:length(net.rownames),j] <- tmp_list[[j]]$ligand.abundance 352 | # target.abundance_all[1:length(net.rownames),j] <- tmp_list[[j]]$target.abundance} 353 | end.time <- Sys.time();time.taken <- end.time - start.time; 354 | print(time.taken) 355 | #list_return <- list(net_all=net_all,net0_all=net0_all,FC_all=FC_all,pvalue_all=pvalue_all) 356 | #return(list_return) 357 | object@net0 <- net0_all 358 | object@pvalue <- pvalue_all 359 | object@net <- net_all 360 | object@fc <- FC_all 361 | object@info <- info_all 362 | object@ligand.abundance <- ligand.abundance_all 363 | object@target.abundance <- target.abundance_all 364 | return(object) 365 | } 366 | #' Aggregation of communication networks over all ligand-target pairs 367 | #' @param net_list a list containing communication strength matrices for all ligand-target pairs, e.g., 'net' slot of NeuronChat object after run 'run_NeuronChat' 368 | #' @param method one of 'weight','count','weighted_count','weighted_count2' and 'weight_threshold' 369 | #' @param cut_off threshold used for methods 'weighted_count2' and 'weight_threshold' 370 | #' @return 371 | #' @export 372 | #' 373 | #' @examples 374 | net_aggregation <- function(net_list,method=c('weight','count','weighted_count','weighted_count2','weight_threshold'),cut_off=0.05){ 375 | method <- match.arg(method) 376 | if(method=='weighted_count'){ 377 | net_aggregated <- 0*net_list[[1]] 378 | for(jj in 1:length(net_list)){ 379 | net_aggregated <- net_aggregated+sum(net_list[[jj]])*(net_list[[jj]]>0); 380 | }} else if(method=='count'){ 381 | net_aggregated <- 0*net_list[[1]] 382 | for(jj in 1:length(net_list)){ 383 | net_aggregated <- net_aggregated+1*(net_list[[jj]]>0); 384 | } 385 | } else if(method=='weighted_count2'){ 386 | net_aggregated <- 0*net_list[[1]] 387 | for(jj in 1:length(net_list)){ 388 | net_aggregated <- net_aggregated+sum(net_list[[jj]])/(1e-6+sum(net_list[[jj]]>quantile(net_list[[jj]],probs = cut_off)))*(net_list[[jj]]>quantile(net_list[[jj]],probs = cut_off)); 389 | } 390 | }else if(method=='weight_threshold'){ 391 | net_aggregated <- 0*net_list[[1]] 392 | for(jj in 1:length(net_list)){ 393 | net_aggregated <- net_aggregated+net_list[[jj]]*(net_list[[jj]]>quantile(net_list[[jj]],probs = cut_off)); 394 | } 395 | } 396 | else { 397 | net_aggregated <- 0*net_list[[1]] 398 | for(jj in 1:length(net_list)){ 399 | net_aggregated <- net_aggregated+net_list[[jj]]; 400 | } 401 | } 402 | return(net_aggregated) 403 | } 404 | x <- createNeuronChat(t(mat_sc),DB='mouse',group.by = as.character(meta_sc$subclass_label)) # input data should be gene by cell matrix 405 | library(NeuronChat) 406 | load("/Users/weizhao/Documents/NeuronChat-ST/ST_datasets_processed/MERFISH/visual_spatial_MERFISH.rda") # using your own path 407 | set.seed(123) 408 | x <- createNeuronChat(t(mat_sc),DB='mouse',group.by = as.character(meta_sc$subclass_label)) # input data should be gene by cell matrix 409 | find_funs("t") 410 | require("sos") 411 | findFn("computeEstimate") 412 | library(prada) 413 | find_funs("t") 414 | install.packages('prada') 415 | library(prada) 416 | find_funs("t") 417 | ?t 418 | roxygen2::roxygenise() 419 | knitr::opts_chunk$set( 420 | collapse = TRUE, 421 | comment = "#>" 422 | ) 423 | knitr::opts_chunk$set(fig.width=6, fig.height=6,fig.align = "center") 424 | library(NeuronChat) 425 | library(CellChat) 426 | # load example data: cortex data from Yao 2021, processed 427 | data(list='cortex_data') 428 | # subset the data by choosing the region VISp 429 | region_name <- 'VISp'; cell_class <- names(table(meta$class_label)) 430 | cell_idx <- which(meta$region_label %in% region_name & meta$class_label %in% cell_class & !(meta$subclass_label %in%c('Car3','CR','DG','L2/3 IT PPP','L5/6 IT TPE-ENT'))) 431 | target_df_single <- target_df[cell_idx,] # a data frame: row cell, column gene (the last column is the cell subclass) 432 | meta_tmp <- meta[cell_idx,];rownames(meta_tmp) <- meta_tmp$sample_name # subset meta 433 | df_group <- meta_tmp[!duplicated(meta_tmp$subclass_label),c('class_label','subclass_label')] 434 | group <- structure(df_group$class_label,names=df_group$subclass_label) # create the cell class for the subclasses, used for plot 435 | # creat NeuronChat object; choose the database 'mouse' for mouse data; 'human' for human data 436 | # note that the first parameter should be a numeric matrix with row gene and column cell 437 | x <- createNeuronChat(t(as.matrix(target_df_single[,1:(dim(target_df_single)[2]-1)])),DB='mouse',group.by = target_df_single$cell_subclass); 438 | # M is for the permutation test; typically ~4 mins when M=100, depending on the dataset size and the number of cell groups 439 | # setting M=10 to get a quick start 440 | x <- run_NeuronChat(x,M=100) 441 | # the the communication networks for individual interaction pairs are stored in slot 'net' 442 | # aggregate the communication networks over all interaction pairs, method can be 'weight', 'count' and so on 443 | net_aggregated_x <- net_aggregation(x@net,method = 'weight') 444 | par(mfrow=c(1,2)) 445 | # Visualization, circle plot, for the aggregated network 446 | netVisual_circle_neuron(net_aggregated_x,group=group,vertex.label.cex = 1) 447 | # Visualization, chordDiagram, for the aggregated network; also using cellchat function netVisual_chord_cell_internal(net_aggregated_x, group = group,lab.cex=1) 448 | netVisual_chord_neuron(x,method = 'weight',group=group,lab.cex = 1) 449 | # Visualization, heatmap for the aggregated network 450 | heatmap_aggregated(x, method='weight',group=group) 451 | par(mfrow=c(1,2)) 452 | # Visualization for the single interaction pair, circle plot 453 | netVisual_circle_neuron(x@net$Glu_Gria2,group=group,vertex.label.cex = 1) 454 | # Visualization for the single interaction pair, chord diagram 455 | netVisual_chord_neuron(x,interaction_use='Glu_Gria2',group=group,lab.cex = 1) 456 | # Visualization for the single interaction pair, heatmap 457 | heatmap_single(x,interaction_name='Glu_Gria2',group=group) 458 | # Visualization for the single interaction pair, heatmap with violin plots showing expression of genes realted to ligand and target 459 | lig_tar_heatmap(x,interaction_name='Glu_Gria2',width.vector=c(0.38,0.35,0.27)) 460 | g1 <- rankNet_Neuron(x,slot.name = "net",measure = c("weight"),mode='single',font.size = 5) 461 | g2 <- rankNet_Neuron(x,slot.name = "net",measure = c("count"),mode='single',font.size = 5) 462 | g1+g2 463 | # selectK_Neuron(x,pattern = "outgoing") 464 | # selectK_Neuron(x,pattern = "incoming") 465 | x<- identifyCommunicationPatterns_Neuron(x, slot.name = "net", pattern = c("outgoing"), k=4,height = 18) 466 | x<- identifyCommunicationPatterns_Neuron(x, slot.name = "net", pattern = c("incoming"), k=4,height = 18) 467 | library(ggalluvial) 468 | netAnalysis_river_Neuron(x,slot.name = "net", pattern = c("outgoing"),font.size = 2.5,cutoff.1 = 0.5,cutoff.2=0.5) 469 | netAnalysis_river_Neuron(x,slot.name = "net", pattern = c("incoming"),font.size = 2.5,cutoff.1 = 0.5,cutoff.2=0.5) 470 | x <- computeNetSimilarity_Neuron(x,type='functional') 471 | x <- CellChat::netEmbedding(x, slot.name = "net_analysis", type = "functional") 472 | x <- CellChat::netClustering(x, type='functional',slot.name = "net_analysis",k=5) 473 | netVisual_embedding_Neuron(x, type = "functional", label.size = 5,pathway.remove.show = F) 474 | netVisual_embeddingZoomIn_Neuron(x, type = "functional", nCol = 2,label.size = 3) 475 | library(NeuronChat) 476 | ### MERFISH dataset plus scRNA-seq 477 | ```{r fig08, fig.height = 5, fig.width = 10} 478 | ## MERFISH, 2021, https://www.nature.com/articles/s41586-021-03705-x 479 | load("/Users/weizhao/Documents/NeuronChat-ST/ST_datasets_processed/MERFISH/visual_spatial_MERFISH.rda") # using your own path 480 | set.seed(123) 481 | x <- createNeuronChat(t(mat_sc),DB='mouse',group.by = as.character(meta_sc$subclass_label)) # input data should be gene by cell matrix 482 | x <- run_NeuronChat(x,M=100) 483 | net_aggregated_x <- net_aggregation(x@net,method = 'weight') 484 | net <- net_aggregated_x/max(net_aggregated_x) 485 | # only keep top10 links with highest total weight 486 | net_sort <- sort(net,index.return =T,decreasing = T) 487 | net_top10 <-net*0;net_top10[net_sort$ix[1:10]] <-net[net_sort$ix[1:10]] 488 | # save(mat_sc,meta_sc, meta, net, net_top10,file='visual_spatial_MERFISH.rda') 489 | # circle plot of communication network 490 | par(mfrow=c(1,2)) 491 | library(scales);colours <- hue_pal()(dim(net)[1]); 492 | netVisual_circle_neuron(net,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 493 | netVisual_circle_neuron(net_top10,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 494 | par(mfrow=c(1,2)) 495 | library(scales);colours <- hue_pal()(dim(net)[1]); 496 | netVisual_circle_neuron(net,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 497 | netVisual_circle_neuron(net_top10,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 498 | par(mfrow=c(1,2)) 499 | library(scales);colours <- hue_pal()(dim(net)[1]); 500 | netVisual_circle_neuron(net,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 501 | netVisual_circle_neuron(net_top10,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 502 | netVisual_circle_neuron(net,edge.width.max = 10,color.use = colours,vertex.label.cex = 1) 503 | netVisual_circle_neuron(net_top10,edge.width.max = 10,color.use = colours,vertex.label.cex = 1) 504 | par(mfrow=c(1,2)) 505 | library(scales);colours <- hue_pal()(dim(net)[1]); 506 | netVisual_circle_neuron(net,edge.width.max = 10,color.use = colours,vertex.label.cex = 1) 507 | netVisual_circle_neuron(net_top10,edge.width.max = 10,color.use = colours,vertex.label.cex = 1) 508 | spatialMap(meta,celltype_label = 'cell_type',centroid_x = 'sdimx',centroid_y = 'sdimy',pt.size = 1,pt.alpha = 0.8,font.size = 10) + labs(x ="x coordinate", y = "y coordinate",color='Glutamatergic \n subclass') 509 | knit_with_parameters("~/Documents/CellChat/NeuronChat/vignettes/Spatial_analysis.Rmd") 510 | ?cell_proximity_enrichment_score 511 | ?run_NeuronChat 512 | ?ggalluvial 513 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.css linguist-detectable=false 2 | *.java linguist-detectable=false 3 | *.python linguist-detectable=true 4 | *.js linguist-detectable=false 5 | *.html linguist-detectable=false 6 | *.xml linguist-detectable=false 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | inst/doc 2 | .Rproj.user 3 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: NeuronChat 2 | Title: Inference of neural-specific cell-cell communication from single cell transcriptomics 3 | Version: 1.0.0 4 | Authors@R: c(person("Wei", "Zhao", role = c("aut", "cre"), email = "zhaow17@uci.edu")) 5 | Description: an open source R package that infers, visualizes and analyzes the neural-specific cell-cell communication networks from single cell transcriptomics 6 | License: `use_gpl3_license()` 7 | Encoding: UTF-8 8 | LazyData: true 9 | Roxygen: list(markdown = TRUE) 10 | RoxygenNote: 7.1.2 11 | Depends: R (>= 4.0.0),dplyr,igraph,ggplot2 12 | Imports: 13 | CellChat, 14 | circlize, 15 | ComplexHeatmap, 16 | data.table, 17 | ggalluvial, 18 | ggplot2, 19 | NMF, 20 | Seurat, 21 | SeuratObject 22 | Suggests: 23 | knitr, 24 | rmarkdown 25 | VignetteBuilder: knitr 26 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright © 2007 Free Software Foundation, Inc. 5 | 6 | Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | The GNU General Public License is a free, copyleft license for software and other kinds of works. 10 | 11 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 12 | 13 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. 14 | 15 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. 16 | 17 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 18 | 19 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. 20 | 21 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. 22 | 23 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. 24 | 25 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 26 | 27 | The precise terms and conditions for copying, distribution and modification follow. 28 | 29 | TERMS AND CONDITIONS 30 | 0. Definitions. 31 | “This License” refers to version 3 of the GNU General Public License. 32 | 33 | “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 34 | 35 | “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. 36 | 37 | To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. 38 | 39 | A “covered work” means either the unmodified Program or a work based on the Program. 40 | 41 | To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. 42 | 43 | To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. 44 | 45 | An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 46 | 47 | 1. Source Code. 48 | The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. 49 | 50 | A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. 51 | 52 | The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. 53 | 54 | The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. 55 | 56 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 57 | 58 | The Corresponding Source for a work in source code form is that same work. 59 | 60 | 2. Basic Permissions. 61 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. 62 | 63 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. 64 | 65 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 66 | 67 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 68 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. 69 | 70 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 71 | 72 | 4. Conveying Verbatim Copies. 73 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. 74 | 75 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 76 | 77 | 5. Conveying Modified Source Versions. 78 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: 79 | 80 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 81 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. 82 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. 83 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. 84 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 85 | 86 | 6. Conveying Non-Source Forms. 87 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: 88 | 89 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. 90 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. 91 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. 92 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. 93 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. 94 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. 95 | 96 | A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. 97 | 98 | “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. 99 | 100 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). 101 | 102 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. 103 | 104 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 105 | 106 | 7. Additional Terms. 107 | “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. 108 | 109 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. 110 | 111 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: 112 | 113 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 114 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or 115 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or 116 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 117 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 118 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. 119 | All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. 120 | 121 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. 122 | 123 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 124 | 125 | 8. Termination. 126 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). 127 | 128 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. 129 | 130 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. 131 | 132 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 133 | 134 | 9. Acceptance Not Required for Having Copies. 135 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 136 | 137 | 10. Automatic Licensing of Downstream Recipients. 138 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. 139 | 140 | An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. 141 | 142 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 143 | 144 | 11. Patents. 145 | A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. 146 | 147 | A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. 148 | 149 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. 150 | 151 | In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. 152 | 153 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. 154 | 155 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. 156 | 157 | A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. 158 | 159 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 160 | 161 | 12. No Surrender of Others' Freedom. 162 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 163 | 164 | 13. Use with the GNU Affero General Public License. 165 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 166 | 167 | 14. Revised Versions of this License. 168 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 169 | 170 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. 171 | 172 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. 173 | 174 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 175 | 176 | 15. Disclaimer of Warranty. 177 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 178 | 179 | 16. Limitation of Liability. 180 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 181 | 182 | 17. Interpretation of Sections 15 and 16. 183 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 184 | 185 | END OF TERMS AND CONDITIONS 186 | 187 | How to Apply These Terms to Your New Programs 188 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. 189 | 190 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. 191 | 192 | 193 | Copyright (C) 194 | 195 | This program is free software: you can redistribute it and/or modify 196 | it under the terms of the GNU General Public License as published by 197 | the Free Software Foundation, either version 3 of the License, or 198 | (at your option) any later version. 199 | 200 | This program is distributed in the hope that it will be useful, 201 | but WITHOUT ANY WARRANTY; without even the implied warranty of 202 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 203 | GNU General Public License for more details. 204 | 205 | You should have received a copy of the GNU General Public License 206 | along with this program. If not, see . 207 | Also add information on how to contact you by electronic and paper mail. 208 | 209 | If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: 210 | 211 | Copyright (C) 212 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 213 | This is free software, and you are welcome to redistribute it 214 | under certain conditions; type `show c' for details. 215 | The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. 216 | 217 | You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . 218 | 219 | The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . 220 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(barplot_proximity) 4 | export(cal_expr_by_group) 5 | export(cal_prob_mtx_downstream) 6 | export(cell_proximity_enrichment_score) 7 | export(cell_proximity_enrichment_score_multiple) 8 | export(cell_proximity_enrichment_score_single) 9 | export(compareInteractions_Neuron) 10 | export(computeNetSimilarityPairwise_Neuron) 11 | export(computeNetSimilarity_Neuron) 12 | export(createNeuronChat) 13 | export(heatmap_aggregated) 14 | export(heatmap_single) 15 | export(identifyCommunicationPatterns_Neuron) 16 | export(lig_tar_heatmap) 17 | export(mergeNeuronChat) 18 | export(netAnalysis_river_Neuron) 19 | export(netVisual_chord_neuron) 20 | export(netVisual_circle_compare) 21 | export(netVisual_circle_neuron) 22 | export(netVisual_embeddingPairwiseZoomIn_Neuron) 23 | export(netVisual_embeddingPairwise_Neuron) 24 | export(netVisual_embeddingZoomIn_Neuron) 25 | export(netVisual_embedding_Neuron) 26 | export(netVisual_proximity) 27 | export(net_aggregation) 28 | export(neuron_chat_downstream) 29 | export(rankNet_Neuron) 30 | export(run_NeuronChat) 31 | export(selectK_Neuron) 32 | export(spatialDistribution) 33 | export(spatialMap) 34 | export(update_interactionDB) 35 | exportClasses(NeuronChat) 36 | import(CellChat) 37 | import(ComplexHeatmap) 38 | import(NMF) 39 | import(Seurat) 40 | import(SeuratObject) 41 | import(circlize) 42 | import(data.table) 43 | import(ggalluvial) 44 | import(ggplot2) 45 | importClassesFrom(Matrix,dgCMatrix) 46 | importClassesFrom(data.table,data.table) 47 | importFrom(CellChat,netVisual_chord_cell_internal) 48 | importFrom(CellChat,scPalette) 49 | importFrom(ComplexHeatmap,Heatmap) 50 | importFrom(ComplexHeatmap,HeatmapAnnotation) 51 | importFrom(ComplexHeatmap,draw) 52 | importFrom(Matrix,t) 53 | importFrom(NMF,nmf) 54 | importFrom(NMF,nmfEstimateRank) 55 | importFrom(RColorBrewer,brewer.pal) 56 | importFrom(Rcpp,evalCpp) 57 | importFrom(cowplot,draw_label) 58 | importFrom(cowplot,ggdraw) 59 | importFrom(cowplot,plot_grid) 60 | importFrom(ggplot2,geom_text) 61 | importFrom(ggplot2,ggtitle) 62 | importFrom(ggplot2,scale_fill_manual) 63 | importFrom(ggplot2,scale_x_discrete) 64 | importFrom(ggplot2,theme) 65 | importFrom(ggrepel,geom_text_repel) 66 | importFrom(grDevices,colorRampPalette) 67 | importFrom(grDevices,recordPlot) 68 | importFrom(grid,gpar) 69 | importFrom(grid,grid.draw) 70 | importFrom(grid,grid.grabExpr) 71 | importFrom(grid,grid.newpage) 72 | importFrom(grid,popViewport) 73 | importFrom(grid,pushViewport) 74 | importFrom(grid,unit) 75 | importFrom(grid,viewport) 76 | importFrom(igraph,E) 77 | importFrom(igraph,V) 78 | importFrom(igraph,ends) 79 | importFrom(igraph,graph_from_adjacency_matrix) 80 | importFrom(igraph,in_circle) 81 | importFrom(igraph,layout_) 82 | importFrom(methods,as) 83 | importFrom(methods,new) 84 | importFrom(methods,setClass) 85 | importFrom(methods,setClassUnion) 86 | importFrom(methods,slot) 87 | importFrom(reshape2,dcast) 88 | importFrom(reshape2,melt) 89 | importFrom(scales,hue_pal) 90 | importFrom(stats,cutree) 91 | importFrom(stats,dist) 92 | importFrom(stats,hclust) 93 | importFrom(stats,p.adjust) 94 | importFrom(stats,setNames) 95 | -------------------------------------------------------------------------------- /NeuronChat.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | 18 | BuildType: Package 19 | PackageUseDevtools: Yes 20 | PackageInstallArgs: --no-multiarch --with-keep.source 21 | -------------------------------------------------------------------------------- /R/spatial_analysis_visualization.R: -------------------------------------------------------------------------------- 1 | #' Calculation of cell proximity enrichment score for multiple tissue slices 2 | #' 3 | #' Calculation of cell proximity enrichment score & associated p-values for multiple tissue slices 4 | #' 5 | #' @param meta A dataframe containing spatial locations and cell type annotations of cells 6 | #' @param celltype_label variable name (character) in meta, to indicate the cell type annotations of cells 7 | #' @param centroid_x variable name (character) in meta, to indicate the x coordinates of cells 8 | #' @param centroid_y variable name (character) in meta, to indicate the y coordinates of cells 9 | #' @param slice_id variable name (character) in meta, to indicate slice id of cells 10 | #' @param thresh_dist distance threshold (a scalar) used to determine the spatial neighbors of cells 11 | #' @param permutation_number number of permutations (a scalar) used to calculate expected frequency matrices and p-values 12 | #' @importFrom reshape2 melt dcast 13 | #' @importFrom stats p.adjust 14 | #' @return A list contains orginal frequency matrix, permutation frequency matrices, dataframe containing cell proximity enrichment score & pvalue, CPscore matrix, pvalue (adjusted) matrix 15 | #' @export 16 | cell_proximity_enrichment_score_multiple <- function(meta,celltype_label='subclass',centroid_x='centroid_x', centroid_y='centroid_y', slice_id='slice_id', 17 | thresh_dist=400,permutation_number=1000){ 18 | # meta <- ;thresh_dist=400;permutation_number=10;celltype_label='subclass';centroid_x='centroid_x';centroid_y='centroid_y';slice_id='slice_id'; 19 | celltype <- sort(unique(as.character(meta[,celltype_label])),method='radix') 20 | ## calculating for each slice 21 | cellproximity_list <- lapply(unique(meta[,slice_id]),function(x){ 22 | meta_slice <- meta[meta[,slice_id]==x,] 23 | meta_slice <- meta_slice[(meta_slice[,celltype_label] %in% celltype),] 24 | tmp <- cell_proximity_enrichment_score(meta_slice,celltype_label=celltype_label,centroid_x=centroid_x, centroid_y=centroid_x, thresh_dist=400,permutation_number=permutation_number,celltype= celltype) 25 | return(list(freq_mtx_simu_1K=tmp$freq_mtx_simu_1K,freq_mtx_orig=tmp$freq_mtx_orig)) 26 | }) 27 | ## summing over multiple slices 28 | freq_mtx_orig_sum <- 0*cellproximity_list[[1]]$freq_mtx_orig 29 | freq_mtx_simu_1K_sum <- 0*cellproximity_list[[1]]$freq_mtx_simu_1K 30 | for(j in 1:length(cellproximity_list)){ 31 | freq_mtx_orig_sum <- freq_mtx_orig_sum+ cellproximity_list[[j]]$freq_mtx_orig 32 | freq_mtx_simu_1K_sum <- freq_mtx_simu_1K_sum + cellproximity_list[[j]]$freq_mtx_simu_1K 33 | } 34 | ## calculating observed-over-expected ratio & p-value 35 | freq_mtx_binary <- apply(freq_mtx_simu_1K_sum,3,function(x){(x>freq_mtx_orig_sum)*1},simplify = F) 36 | freq_mtx_binary <- simplify2array(freq_mtx_binary) 37 | freq_mtx_expected <- apply(freq_mtx_simu_1K_sum,MARGIN = c(1,2),FUN=mean) 38 | p_value <- apply(freq_mtx_binary,1:2,sum)/permutation_number; p_value_mtx <- p_value; p_value[lower.tri(p_value)] <- 0 39 | p_value_adjusted_mtx <- stats::p.adjust(c(p_value_mtx),method = 'BH'); dim(p_value_adjusted_mtx) <- dim(p_value_mtx) 40 | 41 | CPscore <- (freq_mtx_orig_sum+1)/(freq_mtx_expected+1); log2CPscore_mtx <- log2(CPscore); CPscore[lower.tri(CPscore)] <- 0 42 | 43 | CPscore_long <- reshape2::melt(CPscore,value.name = "CPscore") 44 | p_value_long <- reshape2::melt(p_value,value.name = "pvalue") 45 | CPs_df <- merge(CPscore_long,p_value_long); 46 | CPs_df <- CPs_df[CPs_df$CPscore>0,] 47 | CPs_df$log2CPscore <- log2(CPs_df$CPscore) 48 | CPs_df$group <- ifelse(CPs_df$log2CPscore>0,'enriched','depleted') 49 | CPs_df$p.adjusted <- stats::p.adjust(CPs_df$pvalue,method = 'BH') 50 | CPs_df$sig_0.05 <-''; CPs_df$sig_0.05[CPs_df$p.adjusted <0.05] <- '*' 51 | CPs_df <- CPs_df[order(CPs_df$CPscore,decreasing = T),] 52 | CPs_df$cellpair <- paste(CPs_df$Var1,CPs_df$Var2,sep='--') 53 | 54 | return(list(freq_mtx_simu_1K=freq_mtx_simu_1K_sum,freq_mtx_orig=freq_mtx_orig_sum,CPScore_df=CPs_df,log2CPscore_mtx=log2CPscore_mtx,p_value_adjusted_mtx=p_value_adjusted_mtx)) 55 | } 56 | 57 | #' Calculation of cell proximity enrichment score for single tissue slice 58 | #' 59 | #' Calculation of cell proximity enrichment score & associated p-values for single tissue slice 60 | #' 61 | #' @param meta A dataframe containing spatial locations and cell type annotations of cells 62 | #' @param celltype_label variable name (character) in meta, to indicate the cell type annotations of cells 63 | #' @param centroid_x variable name (character) in meta, to indicate the x coordinates of cells 64 | #' @param centroid_y variable name (character) in meta, to indicate the y coordinates of cells 65 | #' @param thresh_dist distance threshold (a scalar) used to determine the spatial neighbors of cells 66 | #' @param permutation_number number of permutations (a scalar) used to calculate expected frequency matrices and p-values 67 | #' @importFrom reshape2 melt dcast 68 | #' @importFrom stats p.adjust 69 | #' @return A list contains orginal frequency matrix, permutation frequency matrices, dataframe containing cell proximity enrichment score & pvalue, CPscore matrix, pvalue (adjusted) matrix 70 | #' @export 71 | cell_proximity_enrichment_score_single <- function(meta,celltype_label='subclass',centroid_x='centroid_x', centroid_y='centroid_y', 72 | thresh_dist=400,permutation_number=1000){ 73 | celltype <- sort(unique(as.character(meta[,celltype_label])),method='radix') 74 | results <- cell_proximity_enrichment_score(meta,celltype_label=celltype_label,centroid_x=centroid_x, centroid_y=centroid_y, 75 | thresh_dist=400,permutation_number=1000,celltype= celltype) 76 | return(results) 77 | } 78 | 79 | #' Calculation of cell proximity enrichment score 80 | #' 81 | #' Calculation of cell proximity enrichment score & associated p-values (internal function) 82 | #' 83 | #' @param loc_centroid_subset_10K A dataframe containing spatial locations and cell type annotations of cells 84 | #' @param celltype_label variable name (character) in loc_centroid_subset_10K, to indicate the cell type annotations of cells 85 | #' @param centroid_x variable name (character) in loc_centroid_subset_10K, to indicate the x coordinates of cells 86 | #' @param centroid_y variable name (character) in loc_centroid_subset_10K, to indicate the y coordinates of cells 87 | #' @param thresh_dist distance threshold (a scalar) used to determine the spatial neighbors of cells 88 | #' @param permutation_number number of permutations (a scalar) used to calculate expected frequency matrices and p-values 89 | #' @param celltype uniqued cell type names (a vector) 90 | #' @importFrom reshape2 melt dcast 91 | #' @importFrom stats p.adjust 92 | #' @return A list contains orginal frequency matrix, permutation frequency matrices, dataframe containing cell proximity enrichment score & pvalue, CPscore matrix, pvalue (adjusted) matrix 93 | #' @export 94 | cell_proximity_enrichment_score <- function(loc_centroid_subset_10K,celltype_label='subclass',centroid_x='centroid_x', centroid_y='centroid_y', 95 | thresh_dist=400,permutation_number=1000,celltype= celltype){ 96 | # thresh_dist=400;permutation_number=1000;celltype_label='subclass';centroid_x='centroid_x';centroid_y='centroid_y'; 97 | rownames(loc_centroid_subset_10K) <- NULL 98 | n_celltype <- length(celltype) 99 | coord_mtx <- as.matrix(loc_centroid_subset_10K[,c(centroid_x,centroid_y)]) 100 | Euclidean_dist <- dist(coord_mtx, method = "euclidean", diag = FALSE, upper = FALSE, p = 2) 101 | Euclidean_mtx <- as.matrix(Euclidean_dist) 102 | Euclidean_mtx[lower.tri(Euclidean_mtx,diag = T)] <- 0 103 | Euclidean_df <- reshape2::melt(Euclidean_mtx) 104 | Euclidean_df <- Euclidean_df[Euclidean_df$value>0,] 105 | Euclidean_df_filter <- Euclidean_df[Euclidean_df$value <=thresh_dist,] 106 | idx_from <- match(Euclidean_df_filter$Var1,rownames(loc_centroid_subset_10K)) 107 | idx_to <- match(Euclidean_df_filter$Var2,rownames(loc_centroid_subset_10K)) 108 | 109 | # original freq matrix(observed) 110 | freq_mtx_orig <- matrix(0, n_celltype,n_celltype); dimnames(freq_mtx_orig) <- list(celltype,celltype) 111 | Euclidean_df_filter$from <- loc_centroid_subset_10K[,celltype_label][idx_from] 112 | Euclidean_df_filter$to <- loc_centroid_subset_10K[,celltype_label][idx_to] 113 | Euclidean_df_filter_cast <- reshape2::dcast(Euclidean_df_filter,from + to ~ . , fun.aggregate=length,value.var='value'); colnames(Euclidean_df_filter_cast)[3] <- 'freq' 114 | freq_mtx <- reshape2::dcast(Euclidean_df_filter_cast,from~ to,value.var='freq');freq_mtx[is.na(freq_mtx)] <-0 115 | rownames(freq_mtx) <- freq_mtx[,1]; freq_mtx <- freq_mtx[,-1] 116 | freq_mtx_orig[rownames(freq_mtx), colnames(freq_mtx)] <- as.matrix(freq_mtx); 117 | freq_mtx_orig <- freq_mtx_orig + t(freq_mtx_orig)- diag(diag(freq_mtx_orig)) 118 | 119 | ## permutation freq matrix (expected) 120 | sampling_mtx <- sapply(1:permutation_number,FUN=function(x){sample(1:dim(loc_centroid_subset_10K)[1],dim(loc_centroid_subset_10K)[1])},simplify=T) 121 | freq_mtx_simu_1K <- sapply(1:permutation_number,FUN=function(x){ 122 | freq_mtx_simu <- matrix(0, n_celltype,n_celltype); dimnames(freq_mtx_simu) <- list(celltype,celltype) 123 | Euclidean_df_filter$from <- loc_centroid_subset_10K[,celltype_label][sampling_mtx[,x]][idx_from] 124 | Euclidean_df_filter$to <- loc_centroid_subset_10K[,celltype_label][sampling_mtx[,x]][idx_to] 125 | Euclidean_df_filter_cast <- reshape2::dcast(Euclidean_df_filter,from + to ~ . , fun.aggregate=length,value.var='value'); colnames(Euclidean_df_filter_cast)[3] <- 'freq' 126 | freq_mtx <- reshape2::dcast(Euclidean_df_filter_cast,from~ to,value.var='freq') 127 | freq_mtx[is.na(freq_mtx)] <-0 128 | rownames(freq_mtx) <- freq_mtx[,1]; freq_mtx <- freq_mtx[,-1] 129 | freq_mtx_simu[rownames(freq_mtx), colnames(freq_mtx)] <- as.matrix(freq_mtx) 130 | freq_mtx_simu <- freq_mtx_simu + t(freq_mtx_simu)- diag(diag(freq_mtx_simu)) 131 | freq_mtx_simu 132 | },simplify = F) 133 | freq_mtx_simu_1K <- simplify2array(freq_mtx_simu_1K) 134 | 135 | ## calculating observed-over-expected ratio & p-value 136 | freq_mtx_expected <- apply(freq_mtx_simu_1K,MARGIN = c(1,2),FUN=mean) 137 | CPscore <- (freq_mtx_orig+1)/(freq_mtx_expected+1); log2CPscore_mtx <- log2(CPscore); CPscore[lower.tri(CPscore)] <- 0 138 | 139 | freq_mtx_binary <- apply(freq_mtx_simu_1K,3,function(x){(x>freq_mtx_orig)*1},simplify = F) 140 | freq_mtx_binary <- simplify2array(freq_mtx_binary) 141 | p_value <- apply(freq_mtx_binary,1:2,sum)/permutation_number; p_value[lower.tri(p_value)] <- 0 142 | 143 | CPscore_long <- reshape2::melt(CPscore,value.name = "CPscore") 144 | p_value_long <- reshape2::melt(p_value,value.name = "pvalue") 145 | CPs_df <- merge(CPscore_long,p_value_long); 146 | CPs_df <- CPs_df[CPs_df$CPscore>0,] 147 | CPs_df$log2CPscore <- log2(CPs_df$CPscore) 148 | CPs_df$group <- ifelse(CPs_df$log2CPscore>0,'enriched','depleted') 149 | CPs_df$p.adjusted <- stats::p.adjust(CPs_df$pvalue,method = 'BH') 150 | CPs_df$sig_0.05 <-''; CPs_df$sig_0.05[CPs_df$p.adjusted <0.05] <- '*' 151 | CPs_df <- CPs_df[order(CPs_df$CPscore,decreasing = T),] 152 | CPs_df$cellpair <- paste(CPs_df$Var1,CPs_df$Var2,sep='--') 153 | 154 | p_value_adjusted_mtx_tmp <- reshape2::dcast(CPs_df[,c('Var1','Var2','p.adjusted')],Var1~Var2,value.var='p.adjusted') 155 | rownames(p_value_adjusted_mtx_tmp) <- p_value_adjusted_mtx_tmp[,1];p_value_adjusted_mtx_tmp <- p_value_adjusted_mtx_tmp[,-1] 156 | p_value_adjusted_mtx_tmp[is.na(p_value_adjusted_mtx_tmp)] <- 0; #CP_net <- ifelse(CP_net>0,1,0) 157 | p_value_adjusted_mtx_tmp <- as.matrix(p_value_adjusted_mtx_tmp) 158 | p_value_adjusted_mtx_tmp <- p_value_adjusted_mtx_tmp + t(p_value_adjusted_mtx_tmp) - diag(diag(p_value_adjusted_mtx_tmp)) 159 | p_value_adjusted_mtx <- log2CPscore_mtx; p_value_adjusted_mtx[rownames(p_value_adjusted_mtx_tmp),colnames(p_value_adjusted_mtx_tmp)] <- p_value_adjusted_mtx_tmp 160 | ## return value 161 | return(list(freq_mtx_simu_1K=freq_mtx_simu_1K,freq_mtx_orig=freq_mtx_orig,CPScore_df=CPs_df,log2CPscore_mtx=log2CPscore_mtx,p_value_adjusted_mtx=p_value_adjusted_mtx)) 162 | } 163 | 164 | #' bar plot of spatial proximity for pairwise cell types 165 | #' 166 | #' bar plot of spatial proximity for pairwise cell types 167 | #' @param cell_proximity_df a dataframe stored in the output list from function "cell_proximity_enrichment_score_single" or "cell_proximity_enrichment_score_multiple", e.g., cell_proximity$CPScore_df 168 | #' @param font.size font.size for ggplot 169 | #' @import ggplot2 170 | #' @importFrom scales hue_pal 171 | #' @return a ggplot object 172 | #' @export 173 | barplot_proximity <- function(cell_proximity_df,font.size=20){ 174 | CPs_df <- cell_proximity_df 175 | p4 <- ggplot() + theme_bw() + geom_bar(data=CPs_df[order(CPs_df$log2CPscore,decreasing = T),], aes(x = reorder(cellpair, log2CPscore) , y = log2CPscore, fill = group), stat = 'identity', show.legend = F) + 176 | labs(y ="cell proximity enrichment score", x = "interacting cell pair") + coord_flip() + scale_fill_manual(values=rev(scales::hue_pal()(2))) + 177 | theme(text=element_text(size=font.size), #change font size of all text 178 | axis.text=element_text(size=font.size,color = 'black'), #change font size of axis text 179 | axis.title=element_text(size=font.size), #change font size of axis titles 180 | legend.text=element_text(size=font.size), #change font size of legend text 181 | legend.title=element_text(size=font.size)) #change font size of legend title 182 | return(p4) 183 | } 184 | 185 | #' Circle plot of cell-cell proximity network 186 | #' 187 | #' Circle plot of cell-cell proximity network (adapted from CellChat https://github.com/sqjin/CellChat) 188 | #' 189 | #' The width of edges represent the absolute value of cell proximity enrichment score; 190 | #' red line means enriched cell proximity while grey line means depleted cell proximity 191 | #' 192 | #' @param net_ori A weighted matrix representing the connections 193 | #' @param group a vector indicating which cell types (cell subclass, e.g., L2/3 IT) belong to which big groups (cell class, e.g., Glutamatergic) 194 | #' @param color.use Colors represent different cell groups 195 | #' @param title.name the name of the title 196 | #' @param sources.use a vector giving the index or the name of source cell groups 197 | #' @param targets.use a vector giving the index or the name of target cell groups. 198 | #' @param idents.use a vector giving the index or the name of cell groups of interest. 199 | #' @param remove.isolate whether remove the isolate nodes in the communication network 200 | #' @param top the fraction of interactions to show 201 | #' @param weight.scale whether scale the weight 202 | #' @param vertex.weight The weight of vertex: either a scale value or a vector 203 | #' @param vertex.weight.max the maximum weight of vertex; defualt = max(vertex.weight) 204 | #' @param vertex.size.max the maximum vertex size for visualization 205 | #' @param vertex.label.cex The label size of vertex 206 | #' @param vertex.label.color The color of label for vertex 207 | #' @param edge.weight.max the maximum weight of edge; defualt = max(net) 208 | #' @param edge.width.max The maximum edge width for visualization 209 | #' @param label.edge Whether or not shows the label of edges 210 | #' @param alpha.edge the transprency of edge 211 | #' @param edge.label.color The color for single arrow 212 | #' @param edge.label.cex The size of label for arrows 213 | #' @param edge.curved Specifies whether to draw curved edges, or not. 214 | #' This can be a logical or a numeric vector or scalar. 215 | #' First the vector is replicated to have the same length as the number of 216 | #' edges in the graph. Then it is interpreted for each edge separately. 217 | #' A numeric value specifies the curvature of the edge; zero curvature means 218 | #' straight edges, negative values means the edge bends clockwise, positive 219 | #' values the opposite. TRUE means curvature 0.5, FALSE means curvature zero 220 | #' @param shape The shape of the vertex, currently “circle”, “square”, 221 | #' “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see 222 | #' vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the 223 | #' plot.igraph command. “none” does not draw the vertices at all, although 224 | #' vertex label are plotted (if given). See shapes for details about vertex 225 | #' shapes and vertex.shape.pie for using pie charts as vertices. 226 | #' @param layout The layout specification. It must be a call to a layout 227 | #' specification function. 228 | #' @param margin The amount of empty space below, over, at the left and right 229 | #' of the plot, it is a numeric vector of length four. Usually values between 230 | #' 0 and 0.5 are meaningful, but negative values are also possible, that will 231 | #' make the plot zoom in to a part of the graph. If it is shorter than four 232 | #' then it is recycled. 233 | #' @param arrow.width The width of arrows 234 | #' @param arrow.size the size of arrow 235 | # #' @param from,to,bidirection Deprecated. Use `sources.use`,`targets.use` 236 | #' @param vertex.size Deprecated. Use `vertex.weight` 237 | #' @importFrom igraph graph_from_adjacency_matrix ends E V layout_ in_circle 238 | #' @importFrom grDevices recordPlot 239 | #' @import CellChat 240 | #' @return an object of class "recordedplot" 241 | #' @export 242 | netVisual_proximity <-function(net_ori, color.use = NULL,group=NULL,title.name = NULL, sources.use = NULL, targets.use = NULL, remove.isolate = FALSE, top = 1, 243 | weight.scale = TRUE, vertex.weight = 1, vertex.weight.max = NULL, vertex.size.max = 10, vertex.label.cex=1.5,vertex.label.color= "black", 244 | edge.weight.max = NULL, edge.width.max=10, alpha.edge = 0.6, label.edge = FALSE,edge.label.color='black',edge.label.cex=0.8, 245 | edge.curved=0,shape=NULL,layout=in_circle(), margin=0.2, vertex.size = NULL, 246 | arrow.width=0,arrow.size = 0){ 247 | # color.use = NULL;title.name = NULL; sources.use = NULL; targets.use = NULL; remove.isolate = FALSE; top = 1; 248 | # weight.scale = TRUE; vertex.weight = 1; vertex.weight.max = NULL; vertex.size.max = 10; vertex.label.cex=1.5;vertex.label.color= "black"; 249 | # edge.weight.max = NULL; edge.width.max=10; alpha.edge = 0.6; label.edge = FALSE;edge.label.color='black';edge.label.cex=1.2; 250 | # edge.curved=0;shape='circle';layout=in_circle(); margin=0.2; vertex.size = NULL;arrow.width=0;arrow.size = 0 251 | # arrow.width=1;arrow.size = 0.2 252 | net_ori[lower.tri(net_ori)] <- 0 253 | net.names <- unique(c(rownames(net_ori),colnames(net_ori))) 254 | net <- matrix(0,nrow=length(net.names),ncol=length(net.names)) 255 | dimnames(net) <- list(net.names,net.names) 256 | net[rownames(net_ori),colnames(net_ori)] <- net_ori 257 | if (!is.null(vertex.size)) { 258 | warning("'vertex.size' is deprecated. Use `vertex.weight`") 259 | } 260 | if (is.null(vertex.size.max)) { 261 | if (length(unique(vertex.weight)) == 1) { 262 | vertex.size.max <- 5 263 | } else { 264 | vertex.size.max <- 15 265 | } 266 | } 267 | options(warn = -1) 268 | thresh <- stats::quantile(net, probs = 1-top) 269 | net[net < thresh] <- 0 270 | 271 | if ((!is.null(sources.use)) | (!is.null(targets.use))) { 272 | if (is.null(rownames(net))) { 273 | stop("The input weighted matrix should have rownames!") 274 | } 275 | cells.level <- rownames(net) 276 | df.net <- reshape2::melt(net, value.name = "value") 277 | colnames(df.net)[1:2] <- c("source","target") 278 | # keep the interactions associated with sources and targets of interest 279 | if (!is.null(sources.use)){ 280 | if (is.numeric(sources.use)) { 281 | sources.use <- cells.level[sources.use] 282 | } 283 | df.net <- subset(df.net, source %in% sources.use) 284 | } 285 | if (!is.null(targets.use)){ 286 | if (is.numeric(targets.use)) { 287 | targets.use <- cells.level[targets.use] 288 | } 289 | df.net <- subset(df.net, target %in% targets.use) 290 | } 291 | df.net$source <- factor(df.net$source, levels = cells.level) 292 | df.net$target <- factor(df.net$target, levels = cells.level) 293 | df.net$value[is.na(df.net$value)] <- 0 294 | net <- tapply(df.net[["value"]], list(df.net[["source"]], df.net[["target"]]), sum) 295 | } 296 | net[is.na(net)] <- 0 297 | 298 | 299 | if (remove.isolate) { 300 | idx1 <- which(Matrix::rowSums(net) == 0) 301 | idx2 <- which(Matrix::colSums(net) == 0) 302 | idx <- intersect(idx1, idx2) 303 | net <- net[-idx, ] 304 | net <- net[, -idx] 305 | } 306 | g1 <- graph_from_adjacency_matrix(net, mode = "directed", weighted = T) 307 | if (is.null(group)) { 308 | g <-igraph::permute(g1,match(V(g1)$name,net.names)) 309 | group <- structure(rep(1,length(V(g))),names=names(V(g))) 310 | group <- group[names(V(g))] 311 | } else { 312 | g <-igraph::permute(g1,match(V(g1)$name,names(group)[order(group, names(group))])) 313 | } 314 | edge.start <- igraph::ends(g, es=igraph::E(g), names=FALSE) 315 | coords<-layout_(g,layout) 316 | if(nrow(coords)!=1){ 317 | coords_scale=scale(coords) 318 | }else{ 319 | coords_scale<-coords 320 | } 321 | if (is.null(color.use)) { 322 | color.use = CellChat::scPalette(length(igraph::V(g))) 323 | } 324 | if (is.null(vertex.weight.max)) { 325 | vertex.weight.max <- max(vertex.weight) 326 | } 327 | vertex.weight <- vertex.weight/vertex.weight.max*vertex.size.max+5 328 | # color.use.label <- c('red','black') 329 | color.use.label <- c('black',CellChat::scPalette(length(unique(group))))[1:length(unique(group))] 330 | color.use.label <- structure(color.use.label,names=unique(group)) 331 | # color.use.label <- color.use.label[-length(color.use.label)] 332 | # if(length(color.use.label)==1){ color.use.label='black'} 333 | 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])) 334 | if(length(vertex.weight)==1){ igraph::V(g)$size<-vertex.weight} else {igraph::V(g)$size<-vertex.weight[names(V(g))]} 335 | igraph::V(g)$color<-color.use[igraph::V(g)] 336 | igraph::V(g)$shape <- c('circle')#, 'square', 'csquare', 'rectangle', 'crectangle', 'vrectangle', 'pie', 'raster','sphere')[group[igraph::V(g)]] 337 | igraph::V(g)$frame.color <- color.use[igraph::V(g)] 338 | #igraph::V(g)$frame.color <- border.color.use[igraph::V(g)] 339 | igraph::V(g)$label.color <-color.use.label[group[names(V(g))]]#unlist(lapply(V(g), FUN= function(x){color.use.label[group[x]]})) 340 | igraph::V(g)$label.cex<-vertex.label.cex 341 | if(label.edge){ 342 | igraph::E(g)$label<-igraph::E(g)$weight 343 | igraph::E(g)$label <- round(igraph::E(g)$label, digits = 1) 344 | } 345 | if (is.null(edge.weight.max)) { 346 | edge.weight.max <- max(igraph::E(g)$weight) 347 | } 348 | if (weight.scale == TRUE) { 349 | E(g)$width<-0.3+edge.width.max/(max(E(g)$weight)-min(E(g)$weight))*(E(g)$weight-min(E(g)$weight)) 350 | # igraph::E(g)$width<- 0.3+abs(igraph::E(g)$weight)/edge.weight.max*edge.width.max 351 | }else{ 352 | igraph::E(g)$width<-0.3+edge.width.max*(E(g)$weight-min(E(g)$weight)) 353 | } 354 | 355 | igraph::E(g)$arrow.width<-arrow.width 356 | igraph::E(g)$arrow.size<-arrow.size 357 | igraph::E(g)$label.color<-edge.label.color 358 | igraph::E(g)$label.cex<-edge.label.cex 359 | igraph::E(g)$color <- ifelse(igraph::E(g)$weight>0, 'red','grey'); 360 | igraph::E(g)$color <- grDevices::adjustcolor(igraph::E(g)$color,alpha.edge) 361 | igraph::E(g)$lty <- ifelse(igraph::E(g)$weight>0, 1,1) 362 | 363 | if(sum(edge.start[,2]==edge.start[,1])!=0){ 364 | igraph::E(g)$loop.angle[which(edge.start[,2]==edge.start[,1])]<-loop.angle[edge.start[which(edge.start[,2]==edge.start[,1]),1]] 365 | } 366 | radian.rescale <- function(x, start=0, direction=1) { 367 | c.rotate <- function(x) (x + start) %% (2 * pi) * direction 368 | c.rotate(scales::rescale(x, c(0, 2 * pi), range(x))) 369 | } 370 | label.locs <- radian.rescale(x=1:length(igraph::V(g)), direction=-1, start=0) 371 | label.dist <- vertex.weight/max(vertex.weight)+4 372 | plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin, vertex.label.dist=label.dist, 373 | vertex.label.degree=label.locs, vertex.label.family="Helvetica", edge.label.family="Helvetica") # "sans" 374 | # plot(g,edge.curved=edge.curved,layout=coords_scale,margin=margin, vertex.label.dist=label.dist, 375 | # vertex.label.degree=label.locs, vertex.label.family="Helvetica", edge.label.family="Helvetica",vertex.label="") # "sans" 376 | # ## https://gist.github.com/ajhmohr/5337a5c99b504e4a243fad96203fa74f 377 | # text.pos <- coords*(1.15+strwidth(names(V(g)),font=12)/2) 378 | # angle = ifelse(atan(-(coords[,1]/coords[,2]))*(180/pi) < 0, 90 + atan(-(coords[,1]/coords[,2]))*(180/pi), 270 + atan(-coords[,1]/coords[,2])*(180/pi)) 379 | # for (i in 1:length(V(g))) { 380 | # text(x=text.pos[i,1], y=text.pos[i,2], labels=V(g)$name[i], adj=NULL, pos=NULL, cex=1.2, col=igraph::V(g)$label.color[i], srt=angle[i], xpd=T) 381 | # } 382 | 383 | if (!is.null(title.name)) { 384 | text(0,1.6,title.name, cex = 1.5) 385 | } 386 | gg <- recordPlot() 387 | return(gg) 388 | } 389 | 390 | #' Spatial plot of cells with their annotations 391 | #' 392 | #' Spatial plot of cells with their annotations 393 | #' 394 | #' @param meta A dataframe containing spatial locations and cell type annotations of cells 395 | #' @param celltype_label variable name (character) in meta, to indicate the cell type annotations of cells 396 | #' @param centroid_x variable name (character) in meta, to indicate the x coordinates of cells 397 | #' @param centroid_y variable name (character) in meta, to indicate the y coordinates of cells 398 | #' @import ggplot2 399 | #' @importFrom scales hue_pal 400 | #' @return a ggplot object 401 | #' @export 402 | spatialMap <- function(meta,celltype_label='subclass',centroid_x='centroid_x', centroid_y='centroid_y', pt.size=5,pt.alpha=0.8,font.size=20,legend.symbol.size=5){ 403 | attr_x <- celltype_label 404 | p2 <- ggplot2::ggplot() + theme_bw() 405 | p2 <- p2+ ggplot2::geom_point(data = meta[order(meta[,attr_x],decreasing = F),], aes_string(x = centroid_x, y = centroid_y,colour = attr_x), 406 | show.legend = T, size = pt.size, alpha =pt.alpha) + scale_color_manual(values=colours) + 407 | labs(x ="x coordinates", y = "y coordinates",color=attr_x) + guides(color = guide_legend(override.aes = list(size=legend.symbol.size))) + 408 | theme(text=element_text(size=font.size), #change font size of all text 409 | axis.text=element_text(size=font.size), #change font size of axis text 410 | axis.title=element_text(size=font.size), #change font size of axis titles 411 | plot.title=element_text(size=font.size,hjust = 0.5), #change font size of plot title 412 | legend.text=element_text(size=font.size), #change font size of legend text 413 | legend.title=element_text(size=font.size)) #change font size of legend title 414 | return(p2) 415 | } 416 | 417 | #' Spatial distribution of cell types along sptial axis 418 | #' 419 | #' Spatial distribution of cell types along sptial axis 420 | #' 421 | #' @param meta A dataframe containing spatial locations and cell type annotations of cells 422 | #' @param celltype_label variable name (character) in meta, to indicate the cell type annotations of cells 423 | #' @param centroid variable name (character) in meta, to indicate the x or y coordinates of cells 424 | #' @import ggplot2 425 | #' @importFrom scales hue_pal 426 | #' @return a ggplot object 427 | #' @export 428 | spatialDistribution <- function(meta,celltype_label='subclass',centroid='centroid_y', curve.alpha=0.5,font.size=20,legend.symbol.size=5){ 429 | attr_x <- celltype_label 430 | p3 <- ggplot(data=meta[order(meta[,attr_x],decreasing = T),], aes_string(x=centroid, group=attr_x, fill=attr_x)) + 431 | geom_density(adjust=1.5, alpha=curve.alpha) + scale_fill_manual(values=colours) + 432 | labs(y ="density", x = "y coordinate",fill=attr_x) + guides(color = guide_legend(override.aes = list(size=legend.symbol.size))) + coord_flip() + 433 | theme(text=element_text(size=font.size), #change font size of all text 434 | axis.text=element_text(size=font.size,color = 'black'), #change font size of axis text 435 | axis.title=element_text(size=font.size), #change font size of axis titles 436 | legend.text=element_text(size=font.size), #change font size of legend text 437 | legend.title=element_text(size=font.size)) #change font size of legend title 438 | return(p3) 439 | } 440 | -------------------------------------------------------------------------------- /R/update_NeuronChatDB.R: -------------------------------------------------------------------------------- 1 | #' Update NeuronChatDB using user defined new entry information 2 | #' 3 | #' Update NeuronChatDB using user defined new entry information 4 | #' 5 | #' @param DB current interation database (stored in slot 'DB' of NeuronChat object, i.e., object@DB) 6 | #' @param interaction_name a character to denote the name of the interaction to be added 7 | #' @param lig_contributor a vector of gene symbols, contributing to ligand abundance 8 | #' @param receptor_subunit a vector of gene symbols, contributing to receptor abundance 9 | #' @param interaction_type a character to denote the interaction type 10 | #' @param ligand_type a character to denote the ligand_type 11 | #' @param lig_contributor_group a vector of integers to indicate the biological function group of genes in `lig_contributor`; 12 | #' the length of `lig_contributor_group` is the same as `lig_contributor` 13 | #' @param lig_contributor_coeff a numerical vector to indicate the stoichiometric coefficients of ligand-contribuing groups, to calculate ligand abundance; 14 | #' the length is the same as the unique of `lig_contributor_group` 15 | #' @param receptor_subunit_group a vector of integers to indicate the biological function group of genes in `receptor_subunit`; 16 | #' the length of `receptor_subunit_group` is the same as `receptor_subunit` 17 | #' @param receptor_subunit_coeff a numerical vector to indicate the stoichiometric coefficients of receptor subunit groups, to calculate receptor abundance; 18 | #' the length is the same as the unique of `receptor_subunit_group` 19 | #' @return a updated interaction database (a list) 20 | #' @export 21 | update_interactionDB <- function(DB,interaction_name,lig_contributor,receptor_subunit,interaction_type='user_defined',ligand_type='user_defined', 22 | lig_contributor_group=NULL,lig_contributor_coeff=NULL,receptor_subunit_group=NULL,receptor_subunit_coeff=NULL){ 23 | DB_new <-DB 24 | ll <- length(DB_new) 25 | if(interaction_name %in% names(DB)){ 26 | stop("The input `interaction_name` already exists in the current DB") 27 | } else { 28 | interaction_name <- interaction_name 29 | lig_contributor <- lig_contributor 30 | receptor_subunit <- receptor_subunit 31 | if(is.null(lig_contributor_group)){ 32 | lig_contributor_group <- rep(1,length(lig_contributor)) 33 | lig_contributor_coeff <- 1 34 | } 35 | if(is.null(receptor_subunit_group)){ 36 | receptor_subunit_group <- rep(1,length(receptor_subunit)) 37 | receptor_subunit_coeff <- 1 38 | } 39 | if(length(lig_contributor_group)!=length(lig_contributor) | length(receptor_subunit_group)!=length(receptor_subunit)){ 40 | stop("The input `lig_contributor_group` (or `receptor_subunit_group`) doesn't match the length of `lig_contributor` (or `receptor_subunit`)") 41 | } 42 | if(length(lig_contributor_coeff)!=length(unique(lig_contributor_group)) | length(receptor_subunit_coeff)!=length(unique(receptor_subunit_group))){ 43 | stop("The input `lig_contributor_coeff` (or `receptor_subunit_coeff`) doesn't match the length of `unique(lig_contributor_group)` (or `unique(receptor_subunit_group)`") 44 | } 45 | interaction_tmp <- list(interaction_name=interaction_name,lig_contributor=lig_contributor,receptor_subunit=receptor_subunit, 46 | lig_contributor_group=lig_contributor_group,lig_contributor_coeff=lig_contributor_coeff, 47 | receptor_subunit_group=receptor_subunit_group,receptor_subunit_coeff=receptor_subunit_coeff, 48 | targets_up=character(0), targets_down=character(0), activator=character(0),inhibitor=character(0), interactors=character(0), 49 | interaction_type=interaction_type,ligand_type=ligand_type) 50 | } 51 | DB_new[[ll+1]] <- interaction_tmp 52 | names(DB_new)[ll+1] <- interaction_name 53 | return(DB_new) 54 | } 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # NeuronChat 3 | 4 | 5 | 6 | 7 | The goal of NeuronChat is to infer, visualize and analyze neural-specific cell-cell communication from single cell transcriptomics or spatially resolved transcriptomics data. 8 | 9 | ## Installation 10 | 11 | You can install the latest version of NeuronChat like so: 12 | 13 | ``` r 14 | devtools::install_github("Wei-BioMath/NeuronChat") 15 | ``` 16 | The time required for installation depends on pre-installed dependencies and the typical time is within 10 mins. Dependencies of NeuronChat package can be automatically installed when installing NeuronChat pacakge (When encountering any issues, please see the `Troubleshooting` section below). 17 | 18 | ## Usage & Tutorial 19 | ### Basic usage of NeuronChat 20 | ``` r 21 | library(NeuronChat) 22 | # creat NeuronChat object 23 | x <- createNeuronChat(normalized_count_mtx,DB='mouse',group.by = cell_group_vector) # use DB='human' for human data 24 | # calculation of communication networks 25 | x <- run_NeuronChat(x,M=100) 26 | # aggregating networks over interaction pairs 27 | net_aggregated_x <- net_aggregation(x@net,method = 'weight') 28 | # visualization 29 | netVisual_circle_neuron(net_aggregated_x) 30 | ``` 31 | ### Full tutorials 32 | A set of tutorials of NeuronChat are as follows: 33 | 34 | - [Inference, visualization and analysis of neural-specific communication network](https://htmlpreview.github.io/?https://github.com/Wei-BioMath/NeuronChat/blob/main/vignettes/NeuronChat-Tutorial.html) 35 | - [Comparative analysis of multiple datasets](https://htmlpreview.github.io/?https://github.com/Wei-BioMath/NeuronChat/blob/main/vignettes/comparison.html) 36 | - [Analysis of spatial datasets & calculation of spatially constrained communication network](https://htmlpreview.github.io/?https://github.com/Wei-BioMath/NeuronChat/blob/main/vignettes/Spatial_analysis.html) 37 | - [Update the NeuronChat interaction database](https://htmlpreview.github.io/?https://github.com/Wei-BioMath/NeuronChat/blob/main/vignettes/Update_NeuronChat_database.html) 38 | 39 | These tutorials can also be found in the [vignettes directory of the repo](https://github.com/Wei-BioMath/NeuronChat/tree/main/vignettes) 40 | 41 | See also the [repository](https://github.com/Wei-BioMath/NeuronChatAnalysis2022) for more details about repoducing the figures and results in the related study [(Zhao et al., _Nat_ _Commun._, 2023)](https://doi.org/10.1038/s41467-023-36800-w) 42 | 43 | ### How to cite? 44 | Zhao, W., Johnston, K.G., Ren, H. et al. Inferring neuron-neuron communications from single-cell transcriptomics through NeuronChat. _Nat Commun_ 14, 1128 (2023). [https://doi.org/10.1038/s41467-023-36800-w](https://doi.org/10.1038/s41467-023-36800-w) 45 | 46 | ## System Requirements 47 | 48 | ### Hardware requirements 49 | 50 | NeuronChat requires a standard computer and enough memory is recommended to handle large single-cell transcriptomic datasets. 51 | 52 | ### Software requirements 53 | 54 | #### ** Operating System Requirements 55 | 56 | The package has been tested on the following systems: 57 | 58 | ``` r 59 | macOS Big Sur, Version 11.5.1 60 | Windows 10 Pro, version 1909 61 | ``` 62 | 63 | #### ** R Dependencies (tested and recommended) 64 | 65 | ``` r 66 | R >= 4.1.0 67 | dplyr >= 1.0.9 68 | data.table >= 1.14.2 69 | CellChat >= 1.1.3 70 | Seurat >= 4.1.0 71 | SeuratObject >= 4.1.0 72 | NMF >= 0.23.0 73 | igraph >= 1.3.4 74 | ggplot2 >= 3.3.6 75 | ComplexHeatmap >= 2.8.0 76 | circlize >= 0.4.14 77 | ggalluvial >= 0.12.3 78 | ``` 79 | 80 | ## Troubleshooting 81 | Here are some instructions in case users might encounter issues during installation: 82 | 83 | - Install [CellChat](https://github.com/sqjin/CellChat) using `devtools::install_github("sqjin/CellChat")`. See also the `Installation of other dependencies 84 | ` in the [README](https://github.com/sqjin/CellChat) of CellChat for any other issues (including `NMF` package installation). 85 | - Install [ComplexHeatmap](https://github.com/jokergoo/ComplexHeatmap) using `devtools::install_github("jokergoo/ComplexHeatmap")`. 86 | - Install [circlize](https://github.com/jokergoo/circlize) using `devtools::install_github("jokergoo/circlize")`. 87 | - Please see the instructions for installation of `Seurat` or `SeuratObject` via the link [Seurat](https://satijalab.org/seurat/articles/install.html) or [SeuratObject](https://github.com/mojaveazure/seurat-object). 88 | 89 | 90 | -------------------------------------------------------------------------------- /data/cortex_data.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wei-BioMath/NeuronChat/36e06b29397558ba2433bd5deccacd7f2071170e/data/cortex_data.rda -------------------------------------------------------------------------------- /data/df_interactionDB_human.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wei-BioMath/NeuronChat/36e06b29397558ba2433bd5deccacd7f2071170e/data/df_interactionDB_human.rda -------------------------------------------------------------------------------- /data/df_interactionDB_mouse.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wei-BioMath/NeuronChat/36e06b29397558ba2433bd5deccacd7f2071170e/data/df_interactionDB_mouse.rda -------------------------------------------------------------------------------- /data/interactionDB_human.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wei-BioMath/NeuronChat/36e06b29397558ba2433bd5deccacd7f2071170e/data/interactionDB_human.rda -------------------------------------------------------------------------------- /data/interactionDB_mouse.rda: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Wei-BioMath/NeuronChat/36e06b29397558ba2433bd5deccacd7f2071170e/data/interactionDB_mouse.rda -------------------------------------------------------------------------------- /man/AnyMatrix-class.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/NeuronChat_source_file.R 3 | \docType{class} 4 | \name{AnyMatrix-class} 5 | \alias{AnyMatrix-class} 6 | \title{The NeuronChat ClassClass definitions} 7 | \description{ 8 | The NeuronChat ClassClass definitions 9 | } 10 | -------------------------------------------------------------------------------- /man/NeuronChat-class.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/NeuronChat_source_file.R 3 | \docType{class} 4 | \name{NeuronChat-class} 5 | \alias{NeuronChat-class} 6 | \alias{NeuronChat} 7 | \title{The key slots used in the NeuronChat object are described below; adapted from CellChat https://github.com/sqjin/CellChat} 8 | \description{ 9 | The key slots used in the NeuronChat object are described below; adapted from CellChat https://github.com/sqjin/CellChat 10 | } 11 | \section{Slots}{ 12 | 13 | \describe{ 14 | \item{\code{data.raw}}{raw count data matrix} 15 | 16 | \item{\code{data}}{normalized data matrix for CellChat analysis (Genes should be in rows and cells in columns)} 17 | 18 | \item{\code{data.signaling}}{a data.frame only containing signaling genes as well as cell group labels} 19 | 20 | \item{\code{net0}}{a list contianing the original communication strength matrix without filtered by p-value} 21 | 22 | \item{\code{pvalue}}{a list containing the p-value (calculated by permutation test) matrices corresponding to net0} 23 | 24 | \item{\code{net}}{a list of length K contianing the communication strength matrices (N1 X N2) filtered by p-value, where N1 is the number of sending cell groups, N2 is the number of receiving cell groups, and K is the number of ligand-target pairs. Each row of the communication strength matrix indicates the communication probability originating from the sender cell group to other cell groups} 25 | 26 | \item{\code{net_analysis}}{a list containing various network analysis results} 27 | 28 | \item{\code{DB}}{ligand-target interaction database used in the analysis} 29 | 30 | \item{\code{LR}}{a list of information related with ligand-target pairs} 31 | 32 | \item{\code{meta}}{data frame storing the information associated with each cell} 33 | 34 | \item{\code{idents}}{a factor defining the cell identity used for all analysis. It becomes a list for a merged NeuronChat object} 35 | 36 | \item{\code{dr}}{List of the reduced 2D coordinates, one per method, e.g., umap/tsne/dm} 37 | 38 | \item{\code{options}}{List of miscellaneous data, such as parameters used throughout analysis, and a indicator whether the NeuronChat object is a single or merged} 39 | 40 | \item{\code{fc}}{deprecated} 41 | 42 | \item{\code{info}}{information flow of each ligand-target pair} 43 | 44 | \item{\code{ligand.abundance}}{ligand.abundance of sending cell groups (row) for ligand-target pairs (column)} 45 | 46 | \item{\code{target.abundance}}{target.abundance of receiving cell groups (row) for ligand-target pairs (column)} 47 | }} 48 | 49 | -------------------------------------------------------------------------------- /man/barplot_proximity.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/spatial_analysis_visualization.R 3 | \name{barplot_proximity} 4 | \alias{barplot_proximity} 5 | \title{bar plot of spatial proximity for pairwise cell types} 6 | \usage{ 7 | barplot_proximity(cell_proximity_df, font.size = 20) 8 | } 9 | \arguments{ 10 | \item{cell_proximity_df}{a dataframe stored in the output list from function "cell_proximity_enrichment_score_single" or "cell_proximity_enrichment_score_multiple", e.g., cell_proximity$CPScore_df} 11 | 12 | \item{font.size}{font.size for ggplot} 13 | } 14 | \value{ 15 | a ggplot object 16 | } 17 | \description{ 18 | bar plot of spatial proximity for pairwise cell types 19 | } 20 | -------------------------------------------------------------------------------- /man/cal_expr_by_group.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/NeuronChat_source_file.R 3 | \name{cal_expr_by_group} 4 | \alias{cal_expr_by_group} 5 | \title{Calculate the average gene expression by cell group} 6 | \usage{ 7 | cal_expr_by_group(df, gene_used, mean_method = NULL) 8 | } 9 | \arguments{ 10 | \item{df}{a data frame or data.table containing signaling gene expression (row: cell; column: genes; the last column is cell group labels)} 11 | 12 | \item{gene_used}{gene symbols used to calculate average expression for cell groups} 13 | } 14 | \value{ 15 | 16 | } 17 | \description{ 18 | Calculate the average gene expression by cell group 19 | } 20 | -------------------------------------------------------------------------------- /man/cal_prob_mtx_downstream.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/NeuronChat_source_file.R 3 | \name{cal_prob_mtx_downstream} 4 | \alias{cal_prob_mtx_downstream} 5 | \title{Calculate the communication strength matrix for a single ligand-target pair (without permutation test)} 6 | \usage{ 7 | cal_prob_mtx_downstream( 8 | df, 9 | sender, 10 | receiver, 11 | lig_contributor_new, 12 | lig_contributor_group, 13 | lig_contributor_coeff, 14 | receptor_subunit_new, 15 | receptor_subunit_group, 16 | receptor_subunit_coeff, 17 | targets_up, 18 | targets_down, 19 | targets_nichenet, 20 | N, 21 | K = 0.5, 22 | method = NULL, 23 | mean_method = NULL 24 | ) 25 | } 26 | \arguments{ 27 | \item{df}{a data frame or data.table containing signaling gene expression (row: cell; column: genes; the last column is cell group labels)} 28 | 29 | \item{sender}{sending cell groups} 30 | 31 | \item{receiver}{receiving cell groups} 32 | 33 | \item{lig_contributor_new}{a vector with updated gene symbols (removing those excluded from the expression data) that are regarded as ligand contributors} 34 | 35 | \item{lig_contributor_group}{a vector indicating the grouping of ligand contributors} 36 | 37 | \item{lig_contributor_coeff}{a vector with stoichiometry of each group of ligand contributors for calculating ligand abundance} 38 | 39 | \item{receptor_subunit_new}{a vector with updated gene symbols (removing those excluded from the expression data) that are regarded as target subunits} 40 | 41 | \item{receptor_subunit_group}{a vector indicating the grouping of target subunits} 42 | 43 | \item{receptor_subunit_coeff}{a vector with stoichiometry of each group of target subunits for calculating target abundance} 44 | 45 | \item{targets_up}{deprecated} 46 | 47 | \item{targets_down}{deprecated} 48 | 49 | \item{targets_nichenet}{deprecated} 50 | 51 | \item{N}{deprecated} 52 | 53 | \item{K}{Hill coefficient for CellChat modeling method} 54 | } 55 | \value{ 56 | 57 | } 58 | \description{ 59 | Calculate the communication strength matrix for a single ligand-target pair (without permutation test) 60 | } 61 | -------------------------------------------------------------------------------- /man/cell_proximity_enrichment_score.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/spatial_analysis_visualization.R 3 | \name{cell_proximity_enrichment_score} 4 | \alias{cell_proximity_enrichment_score} 5 | \title{Calculation of cell proximity enrichment score} 6 | \usage{ 7 | cell_proximity_enrichment_score( 8 | loc_centroid_subset_10K, 9 | celltype_label = "subclass", 10 | centroid_x = "centroid_x", 11 | centroid_y = "centroid_y", 12 | thresh_dist = 400, 13 | permutation_number = 1000, 14 | celltype = celltype 15 | ) 16 | } 17 | \arguments{ 18 | \item{loc_centroid_subset_10K}{A dataframe containing spatial locations and cell type annotations of cells} 19 | 20 | \item{celltype_label}{variable name (character) in loc_centroid_subset_10K, to indicate the cell type annotations of cells} 21 | 22 | \item{centroid_x}{variable name (character) in loc_centroid_subset_10K, to indicate the x coordinates of cells} 23 | 24 | \item{centroid_y}{variable name (character) in loc_centroid_subset_10K, to indicate the y coordinates of cells} 25 | 26 | \item{thresh_dist}{distance threshold (a scalar) used to determine the spatial neighbors of cells} 27 | 28 | \item{permutation_number}{number of permutations (a scalar) used to calculate expected frequency matrices and p-values} 29 | 30 | \item{celltype}{uniqued cell type names (a vector)} 31 | } 32 | \value{ 33 | A list contains orginal frequency matrix, permutation frequency matrices, dataframe containing cell proximity enrichment score & pvalue, CPscore matrix, pvalue (adjusted) matrix 34 | } 35 | \description{ 36 | Calculation of cell proximity enrichment score & associated p-values (internal function) 37 | } 38 | -------------------------------------------------------------------------------- /man/cell_proximity_enrichment_score_multiple.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/spatial_analysis_visualization.R 3 | \name{cell_proximity_enrichment_score_multiple} 4 | \alias{cell_proximity_enrichment_score_multiple} 5 | \title{Calculation of cell proximity enrichment score for multiple tissue slices} 6 | \usage{ 7 | cell_proximity_enrichment_score_multiple( 8 | meta, 9 | celltype_label = "subclass", 10 | centroid_x = "centroid_x", 11 | centroid_y = "centroid_y", 12 | slice_id = "slice_id", 13 | thresh_dist = 400, 14 | permutation_number = 1000 15 | ) 16 | } 17 | \arguments{ 18 | \item{meta}{A dataframe containing spatial locations and cell type annotations of cells} 19 | 20 | \item{celltype_label}{variable name (character) in meta, to indicate the cell type annotations of cells} 21 | 22 | \item{centroid_x}{variable name (character) in meta, to indicate the x coordinates of cells} 23 | 24 | \item{centroid_y}{variable name (character) in meta, to indicate the y coordinates of cells} 25 | 26 | \item{slice_id}{variable name (character) in meta, to indicate slice id of cells} 27 | 28 | \item{thresh_dist}{distance threshold (a scalar) used to determine the spatial neighbors of cells} 29 | 30 | \item{permutation_number}{number of permutations (a scalar) used to calculate expected frequency matrices and p-values} 31 | } 32 | \value{ 33 | A list contains orginal frequency matrix, permutation frequency matrices, dataframe containing cell proximity enrichment score & pvalue, CPscore matrix, pvalue (adjusted) matrix 34 | } 35 | \description{ 36 | Calculation of cell proximity enrichment score & associated p-values for multiple tissue slices 37 | } 38 | -------------------------------------------------------------------------------- /man/cell_proximity_enrichment_score_single.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/spatial_analysis_visualization.R 3 | \name{cell_proximity_enrichment_score_single} 4 | \alias{cell_proximity_enrichment_score_single} 5 | \title{Calculation of cell proximity enrichment score for single tissue slice} 6 | \usage{ 7 | cell_proximity_enrichment_score_single( 8 | meta, 9 | celltype_label = "subclass", 10 | centroid_x = "centroid_x", 11 | centroid_y = "centroid_y", 12 | thresh_dist = 400, 13 | permutation_number = 1000 14 | ) 15 | } 16 | \arguments{ 17 | \item{meta}{A dataframe containing spatial locations and cell type annotations of cells} 18 | 19 | \item{celltype_label}{variable name (character) in meta, to indicate the cell type annotations of cells} 20 | 21 | \item{centroid_x}{variable name (character) in meta, to indicate the x coordinates of cells} 22 | 23 | \item{centroid_y}{variable name (character) in meta, to indicate the y coordinates of cells} 24 | 25 | \item{thresh_dist}{distance threshold (a scalar) used to determine the spatial neighbors of cells} 26 | 27 | \item{permutation_number}{number of permutations (a scalar) used to calculate expected frequency matrices and p-values} 28 | } 29 | \value{ 30 | A list contains orginal frequency matrix, permutation frequency matrices, dataframe containing cell proximity enrichment score & pvalue, CPscore matrix, pvalue (adjusted) matrix 31 | } 32 | \description{ 33 | Calculation of cell proximity enrichment score & associated p-values for single tissue slice 34 | } 35 | -------------------------------------------------------------------------------- /man/compareInteractions_Neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/network_analysis.R 3 | \name{compareInteractions_Neuron} 4 | \alias{compareInteractions_Neuron} 5 | \title{Comparing the number of inferred communication links between different datasets} 6 | \usage{ 7 | compareInteractions_Neuron( 8 | object, 9 | measure = c("count", "weight"), 10 | color.use = NULL, 11 | group = NULL, 12 | comparison = c(1, 2), 13 | group.levels = NULL, 14 | group.facet = NULL, 15 | group.facet.levels = NULL, 16 | n.row = 1, 17 | color.alpha = 1, 18 | legend.title = NULL, 19 | width = 0.6, 20 | title.name = NULL, 21 | digits = 3, 22 | xlabel = NULL, 23 | ylabel = NULL, 24 | remove.xtick = FALSE, 25 | show.legend = TRUE, 26 | x.lab.rot = FALSE, 27 | angle.x = 45, 28 | vjust.x = NULL, 29 | hjust.x = 1, 30 | size.text = 10 31 | ) 32 | } 33 | \arguments{ 34 | \item{object}{A merged NeuronChat object} 35 | 36 | \item{measure}{"count" or "weight". "count": comparing the number of interactions; "weight": comparing the total interaction weights (strength)} 37 | 38 | \item{color.use}{defining the color for each group of datasets} 39 | 40 | \item{group}{a vector giving the groups of different datasets to define colors of the bar plot. Default: only one group and a single color} 41 | 42 | \item{group.levels}{the factor level in the defined group} 43 | 44 | \item{group.facet}{Name of one metadata column defining faceting groups} 45 | 46 | \item{group.facet.levels}{the factor level in the defined group.facet} 47 | 48 | \item{n.row}{Number of rows in facet_grid()} 49 | 50 | \item{color.alpha}{transparency} 51 | 52 | \item{legend.title}{legend title} 53 | 54 | \item{width}{bar width} 55 | 56 | \item{title.name}{main title of the plot} 57 | 58 | \item{digits}{integer indicating the number of decimal places (round) to be used when \code{measure} is \code{weight}.} 59 | 60 | \item{xlabel}{label of x-axis} 61 | 62 | \item{ylabel}{label of y-axis} 63 | 64 | \item{remove.xtick}{whether remove xtick} 65 | 66 | \item{show.legend}{whether show the legend} 67 | 68 | \item{x.lab.rot, angle.x, vjust.x, hjust.x}{adjusting parameters if rotating xtick.labels when x.lab.rot = TRUE} 69 | 70 | \item{size.text}{font size of the text} 71 | } 72 | \value{ 73 | A ggplot object 74 | } 75 | \description{ 76 | Comparing the number of inferred communication links between different datasets; adapted from CellChat https://github.com/sqjin/CellChat 77 | } 78 | -------------------------------------------------------------------------------- /man/computeNetSimilarityPairwise_Neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/network_analysis.R 3 | \name{computeNetSimilarityPairwise_Neuron} 4 | \alias{computeNetSimilarityPairwise_Neuron} 5 | \title{Compute signaling network similarity for any pair of datasets} 6 | \usage{ 7 | computeNetSimilarityPairwise_Neuron( 8 | object, 9 | slot.name = "net", 10 | type = c("functional"), 11 | comparison = NULL, 12 | k = NULL, 13 | thresh = NULL 14 | ) 15 | } 16 | \arguments{ 17 | \item{object}{A merged NeuronChat object} 18 | 19 | \item{slot.name}{the slot name of object that is used to store communication strength matrices, i.e., 'net'} 20 | 21 | \item{type}{"functional","structural"} 22 | 23 | \item{comparison}{a numerical vector giving the datasets for comparison} 24 | 25 | \item{k}{the number of nearest neighbors} 26 | 27 | \item{thresh}{the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity} 28 | } 29 | \value{ 30 | 31 | } 32 | \description{ 33 | Compute signaling network similarity for any pair of datasets; adapted from CellChat https://github.com/sqjin/CellChat 34 | } 35 | -------------------------------------------------------------------------------- /man/computeNetSimilarity_Neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/network_analysis.R 3 | \name{computeNetSimilarity_Neuron} 4 | \alias{computeNetSimilarity_Neuron} 5 | \title{Compute signaling network similarity for any pair of signaling networks} 6 | \usage{ 7 | computeNetSimilarity_Neuron( 8 | object, 9 | slot.name = "net", 10 | type = c("functional", "structural"), 11 | k = NULL, 12 | thresh = NULL 13 | ) 14 | } 15 | \arguments{ 16 | \item{object}{NeuronChat object} 17 | 18 | \item{slot.name}{the slot name of object that is used to store communication strength matrices, i.e., 'net'} 19 | 20 | \item{type}{"functional"} 21 | 22 | \item{k}{the number of nearest neighbors} 23 | 24 | \item{thresh}{the fraction (0 to 0.25) of interactions to be trimmed before computing network similarity} 25 | } 26 | \value{ 27 | 28 | } 29 | \description{ 30 | Compute signaling network similarity for any pair of signaling networks; adapted from CellChat https://github.com/sqjin/CellChat 31 | } 32 | -------------------------------------------------------------------------------- /man/createNeuronChat.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/NeuronChat_source_file.R 3 | \name{createNeuronChat} 4 | \alias{createNeuronChat} 5 | \title{Create a new NeuronChat object from a data matrix 6 | Create a new NeuronChat object from a data matrix; adapted from CellChat https://github.com/sqjin/CellChat} 7 | \usage{ 8 | createNeuronChat( 9 | object, 10 | DB = c("mouse", "human"), 11 | meta = NULL, 12 | group.by = NULL, 13 | assay = NULL, 14 | do.sparse = T 15 | ) 16 | } 17 | \arguments{ 18 | \item{object}{a normalized (NOT count) data matrix (genes by cells)} 19 | 20 | \item{meta}{a data frame (rows are cells with rownames) consisting of cell information, which will be used for defining cell groups.} 21 | 22 | \item{group.by}{a vector to indicate group annotations of cells} 23 | 24 | \item{assay}{Assay to use when the input is a Seurat object.} 25 | 26 | \item{do.sparse}{whether use sparse format} 27 | } 28 | \value{ 29 | 30 | } 31 | \description{ 32 | Create a new NeuronChat object from a data matrix 33 | Create a new NeuronChat object from a data matrix; adapted from CellChat https://github.com/sqjin/CellChat 34 | } 35 | -------------------------------------------------------------------------------- /man/heatmap_aggregated.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/visualization.R 3 | \name{heatmap_aggregated} 4 | \alias{heatmap_aggregated} 5 | \title{Heatmap plot for the aggregated communication} 6 | \usage{ 7 | heatmap_aggregated( 8 | object, 9 | method = c("weight", "count", "weighted_count", "weighted_count2", 10 | "weight_threshold"), 11 | cut_off = 0.05, 12 | interaction_use = "all", 13 | group = NULL, 14 | sender.names = NULL, 15 | receiver.names = NULL 16 | ) 17 | } 18 | \arguments{ 19 | \item{object}{a NeuronChat object} 20 | 21 | \item{method}{method used for aggregation; see also function \code{net_aggregation}} 22 | 23 | \item{cut_off}{threshold used for aggregation; see also function \code{net_aggregation}} 24 | 25 | \item{interaction_use}{ligand-target interaction indexes used for aggregation ('all' means use all interation pairs)} 26 | 27 | \item{group}{a vector indicating which cell types (cell subclass, e.g., L2/3 IT) belong to which big groups (cell class, e.g., Glutamatergic)} 28 | 29 | \item{sender.names}{sending cell groups used for plot} 30 | 31 | \item{receiver.names}{receiving cell groups used for plot} 32 | } 33 | \value{ 34 | 35 | } 36 | \description{ 37 | Heatmap plot for the aggregated communication 38 | } 39 | -------------------------------------------------------------------------------- /man/heatmap_single.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/visualization.R 3 | \name{heatmap_single} 4 | \alias{heatmap_single} 5 | \title{Heatmap plot with ligand abundance and target abundance for single ligand-target pair} 6 | \usage{ 7 | heatmap_single( 8 | object, 9 | interaction_name, 10 | group = NULL, 11 | sender.names = NULL, 12 | receiver.names = NULL 13 | ) 14 | } 15 | \arguments{ 16 | \item{object}{a NeuronChat object} 17 | 18 | \item{interaction_name}{the ligand-target interaction used to plot} 19 | 20 | \item{group}{a vector indicating which cell types (cell subclass, e.g., L2/3 IT) belong to which big groups (cell class, e.g., Glutamatergic)} 21 | 22 | \item{sender.names}{sending cell groups used for plot} 23 | 24 | \item{receiver.names}{receiving cell groups used for plot} 25 | } 26 | \value{ 27 | 28 | } 29 | \description{ 30 | Heatmap plot with ligand abundance and target abundance for single ligand-target pair 31 | } 32 | -------------------------------------------------------------------------------- /man/identifyCommunicationPatterns_Neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/network_analysis.R 3 | \name{identifyCommunicationPatterns_Neuron} 4 | \alias{identifyCommunicationPatterns_Neuron} 5 | \title{Identification of major signals for specific cell groups and general communication patterns} 6 | \usage{ 7 | identifyCommunicationPatterns_Neuron( 8 | object, 9 | slot.name = "net", 10 | pattern = c("outgoing", "incoming"), 11 | k = NULL, 12 | k.range = seq(2, 10), 13 | heatmap.show = TRUE, 14 | color.use = NULL, 15 | color.heatmap = "Spectral", 16 | title.legend = "Contributions", 17 | width = 4, 18 | height = 6, 19 | font.size = 8, 20 | thresh_quantile = 0 21 | ) 22 | } 23 | \arguments{ 24 | \item{object}{NeuronChat object} 25 | 26 | \item{slot.name}{the slot name of object that is used to store communication strength matrices, i.e., 'net'} 27 | 28 | \item{pattern}{"outgoing" or "incoming"} 29 | 30 | \item{k}{the number of patterns} 31 | 32 | \item{k.range}{a range of the number of patterns} 33 | 34 | \item{heatmap.show}{whether showing heatmap} 35 | 36 | \item{color.use}{the character vector defining the color of each cell group} 37 | 38 | \item{color.heatmap}{a color name in brewer.pal} 39 | 40 | \item{title.legend}{the title of legend in heatmap} 41 | 42 | \item{width}{width of heatmap} 43 | 44 | \item{height}{height of heatmap} 45 | 46 | \item{font.size}{fontsize in heatmap} 47 | } 48 | \value{ 49 | 50 | } 51 | \description{ 52 | Identification of major signals for specific cell groups and general communication patterns; adapted from CellChat https://github.com/sqjin/CellChat 53 | } 54 | -------------------------------------------------------------------------------- /man/lig_tar_heatmap.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/visualization.R 3 | \name{lig_tar_heatmap} 4 | \alias{lig_tar_heatmap} 5 | \title{A set of plots illustrating the communication network as well as violin plots for related genes for single ligand-target pair} 6 | \usage{ 7 | lig_tar_heatmap( 8 | object, 9 | interaction_name, 10 | width.vector = c(0.3, 0.34, 0.31), 11 | sender.names = NULL, 12 | receiver.names = NULL 13 | ) 14 | } 15 | \arguments{ 16 | \item{object}{a NeuronChat object} 17 | 18 | \item{interaction_name}{the ligand-target interaction used to plot} 19 | 20 | \item{sender.names}{sending cell groups used for plot} 21 | 22 | \item{receiver.names}{receiving cell groups used for plot} 23 | } 24 | \value{ 25 | 26 | } 27 | \description{ 28 | A set of plots illustrating the communication network as well as violin plots for related genes for single ligand-target pair 29 | } 30 | -------------------------------------------------------------------------------- /man/mergeNeuronChat.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/NeuronChat_source_file.R 3 | \name{mergeNeuronChat} 4 | \alias{mergeNeuronChat} 5 | \title{Merge NeuronChat objects 6 | Merge NeuronChat objects; adapted from CellChat https://github.com/sqjin/CellChat} 7 | \usage{ 8 | mergeNeuronChat( 9 | object.list, 10 | add.names = NULL, 11 | merge.data = FALSE, 12 | cell.prefix = FALSE 13 | ) 14 | } 15 | \arguments{ 16 | \item{object.list}{A list of multiple NeuronChat objects} 17 | 18 | \item{add.names}{A vector containing the name of each dataset} 19 | 20 | \item{merge.data}{whether merging the data for ALL genes. Default only merges the data of signaling genes} 21 | 22 | \item{cell.prefix}{whether prefix cell names} 23 | } 24 | \value{ 25 | 26 | } 27 | \description{ 28 | Merge NeuronChat objects 29 | Merge NeuronChat objects; adapted from CellChat https://github.com/sqjin/CellChat 30 | } 31 | -------------------------------------------------------------------------------- /man/netAnalysis_river_Neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/network_analysis.R 3 | \name{netAnalysis_river_Neuron} 4 | \alias{netAnalysis_river_Neuron} 5 | \title{River plot showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways} 6 | \usage{ 7 | netAnalysis_river_Neuron( 8 | object, 9 | slot.name = "net", 10 | pattern = c("outgoing", "incoming"), 11 | cutoff.1 = 0.25, 12 | cutoff.2 = 0.5, 13 | top.n1 = 10000, 14 | top.n2 = 10000, 15 | sources.use = NULL, 16 | targets.use = NULL, 17 | signaling = NULL, 18 | color.use = NULL, 19 | color.use.pattern = NULL, 20 | color.use.signaling = "grey50", 21 | do.order = FALSE, 22 | main.title = NULL, 23 | font.size = 2.5, 24 | font.size.title = 12 25 | ) 26 | } 27 | \arguments{ 28 | \item{object}{NeuronChat object} 29 | 30 | \item{slot.name}{the slot name of object that is used to store communication strength matrices, i.e., 'net'} 31 | 32 | \item{pattern}{"outgoing" or "incoming"} 33 | 34 | \item{sources.use}{a vector giving the index or the name of source cell groups of interest} 35 | 36 | \item{targets.use}{a vector giving the index or the name of target cell groups of interest} 37 | 38 | \item{signaling}{a character vector giving the name of signaling pathways of interest} 39 | 40 | \item{color.use}{the character vector defining the color of each cell group} 41 | 42 | \item{color.use.pattern}{the character vector defining the color of each pattern} 43 | 44 | \item{color.use.signaling}{the character vector defining the color of each signaling} 45 | 46 | \item{do.order}{whether reorder the cell groups or signaling according to their similarity} 47 | 48 | \item{main.title}{the title of plot} 49 | 50 | \item{font.size}{font size of the text} 51 | 52 | \item{font.size.title}{font size of the title} 53 | 54 | \item{cutoff}{the threshold for filtering out weak links} 55 | } 56 | \value{ 57 | 58 | } 59 | \description{ 60 | River plot showing the associations of latent patterns with cell groups and ligand-receptor pairs or signaling pathways; adapted from CellChat https://github.com/sqjin/CellChat 61 | River (alluvial) plot shows the correspondence between the inferred latent patterns and cell groups as well as ligand-receptor pairs or signaling pathways. 62 | } 63 | \details{ 64 | 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. 65 | 66 | Outgoing patterns reveal how the sender cells coordinate with each other as well as how they coordinate with certain signaling pathways to drive communication. 67 | 68 | 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. 69 | } 70 | -------------------------------------------------------------------------------- /man/netVisual_chord_neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/visualization.R 3 | \name{netVisual_chord_neuron} 4 | \alias{netVisual_chord_neuron} 5 | \title{Chord diagram of cell-cell communication network for single or multiple interaction pairs} 6 | \usage{ 7 | netVisual_chord_neuron( 8 | object, 9 | method = c("weight", "count", "weighted_count", "weighted_count2", 10 | "weight_threshold"), 11 | cut_off = 0.05, 12 | interaction_use = "all", 13 | group = NULL, 14 | sender.names = NULL, 15 | receiver.names = NULL, 16 | lab.cex = 1.3 17 | ) 18 | } 19 | \arguments{ 20 | \item{object}{a NeuronChat object} 21 | 22 | \item{method}{method used for aggregation; see also function \code{net_aggregation}} 23 | 24 | \item{cut_off}{threshold used for aggregation; see also function \code{net_aggregation}} 25 | 26 | \item{interaction_use}{ligand-target interaction indexes used for aggregation ('all' means use all interation pairs); for single interaction pair, set interaction_use as the interaction name or index, e.g., 'Glu_Gria2', or simply use CellChat function netVisual_chord_cell_internal(object@net[\link{'Glu_Gria2'}], group = group,lab.cex=1.3)} 27 | 28 | \item{group}{a vector indicating which cell types (cell subclass, e.g., L2/3 IT) belong to which big groups (cell class, e.g., Glutamatergic)} 29 | 30 | \item{sender.names}{sending cell groups used for plot} 31 | 32 | \item{receiver.names}{receiving cell groups used for plot} 33 | } 34 | \value{ 35 | 36 | } 37 | \description{ 38 | Chord diagram of cell-cell communication network for single or multiple interaction pairs 39 | } 40 | -------------------------------------------------------------------------------- /man/netVisual_circle_compare.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/visualization.R 3 | \name{netVisual_circle_compare} 4 | \alias{netVisual_circle_compare} 5 | \title{Circle plot comparing two cell-cell communication networks (for benchmarking)} 6 | \usage{ 7 | netVisual_circle_compare( 8 | net0, 9 | net1, 10 | color.use = NULL, 11 | group = NULL, 12 | title.name = NULL, 13 | sources.use = NULL, 14 | targets.use = NULL, 15 | remove.isolate = FALSE, 16 | top = 1, 17 | weight.scale = TRUE, 18 | vertex.weight = 20, 19 | vertex.weight.max = NULL, 20 | vertex.size.max = NULL, 21 | vertex.label.cex = 1.2, 22 | vertex.label.color = "black", 23 | edge.weight.max = NULL, 24 | edge.width.max = 5, 25 | alpha.edge = 0.6, 26 | label.edge = FALSE, 27 | edge.label.color = "black", 28 | edge.label.cex = 0.8, 29 | edge.curved = 0.2, 30 | shape = NULL, 31 | layout = in_circle(), 32 | margin = 0.2, 33 | vertex.size = NULL, 34 | arrow.width = 1, 35 | arrow.size = 0.2 36 | ) 37 | } 38 | \arguments{ 39 | \item{net0}{A weighted matrix representing the connections, regarded as the true communication network} 40 | 41 | \item{net1}{A weighted matrix representing the connections, regarded as the predicted communication network} 42 | 43 | \item{color.use}{Colors represent different cell groups} 44 | 45 | \item{group}{a vector indicating which cell types (cell subclass) belong to which big groups (cell class)} 46 | 47 | \item{title.name}{the name of the title} 48 | 49 | \item{sources.use}{a vector giving the index or the name of source cell groups} 50 | 51 | \item{targets.use}{a vector giving the index or the name of target cell groups.} 52 | 53 | \item{remove.isolate}{whether remove the isolate nodes in the communication network} 54 | 55 | \item{top}{the fraction of interactions to show} 56 | 57 | \item{weight.scale}{whether scale the weight} 58 | 59 | \item{vertex.weight}{The weight of vertex: either a scale value or a vector} 60 | 61 | \item{vertex.weight.max}{the maximum weight of vertex; defualt = max(vertex.weight)} 62 | 63 | \item{vertex.size.max}{the maximum vertex size for visualization} 64 | 65 | \item{vertex.label.cex}{The label size of vertex} 66 | 67 | \item{vertex.label.color}{The color of label for vertex} 68 | 69 | \item{edge.weight.max}{the maximum weight of edge; defualt = max(net)} 70 | 71 | \item{edge.width.max}{The maximum edge width for visualization} 72 | 73 | \item{alpha.edge}{the transprency of edge} 74 | 75 | \item{label.edge}{Whether or not shows the label of edges} 76 | 77 | \item{edge.label.color}{The color for single arrow} 78 | 79 | \item{edge.label.cex}{The size of label for arrows} 80 | 81 | \item{edge.curved}{Specifies whether to draw curved edges, or not. 82 | This can be a logical or a numeric vector or scalar. 83 | First the vector is replicated to have the same length as the number of 84 | edges in the graph. Then it is interpreted for each edge separately. 85 | A numeric value specifies the curvature of the edge; zero curvature means 86 | straight edges, negative values means the edge bends clockwise, positive 87 | values the opposite. TRUE means curvature 0.5, FALSE means curvature zero} 88 | 89 | \item{shape}{The shape of the vertex, currently “circle”, “square”, 90 | “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see 91 | vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the 92 | plot.igraph command. “none” does not draw the vertices at all, although 93 | vertex label are plotted (if given). See shapes for details about vertex 94 | shapes and vertex.shape.pie for using pie charts as vertices.} 95 | 96 | \item{layout}{The layout specification. It must be a call to a layout 97 | specification function.} 98 | 99 | \item{margin}{The amount of empty space below, over, at the left and right 100 | of the plot, it is a numeric vector of length four. Usually values between 101 | 0 and 0.5 are meaningful, but negative values are also possible, that will 102 | make the plot zoom in to a part of the graph. If it is shorter than four 103 | then it is recycled.} 104 | 105 | \item{vertex.size}{Deprecated. Use \code{vertex.weight}} 106 | 107 | \item{arrow.width}{The width of arrows} 108 | 109 | \item{arrow.size}{the size of arrow} 110 | 111 | \item{idents.use}{a vector giving the index or the name of cell groups of interest.} 112 | } 113 | \value{ 114 | an object of class "recordedplot" 115 | } 116 | \description{ 117 | Circle plot comparing two cell-cell communication networks (for benchmarking) (adapted from CellChat https://github.com/sqjin/CellChat) 118 | } 119 | -------------------------------------------------------------------------------- /man/netVisual_circle_neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/visualization.R 3 | \name{netVisual_circle_neuron} 4 | \alias{netVisual_circle_neuron} 5 | \title{Circle plot of cell-cell communication network} 6 | \usage{ 7 | netVisual_circle_neuron( 8 | net_ori, 9 | color.use = NULL, 10 | group = NULL, 11 | title.name = NULL, 12 | sources.use = NULL, 13 | targets.use = NULL, 14 | remove.isolate = FALSE, 15 | top = 1, 16 | weight.scale = TRUE, 17 | vertex.weight = 1, 18 | vertex.weight.max = NULL, 19 | vertex.size.max = NULL, 20 | vertex.label.cex = 1.2, 21 | vertex.label.color = "black", 22 | edge.weight.max = NULL, 23 | edge.width.max = 5, 24 | alpha.edge = 0.6, 25 | label.edge = FALSE, 26 | edge.label.color = "black", 27 | edge.label.cex = 0.8, 28 | edge.curved = 0.2, 29 | shape = NULL, 30 | layout = in_circle(), 31 | margin = 0.2, 32 | vertex.size = NULL, 33 | arrow.width = 1, 34 | arrow.size = 0.8 35 | ) 36 | } 37 | \arguments{ 38 | \item{net_ori}{A weighted matrix representing the connections} 39 | 40 | \item{color.use}{Colors represent different cell groups} 41 | 42 | \item{group}{a vector indicating which cell types (cell subclass, e.g., L2/3 IT) belong to which big groups (cell class, e.g., Glutamatergic)} 43 | 44 | \item{title.name}{the name of the title} 45 | 46 | \item{sources.use}{a vector giving the index or the name of source cell groups} 47 | 48 | \item{targets.use}{a vector giving the index or the name of target cell groups.} 49 | 50 | \item{remove.isolate}{whether remove the isolate nodes in the communication network} 51 | 52 | \item{top}{the fraction of interactions to show} 53 | 54 | \item{weight.scale}{whether scale the weight} 55 | 56 | \item{vertex.weight}{The weight of vertex: either a scale value or a vector} 57 | 58 | \item{vertex.weight.max}{the maximum weight of vertex; defualt = max(vertex.weight)} 59 | 60 | \item{vertex.size.max}{the maximum vertex size for visualization} 61 | 62 | \item{vertex.label.cex}{The label size of vertex} 63 | 64 | \item{vertex.label.color}{The color of label for vertex} 65 | 66 | \item{edge.weight.max}{the maximum weight of edge; defualt = max(net)} 67 | 68 | \item{edge.width.max}{The maximum edge width for visualization} 69 | 70 | \item{alpha.edge}{the transprency of edge} 71 | 72 | \item{label.edge}{Whether or not shows the label of edges} 73 | 74 | \item{edge.label.color}{The color for single arrow} 75 | 76 | \item{edge.label.cex}{The size of label for arrows} 77 | 78 | \item{edge.curved}{Specifies whether to draw curved edges, or not. 79 | This can be a logical or a numeric vector or scalar. 80 | First the vector is replicated to have the same length as the number of 81 | edges in the graph. Then it is interpreted for each edge separately. 82 | A numeric value specifies the curvature of the edge; zero curvature means 83 | straight edges, negative values means the edge bends clockwise, positive 84 | values the opposite. TRUE means curvature 0.5, FALSE means curvature zero} 85 | 86 | \item{shape}{The shape of the vertex, currently “circle”, “square”, 87 | “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see 88 | vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the 89 | plot.igraph command. “none” does not draw the vertices at all, although 90 | vertex label are plotted (if given). See shapes for details about vertex 91 | shapes and vertex.shape.pie for using pie charts as vertices.} 92 | 93 | \item{layout}{The layout specification. It must be a call to a layout 94 | specification function.} 95 | 96 | \item{margin}{The amount of empty space below, over, at the left and right 97 | of the plot, it is a numeric vector of length four. Usually values between 98 | 0 and 0.5 are meaningful, but negative values are also possible, that will 99 | make the plot zoom in to a part of the graph. If it is shorter than four 100 | then it is recycled.} 101 | 102 | \item{vertex.size}{Deprecated. Use \code{vertex.weight}} 103 | 104 | \item{arrow.width}{The width of arrows} 105 | 106 | \item{arrow.size}{the size of arrow} 107 | 108 | \item{idents.use}{a vector giving the index or the name of cell groups of interest.} 109 | } 110 | \value{ 111 | an object of class "recordedplot" 112 | } 113 | \description{ 114 | Circle plot of cell-cell communication network (adapted from CellChat https://github.com/sqjin/CellChat) 115 | } 116 | \details{ 117 | The width of edges represent the strength of the communication. 118 | } 119 | -------------------------------------------------------------------------------- /man/netVisual_embeddingPairwiseZoomIn_Neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/network_analysis.R 3 | \name{netVisual_embeddingPairwiseZoomIn_Neuron} 4 | \alias{netVisual_embeddingPairwiseZoomIn_Neuron} 5 | \title{Zoom into the 2D visualization of the joint manifold learning of signaling networks from two datasets} 6 | \usage{ 7 | netVisual_embeddingPairwiseZoomIn_Neuron( 8 | object, 9 | slot.name = "net_analysis", 10 | type = c("functional", "structural"), 11 | comparison = NULL, 12 | color.use = NULL, 13 | nCol = 1, 14 | point.shape = NULL, 15 | pathway.remove = NULL, 16 | dot.size = c(2, 6), 17 | label.size = 2.8, 18 | dot.alpha = 0.5, 19 | xlabel = NULL, 20 | ylabel = NULL, 21 | do.label = T, 22 | show.legend = F, 23 | show.axes = T 24 | ) 25 | } 26 | \arguments{ 27 | \item{object}{NeuronChat object} 28 | 29 | \item{slot.name}{the slot name of object that is used to store network analysis results, i.e., 'net_analysis'} 30 | 31 | \item{type}{"functional"} 32 | 33 | \item{comparison}{a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object} 34 | 35 | \item{color.use}{defining the color for each cell group} 36 | 37 | \item{nCol}{number of columns in the plot} 38 | 39 | \item{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} 40 | 41 | \item{pathway.remove}{a character vector defining the signaling to remove} 42 | 43 | \item{dot.size}{a range defining the size of the symbol} 44 | 45 | \item{label.size}{font size of the text} 46 | 47 | \item{dot.alpha}{transparency} 48 | 49 | \item{xlabel}{label of x-axis} 50 | 51 | \item{ylabel}{label of y-axis} 52 | 53 | \item{do.label}{label the each point} 54 | 55 | \item{show.legend}{whether show the legend} 56 | 57 | \item{show.axes}{whether show the axes} 58 | } 59 | \value{ 60 | 61 | } 62 | \description{ 63 | Zoom into the 2D visualization of the joint manifold learning of signaling networks from two datasets; adapted from CellChat https://github.com/sqjin/CellChat 64 | } 65 | -------------------------------------------------------------------------------- /man/netVisual_embeddingPairwise_Neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/network_analysis.R 3 | \name{netVisual_embeddingPairwise_Neuron} 4 | \alias{netVisual_embeddingPairwise_Neuron} 5 | \title{2D visualization of the joint manifold learning of signaling networks from two datasets} 6 | \usage{ 7 | netVisual_embeddingPairwise_Neuron( 8 | object, 9 | slot.name = "net_analysis", 10 | type = c("functional", "structural"), 11 | comparison = NULL, 12 | color.use = NULL, 13 | point.shape = NULL, 14 | pathway.labeled = NULL, 15 | top.label = 1, 16 | pathway.remove = NULL, 17 | pathway.remove.show = TRUE, 18 | dot.size = c(2, 6), 19 | label.size = 2.5, 20 | dot.alpha = 0.5, 21 | xlabel = "Dim 1", 22 | ylabel = "Dim 2", 23 | title = NULL, 24 | do.label = T, 25 | show.legend = T, 26 | show.axes = T 27 | ) 28 | } 29 | \arguments{ 30 | \item{object}{NeuronChat object} 31 | 32 | \item{slot.name}{the slot name of object that is used to store network analysis results, i.e., 'net_analysis'} 33 | 34 | \item{type}{"functional"} 35 | 36 | \item{comparison}{a numerical vector giving the datasets for comparison. Default are all datasets when object is a merged object} 37 | 38 | \item{color.use}{defining the color for each cell group} 39 | 40 | \item{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} 41 | 42 | \item{pathway.labeled}{a char vector giving the signaling names to show when labeling each point} 43 | 44 | \item{top.label}{the fraction of signaling pathways to label} 45 | 46 | \item{pathway.remove}{a character vector defining the signaling to remove} 47 | 48 | \item{pathway.remove.show}{whether show the removed signaling names} 49 | 50 | \item{dot.size}{a range defining the size of the symbol} 51 | 52 | \item{label.size}{font size of the text} 53 | 54 | \item{dot.alpha}{transparency} 55 | 56 | \item{xlabel}{label of x-axis} 57 | 58 | \item{ylabel}{label of y-axis} 59 | 60 | \item{title}{main title of the plot} 61 | 62 | \item{do.label}{label the each point} 63 | 64 | \item{show.legend}{whether show the legend} 65 | 66 | \item{show.axes}{whether show the axes} 67 | } 68 | \value{ 69 | 70 | } 71 | \description{ 72 | 2D visualization of the joint manifold learning of signaling networks from two datasets; adapted from CellChat https://github.com/sqjin/CellChat 73 | } 74 | -------------------------------------------------------------------------------- /man/netVisual_embeddingZoomIn_Neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/network_analysis.R 3 | \name{netVisual_embeddingZoomIn_Neuron} 4 | \alias{netVisual_embeddingZoomIn_Neuron} 5 | \title{Zoom into the 2D visualization of the learned manifold learning of the signaling networks} 6 | \usage{ 7 | netVisual_embeddingZoomIn_Neuron( 8 | object, 9 | slot.name = "net_analysis", 10 | type = c("functional", "structural"), 11 | color.use = NULL, 12 | pathway.remove = NULL, 13 | nCol = 1, 14 | dot.size = c(2, 6), 15 | label.size = 2.8, 16 | dot.alpha = 0.5, 17 | xlabel = NULL, 18 | ylabel = NULL, 19 | do.label = T, 20 | show.legend = F, 21 | show.axes = T 22 | ) 23 | } 24 | \arguments{ 25 | \item{object}{NeuronChat object} 26 | 27 | \item{slot.name}{the slot name of object that is used to store network analysis results, i.e., 'net_analysis'} 28 | 29 | \item{type}{"functional"} 30 | 31 | \item{color.use}{defining the color for each cell group} 32 | 33 | \item{pathway.remove}{a character vector defining the signaling to remove} 34 | 35 | \item{nCol}{the number of columns of the plot} 36 | 37 | \item{dot.size}{a range defining the size of the symbol} 38 | 39 | \item{label.size}{font size of the text} 40 | 41 | \item{dot.alpha}{transparency} 42 | 43 | \item{xlabel}{label of x-axis} 44 | 45 | \item{ylabel}{label of y-axis} 46 | 47 | \item{do.label}{label the each point} 48 | 49 | \item{show.legend}{whether show the legend} 50 | 51 | \item{show.axes}{whether show the axes} 52 | } 53 | \value{ 54 | 55 | } 56 | \description{ 57 | Zoom into the 2D visualization of the learned manifold learning of the signaling networks; adapted from CellChat https://github.com/sqjin/CellChat 58 | } 59 | -------------------------------------------------------------------------------- /man/netVisual_embedding_Neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/network_analysis.R 3 | \name{netVisual_embedding_Neuron} 4 | \alias{netVisual_embedding_Neuron} 5 | \title{2D visualization of the learned manifold of signaling networks} 6 | \usage{ 7 | netVisual_embedding_Neuron( 8 | object, 9 | slot.name = "net_analysis", 10 | type = c("functional", "structural"), 11 | color.use = NULL, 12 | pathway.labeled = NULL, 13 | top.label = 1, 14 | pathway.remove = NULL, 15 | pathway.remove.show = TRUE, 16 | dot.size = c(2, 6), 17 | label.size = 2, 18 | dot.alpha = 0.5, 19 | xlabel = "Dim 1", 20 | ylabel = "Dim 2", 21 | title = NULL, 22 | font.size = 10, 23 | font.size.title = 12, 24 | do.label = T, 25 | show.legend = T, 26 | show.axes = T 27 | ) 28 | } 29 | \arguments{ 30 | \item{object}{NeuronChat object} 31 | 32 | \item{slot.name}{the slot name of object that is used to store network analysis results, i.e., 'net_analysis'} 33 | 34 | \item{type}{"functional"} 35 | 36 | \item{color.use}{defining the color for each cell group} 37 | 38 | \item{pathway.labeled}{a char vector giving the signaling names to show when labeling each point} 39 | 40 | \item{top.label}{the fraction of signaling pathways to label} 41 | 42 | \item{pathway.remove}{a character vector defining the signaling to remove} 43 | 44 | \item{pathway.remove.show}{whether show the removed signaling names} 45 | 46 | \item{dot.size}{a range defining the size of the symbol} 47 | 48 | \item{label.size}{font size of the text} 49 | 50 | \item{dot.alpha}{transparency} 51 | 52 | \item{xlabel}{label of x-axis} 53 | 54 | \item{ylabel}{label of y-axis} 55 | 56 | \item{title}{main title of the plot} 57 | 58 | \item{font.size}{font size of the text} 59 | 60 | \item{font.size.title}{font size of the title} 61 | 62 | \item{do.label}{label the each point} 63 | 64 | \item{show.legend}{whether show the legend} 65 | 66 | \item{show.axes}{whether show the axes} 67 | } 68 | \value{ 69 | 70 | } 71 | \description{ 72 | 2D visualization of the learned manifold of signaling networks; adapted from CellChat https://github.com/sqjin/CellChat 73 | } 74 | -------------------------------------------------------------------------------- /man/netVisual_proximity.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/spatial_analysis_visualization.R 3 | \name{netVisual_proximity} 4 | \alias{netVisual_proximity} 5 | \title{Circle plot of cell-cell proximity network} 6 | \usage{ 7 | netVisual_proximity( 8 | net_ori, 9 | color.use = NULL, 10 | group = NULL, 11 | title.name = NULL, 12 | sources.use = NULL, 13 | targets.use = NULL, 14 | remove.isolate = FALSE, 15 | top = 1, 16 | weight.scale = TRUE, 17 | vertex.weight = 1, 18 | vertex.weight.max = NULL, 19 | vertex.size.max = 10, 20 | vertex.label.cex = 1.5, 21 | vertex.label.color = "black", 22 | edge.weight.max = NULL, 23 | edge.width.max = 10, 24 | alpha.edge = 0.6, 25 | label.edge = FALSE, 26 | edge.label.color = "black", 27 | edge.label.cex = 0.8, 28 | edge.curved = 0, 29 | shape = NULL, 30 | layout = in_circle(), 31 | margin = 0.2, 32 | vertex.size = NULL, 33 | arrow.width = 0, 34 | arrow.size = 0 35 | ) 36 | } 37 | \arguments{ 38 | \item{net_ori}{A weighted matrix representing the connections} 39 | 40 | \item{color.use}{Colors represent different cell groups} 41 | 42 | \item{group}{a vector indicating which cell types (cell subclass, e.g., L2/3 IT) belong to which big groups (cell class, e.g., Glutamatergic)} 43 | 44 | \item{title.name}{the name of the title} 45 | 46 | \item{sources.use}{a vector giving the index or the name of source cell groups} 47 | 48 | \item{targets.use}{a vector giving the index or the name of target cell groups.} 49 | 50 | \item{remove.isolate}{whether remove the isolate nodes in the communication network} 51 | 52 | \item{top}{the fraction of interactions to show} 53 | 54 | \item{weight.scale}{whether scale the weight} 55 | 56 | \item{vertex.weight}{The weight of vertex: either a scale value or a vector} 57 | 58 | \item{vertex.weight.max}{the maximum weight of vertex; defualt = max(vertex.weight)} 59 | 60 | \item{vertex.size.max}{the maximum vertex size for visualization} 61 | 62 | \item{vertex.label.cex}{The label size of vertex} 63 | 64 | \item{vertex.label.color}{The color of label for vertex} 65 | 66 | \item{edge.weight.max}{the maximum weight of edge; defualt = max(net)} 67 | 68 | \item{edge.width.max}{The maximum edge width for visualization} 69 | 70 | \item{alpha.edge}{the transprency of edge} 71 | 72 | \item{label.edge}{Whether or not shows the label of edges} 73 | 74 | \item{edge.label.color}{The color for single arrow} 75 | 76 | \item{edge.label.cex}{The size of label for arrows} 77 | 78 | \item{edge.curved}{Specifies whether to draw curved edges, or not. 79 | This can be a logical or a numeric vector or scalar. 80 | First the vector is replicated to have the same length as the number of 81 | edges in the graph. Then it is interpreted for each edge separately. 82 | A numeric value specifies the curvature of the edge; zero curvature means 83 | straight edges, negative values means the edge bends clockwise, positive 84 | values the opposite. TRUE means curvature 0.5, FALSE means curvature zero} 85 | 86 | \item{shape}{The shape of the vertex, currently “circle”, “square”, 87 | “csquare”, “rectangle”, “crectangle”, “vrectangle”, “pie” (see 88 | vertex.shape.pie), ‘sphere’, and “none” are supported, and only by the 89 | plot.igraph command. “none” does not draw the vertices at all, although 90 | vertex label are plotted (if given). See shapes for details about vertex 91 | shapes and vertex.shape.pie for using pie charts as vertices.} 92 | 93 | \item{layout}{The layout specification. It must be a call to a layout 94 | specification function.} 95 | 96 | \item{margin}{The amount of empty space below, over, at the left and right 97 | of the plot, it is a numeric vector of length four. Usually values between 98 | 0 and 0.5 are meaningful, but negative values are also possible, that will 99 | make the plot zoom in to a part of the graph. If it is shorter than four 100 | then it is recycled.} 101 | 102 | \item{vertex.size}{Deprecated. Use \code{vertex.weight}} 103 | 104 | \item{arrow.width}{The width of arrows} 105 | 106 | \item{arrow.size}{the size of arrow} 107 | 108 | \item{idents.use}{a vector giving the index or the name of cell groups of interest.} 109 | } 110 | \value{ 111 | an object of class "recordedplot" 112 | } 113 | \description{ 114 | Circle plot of cell-cell proximity network (adapted from CellChat https://github.com/sqjin/CellChat) 115 | } 116 | \details{ 117 | The width of edges represent the absolute value of cell proximity enrichment score; 118 | red line means enriched cell proximity while grey line means depleted cell proximity 119 | } 120 | -------------------------------------------------------------------------------- /man/net_aggregation.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/NeuronChat_source_file.R 3 | \name{net_aggregation} 4 | \alias{net_aggregation} 5 | \title{Aggregation of communication networks over all ligand-target pairs} 6 | \usage{ 7 | net_aggregation( 8 | net_list, 9 | method = c("weight", "count", "weighted_count", "weighted_count2", 10 | "weight_threshold"), 11 | cut_off = 0.05 12 | ) 13 | } 14 | \arguments{ 15 | \item{net_list}{a list containing communication strength matrices for all ligand-target pairs, e.g., 'net' slot of NeuronChat object after run 'run_NeuronChat'} 16 | 17 | \item{method}{one of 'weight','count','weighted_count','weighted_count2' and 'weight_threshold'} 18 | 19 | \item{cut_off}{threshold used for methods 'weighted_count2' and 'weight_threshold'} 20 | } 21 | \value{ 22 | 23 | } 24 | \description{ 25 | Aggregation of communication networks over all ligand-target pairs 26 | } 27 | -------------------------------------------------------------------------------- /man/neuron_chat_downstream.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/NeuronChat_source_file.R 3 | \name{neuron_chat_downstream} 4 | \alias{neuron_chat_downstream} 5 | \title{Calculate the communication strength matrix for a single ligand-target pair (with permutation test)} 6 | \usage{ 7 | neuron_chat_downstream( 8 | df, 9 | sender, 10 | receiver, 11 | interaction_name, 12 | lig_contributor, 13 | lig_contributor_group, 14 | lig_contributor_coeff, 15 | receptor_subunit, 16 | receptor_subunit_group, 17 | receptor_subunit_coeff, 18 | targets_up, 19 | targets_down, 20 | targets_nichenet, 21 | N, 22 | M, 23 | fdr, 24 | K = 0.5, 25 | method = NULL, 26 | mean_method = NULL 27 | ) 28 | } 29 | \arguments{ 30 | \item{df}{a data frame or data.table containing signaling gene expression (row: cell; column: genes; the last column is cell group labels)} 31 | 32 | \item{sender}{sending cell groups} 33 | 34 | \item{receiver}{receiving cell groups} 35 | 36 | \item{interaction_name}{name of the ligand-target interaction} 37 | 38 | \item{lig_contributor}{a vector with gene symbols that are regarded as ligand contributors} 39 | 40 | \item{lig_contributor_group}{a vector indicating the grouping of ligand contributors} 41 | 42 | \item{lig_contributor_coeff}{a vector with stoichiometry of each group of ligand contributors for calculating ligand abundance} 43 | 44 | \item{receptor_subunit_group}{a vector indicating the grouping of target subunits} 45 | 46 | \item{receptor_subunit_coeff}{a vector with stoichiometry of each group of target subunits for calculating target abundance} 47 | 48 | \item{targets_up}{deprecated} 49 | 50 | \item{targets_down}{deprecated} 51 | 52 | \item{targets_nichenet}{deprecated} 53 | 54 | \item{N}{deprecated} 55 | 56 | \item{M}{number of permutation tests} 57 | 58 | \item{fdr}{cutoff value that determines the significance of detected link} 59 | 60 | \item{K}{deprecated} 61 | 62 | \item{receptor_subunit_new}{a vector with updated gene symbols (removing those excluded from the expression data) that are regarded as target subunits} 63 | } 64 | \value{ 65 | 66 | } 67 | \description{ 68 | Calculate the communication strength matrix for a single ligand-target pair (with permutation test) 69 | } 70 | -------------------------------------------------------------------------------- /man/rankNet_Neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/network_analysis.R 3 | \name{rankNet_Neuron} 4 | \alias{rankNet_Neuron} 5 | \title{Rank signaling networks based on the information flow or the number of interactions} 6 | \usage{ 7 | rankNet_Neuron( 8 | object, 9 | slot.name = "net", 10 | measure = c("weight", "count"), 11 | mode = c("comparison", "single"), 12 | comparison = c(1, 2), 13 | color.use = NULL, 14 | stacked = FALSE, 15 | sources.use = NULL, 16 | targets.use = NULL, 17 | signaling = NULL, 18 | pairLR = NULL, 19 | do.stat = FALSE, 20 | cutoff.pvalue = 0.05, 21 | tol = 0.05, 22 | thresh = 0.05, 23 | show.raw = FALSE, 24 | return.data = FALSE, 25 | x.rotation = 90, 26 | title = NULL, 27 | bar.w = 0.75, 28 | font.size = 8, 29 | do.flip = TRUE, 30 | x.angle = NULL, 31 | y.angle = 0, 32 | x.hjust = 1, 33 | y.hjust = 1, 34 | axis.gap = FALSE, 35 | ylim = NULL, 36 | segments = NULL, 37 | tick_width = NULL, 38 | rel_heights = c(0.9, 0, 0.1) 39 | ) 40 | } 41 | \arguments{ 42 | \item{object}{NeuronChat object} 43 | 44 | \item{slot.name}{the slot name of object that is used to store communication strength matrices, i.e., 'net'} 45 | 46 | \item{measure}{"weight" or "count". "weight": comparing the total interaction weights (strength); "count": comparing the number of interactions;} 47 | 48 | \item{mode}{"single","comparison"} 49 | 50 | \item{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} 51 | 52 | \item{color.use}{defining the color for each cell group} 53 | 54 | \item{stacked}{whether plot the stacked bar plot} 55 | 56 | \item{sources.use}{a vector giving the index or the name of source cell groups} 57 | 58 | \item{targets.use}{a vector giving the index or the name of target cell groups.} 59 | 60 | \item{signaling}{a vector giving the signaling pathway to show} 61 | 62 | \item{pairLR}{a vector giving the names of L-R pairs to show (e.g, pairLR = c("IL1A_IL1R1_IL1RAP","IL1B_IL1R1_IL1RAP"))} 63 | 64 | \item{do.stat}{whether do a paired Wilcoxon test to determine whether there is significant difference between two datasets. Default = FALSE} 65 | 66 | \item{cutoff.pvalue}{the cutoff of pvalue when doing Wilcoxon test; Default = 0.05} 67 | 68 | \item{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} 69 | 70 | \item{thresh}{threshold of the p-value for determining significant interaction} 71 | 72 | \item{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.} 73 | 74 | \item{return.data}{whether return the data.frame consisting of the calculated information flow of each signaling pathway or L-R pair} 75 | 76 | \item{x.rotation}{rotation of x-labels} 77 | 78 | \item{title}{main title of the plot} 79 | 80 | \item{bar.w}{the width of bar plot} 81 | 82 | \item{font.size}{font size} 83 | 84 | \item{do.flip}{whether flip the x-y axis} 85 | 86 | \item{x.angle, y.angle, x.hjust, y.hjust}{parameters for rotating and spacing axis labels} 87 | 88 | \item{axis.gap}{whetehr making gaps in y-axes} 89 | 90 | \item{ylim, segments, tick_width, rel_heights}{parameters in the function gg.gap when making gaps in y-axes 91 | 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) 92 | https://tobiasbusch.xyz/an-r-package-for-everything-ep2-gaps} 93 | } 94 | \value{ 95 | 96 | } 97 | \description{ 98 | Rank signaling networks based on the information flow or the number of interactions; adapted from CellChat https://github.com/sqjin/CellChat 99 | } 100 | -------------------------------------------------------------------------------- /man/run_NeuronChat.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/NeuronChat_source_file.R 3 | \name{run_NeuronChat} 4 | \alias{run_NeuronChat} 5 | \title{Calculate the communication strength matrix for all ligand-target pairs} 6 | \usage{ 7 | run_NeuronChat( 8 | object = object, 9 | sender = NULL, 10 | receiver = NULL, 11 | N = 0, 12 | M = 100, 13 | fdr = 0.05, 14 | K = 0.5, 15 | method = NULL, 16 | mean_method = NULL, 17 | strict = 1 18 | ) 19 | } 20 | \arguments{ 21 | \item{object}{a NeuronChat object} 22 | 23 | \item{sender}{sending cell groups} 24 | 25 | \item{receiver}{receiving cell groups} 26 | 27 | \item{N}{deprecated} 28 | 29 | \item{M}{number of permutation tests} 30 | 31 | \item{fdr}{cutoff value that determines the significance of detected link} 32 | 33 | \item{K}{deprecated} 34 | 35 | \item{strict}{indicating whether the calculation of communication score for an ligand-target pair requires that input data include at least one gene for each contributing gene group. strict=1 means 'require', strict=0 means not 'require'. Default value is 1} 36 | } 37 | \value{ 38 | 39 | } 40 | \description{ 41 | Calculate the communication strength matrix for all ligand-target pairs 42 | } 43 | -------------------------------------------------------------------------------- /man/selectK_Neuron.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/network_analysis.R 3 | \name{selectK_Neuron} 4 | \alias{selectK_Neuron} 5 | \title{Select the number of the patterns for running \code{identifyCommunicationPatterns}} 6 | \usage{ 7 | selectK_Neuron( 8 | object, 9 | slot.name = "net", 10 | pattern = c("outgoing", "incoming"), 11 | title.name = NULL, 12 | do.facet = TRUE, 13 | k.range = seq(2, 10), 14 | nrun = 30, 15 | seed.use = 10 16 | ) 17 | } 18 | \arguments{ 19 | \item{object}{NeuronChat object} 20 | 21 | \item{pattern}{"outgoing" or "incoming"} 22 | 23 | \item{title.name}{title of plot} 24 | 25 | \item{do.facet}{whether use facet plot showing the two measures} 26 | 27 | \item{k.range}{a range of the number of patterns} 28 | 29 | \item{nrun}{number of runs when performing NMF} 30 | 31 | \item{seed.use}{seed when performing NMF} 32 | 33 | \item{slot.namethe}{slot name of object that is used to store communication strength matrices, i.e., 'net'} 34 | } 35 | \value{ 36 | a ggplot object 37 | } 38 | \description{ 39 | Select the number of the patterns for running \code{identifyCommunicationPatterns}; adapted from CellChat https://github.com/sqjin/CellChat 40 | 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. 41 | } 42 | -------------------------------------------------------------------------------- /man/spatialDistribution.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/spatial_analysis_visualization.R 3 | \name{spatialDistribution} 4 | \alias{spatialDistribution} 5 | \title{Spatial distribution of cell types along sptial axis} 6 | \usage{ 7 | spatialDistribution( 8 | meta, 9 | celltype_label = "subclass", 10 | centroid = "centroid_y", 11 | curve.alpha = 0.5, 12 | font.size = 20, 13 | legend.symbol.size = 5 14 | ) 15 | } 16 | \arguments{ 17 | \item{meta}{A dataframe containing spatial locations and cell type annotations of cells} 18 | 19 | \item{celltype_label}{variable name (character) in meta, to indicate the cell type annotations of cells} 20 | 21 | \item{centroid}{variable name (character) in meta, to indicate the x or y coordinates of cells} 22 | } 23 | \value{ 24 | a ggplot object 25 | } 26 | \description{ 27 | Spatial distribution of cell types along sptial axis 28 | } 29 | -------------------------------------------------------------------------------- /man/spatialMap.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/spatial_analysis_visualization.R 3 | \name{spatialMap} 4 | \alias{spatialMap} 5 | \title{Spatial plot of cells with their annotations} 6 | \usage{ 7 | spatialMap( 8 | meta, 9 | celltype_label = "subclass", 10 | centroid_x = "centroid_x", 11 | centroid_y = "centroid_y", 12 | pt.size = 5, 13 | pt.alpha = 0.8, 14 | font.size = 20, 15 | legend.symbol.size = 5 16 | ) 17 | } 18 | \arguments{ 19 | \item{meta}{A dataframe containing spatial locations and cell type annotations of cells} 20 | 21 | \item{celltype_label}{variable name (character) in meta, to indicate the cell type annotations of cells} 22 | 23 | \item{centroid_x}{variable name (character) in meta, to indicate the x coordinates of cells} 24 | 25 | \item{centroid_y}{variable name (character) in meta, to indicate the y coordinates of cells} 26 | } 27 | \value{ 28 | a ggplot object 29 | } 30 | \description{ 31 | Spatial plot of cells with their annotations 32 | } 33 | -------------------------------------------------------------------------------- /man/update_interactionDB.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/update_NeuronChatDB.R 3 | \name{update_interactionDB} 4 | \alias{update_interactionDB} 5 | \title{Update NeuronChatDB using user defined new entry information} 6 | \usage{ 7 | update_interactionDB( 8 | DB, 9 | interaction_name, 10 | lig_contributor, 11 | receptor_subunit, 12 | interaction_type = "user_defined", 13 | ligand_type = "user_defined", 14 | lig_contributor_group = NULL, 15 | lig_contributor_coeff = NULL, 16 | receptor_subunit_group = NULL, 17 | receptor_subunit_coeff = NULL 18 | ) 19 | } 20 | \arguments{ 21 | \item{DB}{current interation database (stored in slot 'DB' of NeuronChat object, i.e., object@DB)} 22 | 23 | \item{interaction_name}{a character to denote the name of the interaction to be added} 24 | 25 | \item{lig_contributor}{a vector of gene symbols, contributing to ligand abundance} 26 | 27 | \item{receptor_subunit}{a vector of gene symbols, contributing to receptor abundance} 28 | 29 | \item{interaction_type}{a character to denote the interaction type} 30 | 31 | \item{ligand_type}{a character to denote the ligand_type} 32 | 33 | \item{lig_contributor_group}{a vector of integers to indicate the biological function group of genes in \code{lig_contributor}; 34 | the length of \code{lig_contributor_group} is the same as \code{lig_contributor}} 35 | 36 | \item{lig_contributor_coeff}{a numerical vector to indicate the stoichiometric coefficients of ligand-contribuing groups, to calculate ligand abundance; 37 | the length is the same as the unique of \code{lig_contributor_group}} 38 | 39 | \item{receptor_subunit_group}{a vector of integers to indicate the biological function group of genes in \code{receptor_subunit}; 40 | the length of \code{receptor_subunit_group} is the same as \code{receptor_subunit}} 41 | 42 | \item{receptor_subunit_coeff}{a numerical vector to indicate the stoichiometric coefficients of receptor subunit groups, to calculate receptor abundance; 43 | the length is the same as the unique of \code{receptor_subunit_group}} 44 | } 45 | \value{ 46 | a updated interaction database (a list) 47 | } 48 | \description{ 49 | Update NeuronChatDB using user defined new entry information 50 | } 51 | -------------------------------------------------------------------------------- /tmp.R: -------------------------------------------------------------------------------- 1 | import(CellChat) 2 | import(ComplexHeatmap) 3 | import(NMF) 4 | import(Seurat) 5 | import(SeuratObject) 6 | import(circlize) 7 | import(data.table) 8 | import(ggalluvial) 9 | import(ggplot2) 10 | 11 | usethis::use_package("CellChat") 12 | usethis::use_package("ComplexHeatmap") 13 | usethis::use_package("NMF") 14 | usethis::use_package("Seurat") 15 | usethis::use_package("SeuratObject") 16 | usethis::use_package("circlize") 17 | usethis::use_package("data.table") 18 | usethis::use_package("ggalluvial") 19 | usethis::use_package("ggplot2") 20 | 21 | 22 | 23 | usethis::use_vignette("Update_NeuronChat_database") 24 | usethis::use_vignette("Spatial_analysis") 25 | usethis::use_readme_md(open = rlang::is_interactive()) 26 | rmarkdown::html_document() 27 | 28 | roxygen2::roxygenise() 29 | -------------------------------------------------------------------------------- /vignettes/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | *.R 3 | -------------------------------------------------------------------------------- /vignettes/NeuronChat-Tutorial.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Inference and analysis of neural-specific cell-cell communication using NeuronChat" 3 | author: "Wei Zhao" 4 | output: rmarkdown::html_document 5 | vignette: > 6 | %\VignetteIndexEntry{NeuronChat-Tutorial} 7 | %\VignetteEngine{knitr::rmarkdown} 8 | %\VignetteEncoding{UTF-8} 9 | --- 10 | 11 | ```{r, include = FALSE} 12 | knitr::opts_chunk$set( 13 | collapse = TRUE, 14 | comment = "#>" 15 | ) 16 | knitr::opts_chunk$set(fig.width=6, fig.height=6,fig.align = "center") 17 | ``` 18 | 19 | # Load NeuronChat library 20 | 21 | ```{r setup} 22 | library(NeuronChat) 23 | library(CellChat) 24 | ``` 25 | 26 | # Part I: Create NeuronChat object 27 | 28 | ```{r} 29 | # load example data: cortex data from Yao 2021, processed 30 | data(list='cortex_data') 31 | # subset the data by choosing the region VISp 32 | region_name <- 'VISp'; cell_class <- names(table(meta$class_label)) 33 | cell_idx <- which(meta$region_label %in% region_name & meta$class_label %in% cell_class & !(meta$subclass_label %in%c('Car3','CR','DG','L2/3 IT PPP','L5/6 IT TPE-ENT'))) 34 | target_df_single <- target_df[cell_idx,] # a data frame: row cell, column gene (the last column is the cell subclass) 35 | meta_tmp <- meta[cell_idx,];rownames(meta_tmp) <- meta_tmp$sample_name # subset meta 36 | df_group <- meta_tmp[!duplicated(meta_tmp$subclass_label),c('class_label','subclass_label')] 37 | group <- structure(df_group$class_label,names=df_group$subclass_label) # create the cell class for the subclasses, used for plot 38 | 39 | # creat NeuronChat object; choose the database 'mouse' for mouse data; 'human' for human data 40 | # note that the first parameter should be a numeric matrix with row gene and column cell 41 | x <- createNeuronChat(t(as.matrix(target_df_single[,1:(dim(target_df_single)[2]-1)])),DB='mouse',group.by = target_df_single$cell_subclass); 42 | ``` 43 | 44 | # Part II: Run NeuronChat to infer the neural-specific cell-cell communication networks 45 | 46 | ```{r} 47 | # M is for the permutation test; typically ~4 mins when M=100, depending on the dataset size and the number of cell groups 48 | # setting M=10 to get a quick start 49 | x <- run_NeuronChat(x,M=100) 50 | # the the communication networks for individual interaction pairs are stored in slot 'net' 51 | # aggregate the communication networks over all interaction pairs, method can be 'weight', 'count' and so on 52 | net_aggregated_x <- net_aggregation(x@net,method = 'weight') 53 | ``` 54 | 55 | # Part III: Visualization of neural-specific cell-cell communication networks 56 | 57 | ## for aggregated network 58 | 59 | ```{r fig00, fig.height = 6, fig.width = 12} 60 | par(mfrow=c(1,2)) 61 | # Visualization, circle plot, for the aggregated network 62 | netVisual_circle_neuron(net_aggregated_x,group=group,vertex.label.cex = 1) 63 | # Visualization, chordDiagram, for the aggregated network; also using cellchat function netVisual_chord_cell_internal(net_aggregated_x, group = group,lab.cex=1) 64 | netVisual_chord_neuron(x,method = 'weight',group=group,lab.cex = 1) 65 | ``` 66 | 67 | ```{r fig0, fig.height = 7, fig.width = 8} 68 | # Visualization, heatmap for the aggregated network 69 | heatmap_aggregated(x, method='weight',group=group) 70 | ``` 71 | 72 | ## for individual network 73 | 74 | ```{r fig1, fig.width=12, fig.height=6} 75 | par(mfrow=c(1,2)) 76 | # Visualization for the single interaction pair, circle plot 77 | netVisual_circle_neuron(x@net$Glu_Gria2,group=group,vertex.label.cex = 1) 78 | # Visualization for the single interaction pair, chord diagram 79 | netVisual_chord_neuron(x,interaction_use='Glu_Gria2',group=group,lab.cex = 1) 80 | ``` 81 | 82 | ```{r fig2, fig.height = 7, fig.width = 8} 83 | # Visualization for the single interaction pair, heatmap 84 | heatmap_single(x,interaction_name='Glu_Gria2',group=group) 85 | ``` 86 | 87 | ```{r fig3, fig.height = 6, fig.width = 18} 88 | # Visualization for the single interaction pair, heatmap with violin plots showing expression of genes realted to ligand and target 89 | lig_tar_heatmap(x,interaction_name='Glu_Gria2',width.vector=c(0.38,0.35,0.27)) 90 | ``` 91 | 92 | # Part IV: Analysis of communication 93 | 94 | ## barplot show the count of links or information flow for all interaction pairs 95 | 96 | ```{r fig4, fig.height = 12, fig.width = 6} 97 | g1 <- rankNet_Neuron(x,slot.name = "net",measure = c("weight"),mode='single',font.size = 5) 98 | g2 <- rankNet_Neuron(x,slot.name = "net",measure = c("count"),mode='single',font.size = 5) 99 | g1+g2 100 | ``` 101 | 102 | ## outgoing/incoming pattern 103 | 104 | ```{r} 105 | # selectK_Neuron(x,pattern = "outgoing") 106 | # selectK_Neuron(x,pattern = "incoming") 107 | x<- identifyCommunicationPatterns_Neuron(x, slot.name = "net", pattern = c("outgoing"), k=4,height = 18) 108 | x<- identifyCommunicationPatterns_Neuron(x, slot.name = "net", pattern = c("incoming"), k=4,height = 18) 109 | library(ggalluvial) 110 | netAnalysis_river_Neuron(x,slot.name = "net", pattern = c("outgoing"),font.size = 2.5,cutoff.1 = 0.5,cutoff.2=0.5) 111 | netAnalysis_river_Neuron(x,slot.name = "net", pattern = c("incoming"),font.size = 2.5,cutoff.1 = 0.5,cutoff.2=0.5) 112 | ``` 113 | 114 | ## manifold learning and classification 115 | 116 | ```{r} 117 | x <- computeNetSimilarity_Neuron(x,type='functional') 118 | x <- CellChat::netEmbedding(x, slot.name = "net_analysis", type = "functional") 119 | x <- CellChat::netClustering(x, type='functional',slot.name = "net_analysis",k=5) 120 | netVisual_embedding_Neuron(x, type = "functional", label.size = 5,pathway.remove.show = F) 121 | netVisual_embeddingZoomIn_Neuron(x, type = "functional", nCol = 2,label.size = 3) 122 | ``` 123 | -------------------------------------------------------------------------------- /vignettes/Spatial_analysis.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Spatial_analysis" 3 | author: "Wei Zhao" 4 | output: rmarkdown::html_vignette 5 | vignette: > 6 | %\VignetteIndexEntry{Spatial_analysis} 7 | %\VignetteEngine{knitr::rmarkdown} 8 | %\VignetteEncoding{UTF-8} 9 | --- 10 | 11 | ```{r, include = FALSE} 12 | knitr::opts_chunk$set( 13 | collapse = TRUE, 14 | comment = "#>" 15 | ) 16 | knitr::opts_chunk$set(fig.width=5, fig.height=5,fig.align = "center") 17 | ``` 18 | 19 | ```{r setup} 20 | library(NeuronChat) 21 | ``` 22 | ## Analysis of three spatial datasets 23 | ### Download processed data for the three datasets via the [link](https://github.com/Wei-BioMath/NeuronChatAnalysis2022/tree/main/Analysis_of_spatial_datasets) 24 | 25 | ### MERFISH dataset plus scRNA-seq 26 | ```{r fig08, fig.height = 5, fig.width = 10} 27 | ## MERFISH, 2021, https://www.nature.com/articles/s41586-021-03705-x 28 | load("/Users/weizhao/Documents/NeuronChat-ST/ST_datasets_processed/MERFISH/visual_spatial_MERFISH.rda") # using your own path 29 | set.seed(123) 30 | x <- createNeuronChat(t(mat_sc),DB='mouse',group.by = as.character(meta_sc$subclass_label)) # input data should be gene by cell matrix 31 | x <- run_NeuronChat(x,M=100) 32 | net_aggregated_x <- net_aggregation(x@net,method = 'weight') 33 | net <- net_aggregated_x/max(net_aggregated_x) 34 | # only keep top10 links with highest total weight 35 | net_sort <- sort(net,index.return =T,decreasing = T) 36 | net_top10 <-net*0;net_top10[net_sort$ix[1:10]] <-net[net_sort$ix[1:10]] 37 | # save(mat_sc,meta_sc, meta, net, net_top10,file='visual_spatial_MERFISH.rda') 38 | 39 | # circle plot of communication network 40 | par(mfrow=c(1,2)) 41 | library(scales);colours <- hue_pal()(dim(net)[1]); 42 | netVisual_circle_neuron(net,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 43 | netVisual_circle_neuron(net_top10,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 44 | ``` 45 | 46 | ```{r fig07, fig.height = 5, fig.width = 7} 47 | # spatial map of cell types 48 | spatialMap(meta,celltype_label = 'cell_type',centroid_x = 'sdimx',centroid_y = 'sdimy',pt.size = 1,pt.alpha = 0.8) + labs(x ="x coordinate", y = "y coordinate",color='Glutamatergic \n subclass') 49 | ``` 50 | ### seqFISH+ dataset 51 | ```{r fig06, fig.height = 5, fig.width = 10} 52 | ## seqFISH+, 2019, https://www.nature.com/articles/s41586-019-1049-y 53 | load("/Users/weizhao/Documents/NeuronChat-ST/ST_datasets_processed/SeqFISH/visual_spatial_seqFISH.rda") 54 | set.seed(123) 55 | x <- createNeuronChat(mat,DB='mouse',group.by = as.character(meta$cell_type)) 56 | x <- run_NeuronChat(x,M=100,strict = 0) # use strict=0 to allow calculation for interaction pairs with missing genes, e.g., 'Gls' is missing from this dataset 57 | net_aggregated_x <- net_aggregation(x@net,method = 'weight') 58 | net <- net_aggregated_x/max(net_aggregated_x) 59 | # only keep top10 links with highest total weight 60 | net_sort <- sort(net,index.return =T,decreasing = T) 61 | net_top10 <-net*0;net_top10[net_sort$ix[1:10]] <-net[net_sort$ix[1:10]] 62 | # save(mat,meta, net, net_top10,file='visual_spatial_seqFISH.rda') 63 | 64 | # circle plot of communication network 65 | par(mfrow=c(1,2)) 66 | library(scales);colours <- hue_pal()(dim(net)[1]); 67 | netVisual_circle_neuron(net,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 68 | netVisual_circle_neuron(net_top10,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 69 | ``` 70 | 71 | ```{r fig05, fig.height = 5, fig.width = 7} 72 | # spatial map of cell types 73 | spatialMap(meta,celltype_label = 'cell_type',centroid_x = 'sdimx',centroid_y = 'sdimy',pt.size = 5,pt.alpha = 0.8) + labs(x ="x coordinate", y = "y coordinate",color='cell type') 74 | ``` 75 | ### Visium dataset 76 | ```{r} 77 | ## Visium, 2020, https://support.10xgenomics.com/spatial-gene-expression/datasets/1.1.0/V1_Adult_Mouse_Brain 78 | load("/Users/weizhao/Documents/NeuronChat-ST/ST_datasets_processed/Visium/visual_spatial_Visium.rda") 79 | set.seed(123) 80 | x <- createNeuronChat(mat,DB='mouse',group.by = as.character(meta$cell_type)) 81 | x <- run_NeuronChat(x,M=100) 82 | net_aggregated_x <- net_aggregation(x@net,method = 'weight') 83 | net <- net_aggregated_x/max(net_aggregated_x) 84 | net <- net[levels(meta$cell_type),levels(meta$cell_type)] 85 | net_sort <- sort(net,index.return =T,decreasing = T) 86 | net_top10 <-net*0;net_top10[net_sort$ix[1:10]] <-net[net_sort$ix[1:10]] 87 | ``` 88 | 89 | ```{r fig04, fig.height = 5, fig.width = 10} 90 | par(mfrow=c(1,2)) 91 | library(scales);colours <- hue_pal()(dim(net)[1]);colours <- colours[c(3,2,1,4,5,6,7)] 92 | netVisual_circle_neuron(net,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 93 | netVisual_circle_neuron(net_top10,edge.width.max = 10,color.use = colours,vertex.label.cex = 1.5) 94 | ``` 95 | 96 | ```{r fig03, fig.height = 5, fig.width = 7} 97 | # save(mat,meta, net, net_top10,file='visual_spatial_Visium.rda') 98 | spatialMap(meta,celltype_label = 'cell_type',centroid_x = 'sdimx',centroid_y = 'sdimy',pt.size = 2,pt.alpha = 1) + labs(x ="x coordinate", y = "y coordinate",color='spot cluster') 99 | ``` 100 | ``` 101 | ## Spatially constrained communication network (download data via the [link](https://github.com/Wei-BioMath/NeuronChatAnalysis2022/tree/main/Tutorial_for_spatially_constrained_network)) 102 | ### data preparation 103 | ```{r} 104 | setwd('/Users/weizhao/Documents/NeuronChat-ST/MERFISH/processed_data/') 105 | # locations and cell type annotations of MERFISH for MOp 106 | loc_centroid_subset <- readRDS('meta_MERFISH.rds') 107 | # scRNA-seq data for MOp, with cell type annotations 108 | MOp_sc_list <- readRDS(file = 'MOp_sc_list.rds') 109 | MOp_sc_list$meta_sc$subclass_label <- sub(' CTX','',MOp_sc_list$meta_sc$subclass_label) 110 | cell_type_use <- unique(MOp_sc_list$meta_sc$subclass_label) 111 | cell_type_use_merfish <- unique(loc_centroid_subset$subclass) 112 | 113 | # cell types shared by MERFISH & scRNA-seq 114 | cell_type_shared <- sort(intersect(cell_type_use_merfish,cell_type_use),method='radix') 115 | cell_type_shared <- cell_type_shared[8:12] ## i.e., c("Lamp5","Pvalb","Sncg","Sst","Vip") 116 | ``` 117 | ### Calculation of spatial proximity for pairwise cell types 118 | ```{r} 119 | # subsetting MERFISH meta data for single slice ('mouse1_slice212') and cell_type_shared 120 | meta_single_slice <- loc_centroid_subset[loc_centroid_subset$slice_id=='mouse1_slice212' & loc_centroid_subset$subclass %in% cell_type_shared,] 121 | # calculating cell proximity enrichment score for single slice 122 | cell_proximity <- cell_proximity_enrichment_score_single(meta_single_slice,celltype_label='subclass',centroid_x='centroid_x', centroid_y='centroid_y', 123 | thresh_dist=400,permutation_number=1000) 124 | 125 | # subsetting MERFISH meta data for cell_type_shared but all slices 126 | meta_all_slices <- loc_centroid_subset[loc_centroid_subset$subclass %in% cell_type_shared,] 127 | # calculating cell proximity enrichment score for multiple slices (taking a little long time) 128 | cell_proximity <- cell_proximity_enrichment_score_multiple(meta_all_slices,celltype_label='subclass',centroid_x='centroid_x', centroid_y='centroid_y', slice_id='slice_id', 129 | thresh_dist=400,permutation_number=1000) 130 | # circle plot of cell proximity 131 | library(scales);colours <- hue_pal()(length(cell_type_shared)+1); colours[3] <- 'purple';colours[4] <- 'green'; 132 | netVisual_proximity(cell_proximity$log2CPscore_mtx,color.use = colours[1:5]) 133 | ``` 134 | 135 | ```{r fig02, fig.height = 5, fig.width = 7} 136 | # barplot of cell proximity 137 | barplot_proximity(cell_proximity$CPScore_df) 138 | ``` 139 | ### NeuronChat analysis + filtering the network by cell proximity information 140 | ```{r fig01, fig.height = 5, fig.width = 10} 141 | GABA_idx <- which(MOp_sc_list$meta_sc$subclass_label %in% cell_type_shared); 142 | MOp_sc_GABA <- MOp_sc_list$MOp_sc[GABA_idx,] 143 | meta_sc_GABA <- MOp_sc_list$meta_sc[GABA_idx,] 144 | x <- createNeuronChat(t(MOp_sc_GABA),DB='mouse',group.by = meta_sc_GABA$subclass_label); 145 | x <- run_NeuronChat(x,M=100) 146 | net_aggregated_x <- net_aggregation(x@net,method = 'weight') 147 | par(mfrow=c(1,2)) 148 | # original network 149 | netVisual_circle_neuron(net_aggregated_x, color.use = colours[1:5],vertex.size.max = 10,vertex.label.cex=1.5,edge.width.max=10) 150 | # spatially constrained network (by filtering out links with cell proximity enrichment scores (stored in cell_proximity$log2CPscore_mtx as a matrix form) lower than 0) 151 | netVisual_circle_neuron(net_aggregated_x*(cell_proximity$log2CPscore_mtx>0), color.use = colours[1:5],vertex.size.max = 10,vertex.label.cex=1.5,edge.width.max=10) 152 | ``` 153 | ```{r fig00, fig.height = 5, fig.width = 10} 154 | # spatialMap & spatial distribution 155 | p1 <- spatialMap(meta_single_slice,celltype_label='subclass',centroid_x='centroid_x', centroid_y='centroid_y', pt.size=1,pt.alpha=0.8,font.size=20,legend.symbol.size=5) 156 | p2 <- spatialDistribution(meta_single_slice, celltype_label='subclass',centroid='centroid_y', curve.alpha=0.5,font.size=20,legend.symbol.size=5) 157 | p1+p2 158 | ``` 159 | -------------------------------------------------------------------------------- /vignettes/Update_NeuronChat_database.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Update_NeuronChat_database" 3 | output: rmarkdown::html_vignette 4 | vignette: > 5 | %\VignetteIndexEntry{Update_NeuronChat_database} 6 | %\VignetteEngine{knitr::rmarkdown} 7 | %\VignetteEncoding{UTF-8} 8 | --- 9 | 10 | ```{r, include = FALSE} 11 | knitr::opts_chunk$set( 12 | collapse = TRUE, 13 | comment = "#>" 14 | ) 15 | ``` 16 | 17 | ```{r setup} 18 | library(NeuronChat) 19 | ``` 20 | ## Create NeuronChat object using orignal database (optional but for comparison with updated database) 21 | ```{r} 22 | # load example data: cortex data from Yao 2021, processed 23 | data(list='cortex_data') 24 | # subset the data by choosing the region VISp 25 | region_name <- 'VISp'; cell_class <- names(table(meta$class_label)) 26 | cell_idx <- which(meta$region_label %in% region_name & meta$class_label %in% cell_class & !(meta$subclass_label %in%c('Car3','CR','DG','L2/3 IT PPP','L5/6 IT TPE-ENT'))) 27 | target_df_single <- target_df[cell_idx,] # a data frame: row cell, column gene (the last column is the cell subclass) 28 | 29 | # creat NeuronChat object; choose the database 'mouse' for mouse data; 'human' for human data 30 | # note that the first parameter should be a numeric matrix with row gene and column cell 31 | x <- createNeuronChat(t(as.matrix(target_df_single[,1:(dim(target_df_single)[2]-1)])),DB='mouse',group.by = target_df_single$cell_subclass) 32 | ``` 33 | ## Access and update the current NeuronChat interaction database 34 | ```{r} 35 | # database is stored in the `DB` slot of NeuronChat object 36 | DB <- x@DB 37 | # view the number of entries in current database 38 | length(DB) 39 | 40 | # another way to access the database; replace 'mouse' to 'human' for human data 41 | data(list='interactionDB_mouse'); DB <- eval(parse(text = 'interactionDB_mouse')) 42 | 43 | # add one entry of user defined interaction pair to DB via function `update_interactionDB` 44 | # user needs to provide interaction_name (character), lig_contributor (a vector of genes), receptor_subunit (a vector of genes), 45 | # We show this functionality by applying it to the interaction between glutamate & 46 | # the AMPA receptor (e.g., subunit composition is Gria1:Gria2:Gria3 = 1:2:1) 47 | # Contributing genes of glutamate are Gls for synthesis and Slc17a6, Slc17a7, Slc17a8 for vesicular transport 48 | # Receptor subunits of AMPA are Gria1, Gria2, Gria3 49 | interaction_name <- 'Glu_AMPA' 50 | lig_contributor <- c('Gls','Slc17a6','Slc17a7','Slc17a8') 51 | receptor_subunit <- c('Gria1', 'Gria2', 'Gria3') 52 | lig_contributor_group <- c(1,2,2,2) # 'Gls' corresponds to group 1; 'Slc17a6','Slc17a7','Slc17a8' correspond to group 2 (redundant for vesicular transport) 53 | lig_contributor_coeff <- c(1,1) # stoichiometry coefficients (or weights) for groups in uniuqe(lig_contributor_group) 54 | receptor_subunit_group <- c(1,2,3) # 1 for Gria1, 2 for Gria2, and 3 for Gria3 55 | receptor_subunit_coeff <- c(1,2,1) # subunit composition is Gria1:Gria2:Gria3 = 1:2:1 56 | DB_new <- update_interactionDB(DB,interaction_name=interaction_name,lig_contributor=lig_contributor,receptor_subunit, 57 | interaction_type='user_defined',ligand_type='user_defined', 58 | lig_contributor_group=lig_contributor_group,lig_contributor_coeff=lig_contributor_coeff, 59 | receptor_subunit_group=receptor_subunit_group,receptor_subunit_coeff=receptor_subunit_coeff) 60 | length(DB_new) 61 | dplyr::glimpse(DB_new$Glu_AMPA) # view the newly added entries 62 | 63 | # assign the updated database to `interactionDB_mouse` 64 | interactionDB_mouse <- DB_new 65 | ``` 66 | 67 | ## Create NeuronChat object using the updated database 68 | ```{r} 69 | y <- createNeuronChat(t(as.matrix(target_df_single[,1:(dim(target_df_single)[2]-1)])),DB='mouse',group.by = target_df_single$cell_subclass) 70 | dplyr::glimpse(y@DB$Glu_AMPA) # check the newly added entries 71 | ``` 72 | 73 | 74 | -------------------------------------------------------------------------------- /vignettes/comparison.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Comparative analysis of multiple datasets" 3 | output: rmarkdown::html_vignette 4 | vignette: > 5 | %\VignetteIndexEntry{comparison} 6 | %\VignetteEngine{knitr::rmarkdown} 7 | %\VignetteEncoding{UTF-8} 8 | --- 9 | 10 | ```{r, include = FALSE} 11 | knitr::opts_chunk$set( 12 | collapse = TRUE, 13 | comment = "#>" 14 | ) 15 | knitr::opts_chunk$set(fig.width=6, fig.height=6,fig.align = "center") 16 | ``` 17 | This vignette will show how to use NeuronChat to perform comparative analysis on multiple datasets, by taking the comparison between VISp and ALM as an example. 18 | 19 | # Load NeuronChat library 20 | 21 | ```{r setup} 22 | library(NeuronChat) 23 | library(CellChat) 24 | ``` 25 | 26 | # Part I: Create NeuronChat object list 27 | 28 | ```{r} 29 | data(list='cortex_data') # including `target_df` and `meta` 30 | cortex_1K <- c('ALM','VISp') 31 | subclass_CTX <- names(table(meta$subclass_label[meta$class_label=='Glutamatergic']))[grep('CTX',names(table(meta$subclass_label[meta$class_label=='Glutamatergic'])))] # subset the Glutamatergic subclasses 32 | subclass_CTX 33 | set.seed(1234) 34 | cortex_list <- lapply(cortex_1K, function(y){ 35 | region_name <- y; cell_class <- 'Glutamatergic';if(is.null(cell_class)){cell_class <- names(table(meta$class_label))} 36 | cell_idx <- which(meta$region_label %in% region_name & meta$class_label %in% cell_class & meta$subclass_label %in% subclass_CTX) 37 | target_df_single <- target_df[cell_idx,] 38 | meta_tmp <- meta[cell_idx,];rownames(meta_tmp) <- meta_tmp$sample_name 39 | x <- createNeuronChat( t(as.matrix(target_df_single[,1:(dim(target_df_single)[2]-1)])),DB='mouse',group.by = target_df_single$cell_subclass,meta=meta_tmp); 40 | x <- run_NeuronChat(x,M=100) 41 | return(x) 42 | }) 43 | names(cortex_list) <- cortex_1K 44 | ``` 45 | ```{r fig0, fig.height = 5, fig.width = 10} 46 | # individually plotting the communication networks for VISp and ALM 47 | par(mfrow=c(1,2)) 48 | for(j in c(1,2)){ 49 | netVisual_circle_neuron(cortex_list[[j]]@net$Glu_Grin3a, title.name = paste('Glu_Grin3a -- ',names(cortex_list)[j]),arrow.size = 0.5,margin=0.3,edge.width.max=8) 50 | } 51 | par(mfrow=c(1,2)) 52 | for(j in c(1,2)){ 53 | net_aggregated_x <- net_aggregation(cortex_list[[j]]@net,method='weight') 54 | netVisual_circle_neuron(net_aggregated_x, title.name = names(cortex_list)[j],arrow.size = 0.5,margin=0.3,edge.width.max=8) 55 | } 56 | ``` 57 | 58 | # Part II: Merge the NeuronChat object list 59 | 60 | ```{r} 61 | neuronchat_list <- mergeNeuronChat(cortex_list, add.names = names(cortex_list)) 62 | ``` 63 | 64 | # Part III: Barplots to compare link count and weight of interaction pairs between ALM and VISp 65 | 66 | ```{r fig1, fig.height = 3, fig.width = 6} 67 | # overall communication 68 | p1 <- compareInteractions_Neuron(neuronchat_list,measure = c("weight"),comparison = c(1,2),group=c(1,2),show.legend = F) 69 | p2 <- compareInteractions_Neuron(neuronchat_list,measure = c("count"),comparison = c(1,2),group=c(1,2),show.legend = F ) 70 | p1 + p2 71 | ``` 72 | 73 | ```{r fig2, fig.height = 12, fig.width = 9} 74 | # communication for individual interaction pairs 75 | g1 <- rankNet_Neuron(neuronchat_list,mode='comparison',measure = c("count"),comparison = 1:2,do.stat = F,tol = 0.1,stacked = F,font.size = 11) 76 | g2 <- rankNet_Neuron(neuronchat_list,mode='comparison',measure = c("weight"),comparison = 1:2,do.stat = F,tol = 0.1,stacked = F,font.size = 11) 77 | g1+g2 78 | ``` 79 | 80 | # Part IV: Shared and specific interaction patterns across ALM and VISp 81 | 82 | ```{r fig3, fig.height = 4, fig.width = 5} 83 | # compute functional similarity 84 | neuronchat_list <- computeNetSimilarityPairwise_Neuron(neuronchat_list, slot.name = "net", type = "functional",comparison = c(1,2)) 85 | # manifold learning 86 | neuronchat_list <- netEmbedding(neuronchat_list,slot.name = "net_analysis", type = "functional",comparison = c(1,2)) 87 | # clustering on interactions 88 | neuronchat_list <- netClustering(neuronchat_list, slot.name = "net_analysis", type = "functional",comparison = c(1,2),k = 5) 89 | # visualization 90 | netVisual_embeddingPairwise_Neuron(neuronchat_list, slot.name = "net_analysis", type = "functional", label.size = 3.5,comparison=c(1,2),pathway.remove.show = FALSE,pathway.labeled = F) 91 | ``` 92 | 93 | ```{r fig31, fig.height = 7, fig.width = 12} 94 | # visualization zoom in 95 | netVisual_embeddingPairwiseZoomIn_Neuron(neuronchat_list, slot.name = "net_analysis", type = "functional", label.size = 5,comparison=c(1,2),nCol=3) 96 | ``` 97 | 98 | ```{r fig4, fig.height = 3.5, fig.width = 20} 99 | # heatmap for each interaction pattern 100 | net12 <- neuronchat_list@net[c(1,2)] 101 | net1 <- net12[[1]];names(net1) <- paste(names(net1),'--ALM',sep='') 102 | net2 <- net12[[2]];names(net2) <- paste(names(net2),'--VISp',sep='') 103 | net12_list <- append(net1,net2) 104 | interaction_group <- neuronchat_list@net_analysis$similarity$functional$group$`1-2` 105 | hlist <- list();gb_heatmap <- list() 106 | library(grid); library(ComplexHeatmap);grid.newpage(); x_seq <- c(0,0.2,0.4,0.6,0.8) 107 | for(j in 1:length(sort(unique(interaction_group),decreasing = F))){ 108 | net_aggregated_group2 <- net_aggregation(net12_list[names(interaction_group[interaction_group==j])],method = 'weight') 109 | library(RColorBrewer);col_map = brewer.pal(8,"YlOrBr"); 110 | h <- Heatmap(net_aggregated_group2, name = "Weight", 111 | col = col_map, 112 | cluster_rows = FALSE,cluster_columns=FALSE, 113 | row_names_side='left',column_names_side='bottom', 114 | row_title='Sender',row_title_side='left', 115 | row_title_gp = gpar(fontsize = 16), 116 | column_title='Receiver',column_title_side = "bottom",column_title_gp = gpar(fontsize = 16),column_names_rot = 60) 117 | gb_heatmap[[j]] = grid.grabExpr(draw(h,column_title=paste('pattern cluster',j), padding = unit(c(2, 2, 2, 2), "mm")) ) 118 | pushViewport(viewport(x = x_seq[j], y = 1, width = 0.19, height = 1, just = c("left", "top"),xscale = c(0, 1), yscale = c(0, 1)));grid.draw(gb_heatmap[[j]]);popViewport() 119 | } 120 | ``` 121 | 122 | --------------------------------------------------------------------------------