Skip to content
This repository has been archived by the owner on Jan 24, 2024. It is now read-only.

Error in base::colSums(x, na.rm = na.rm, dims = dims, ...) : 'x' must be an array of at least two dimensions #747

Open
yueli8 opened this issue Jan 17, 2024 · 5 comments

Comments

@yueli8
Copy link

yueli8 commented Jan 17, 2024

Hello,

Thank you for developing so nice software!

Thank you in advance for great help!

Best,

Yue

> cellchat <- computeNetSimilarityPairwise(cellchat, type = "functional")
Compute signaling network similarity for datasets 1 2 
> cellchat <- netEmbedding(cellchat, type = "functional") 
Manifold learning of the signaling networks for datasets 1 2 
> cellchat <- netEmbedding(cellchat, umap.method="uwot",type = "functional") 
Manifold learning of the signaling networks for datasets 1 2 
Found more than one class "dist" in cache; using the first, from namespace 'BiocGenerics'
Also defined by ‘spam’
Found more than one class "dist" in cache; using the first, from namespace 'BiocGenerics'
Also defined by ‘spam’
> cellchat <- netEmbedding(cellchat, umap.method="umap-learn",type = "functional")
Manifold learning of the signaling networks for datasets 1 2 
> cellchat <- netClustering(cellchat, method="umap-learn", type = "functional")
Classification learning of the signaling networks for datasets 1 2 
> cellchat <- netClustering(cellchat, method="uwot", type = "functional")
Classification learning of the signaling networks for datasets 1 2 
> netVisual_embedding(cellchat, type = "functional", label.size = 3.5)
Error in base::colSums(x, na.rm = na.rm, dims = dims, ...) : 
  'x' must be an array of at least two dimensions
`
@maciejmotyka
Copy link

maciejmotyka commented Jan 19, 2024

I have somewhat similar issue.
netVisual_embeddingPairwise(cc_obj, type = "functional") works fine, but there ~700 pathways clustered very tightly so the labels don't show.
I tried to zoom in using netVisual_embeddingZoomIn(cc_obj, type = "functional") and then I get the same error as @yueli8

Here's a traceback:

Error in base::colSums(x, na.rm = na.rm, dims = dims, ...) :
  'x' must be an array of at least two dimensions
    6. stop("'x' must be an array of at least two dimensions")
    5. base::colSums(x, na.rm = na.rm, dims = dims, ...)
    4. colSums(similarity)
    3. colSums(similarity)
    2. which(colSums(similarity) == 1)
    1. netVisual_embeddingZoomIn(cc_obj, type = "functional")

I traced it to those lines:

CellChat/R/visualization.R

Lines 3474 to 3475 in e4f6862

comparison <- "single"
comparison.name <- paste(comparison, collapse = "-")

and a bit further:

CellChat/R/visualization.R

Lines 3479 to 3482 in e4f6862

if (is.null(pathway.remove)) {
similarity <- methods::slot(object, slot.name)$similarity[[type]]$matrix[[comparison.name]]
pathway.remove <- rownames(similarity)[which(colSums(similarity) == 1)]
}

So it's looking for comparison.name = "single", but there is none, so it returns similarity = NULL.
My merged object consists of 3 datasets and the comparison is called 1-2-3.

> names(cc_obj@netP[["similarity"]][["functional"]][["matrix"]])
[1] "1-2-3"

@yueli8
Copy link
Author

yueli8 commented Jan 22, 2024

@maciejmotyka

Hello maciejmotyka,

Thank you!

#install.packages('devtools')
#devtools::install_github("jinworks/CellChat")
library(CellChat)
library(tidyverse)
library(ggalluvial)
#install.packages("anndata")
library(anndata)
library(anndata)
library(Seurat)
library(patchwork)
library(uwot)
library(reticulate)
library(glmGamPoi)
library(umap)
library(ComplexHeatmap)
#install.packages('NMF')
library(NMF)
library(dplyr)
library(SeuratData)
library(ggplot2)
library(svglite)
library(wordcloud)
library(wordcloud2)
library(tm)
#devtools::install_github("jokergoo/circlize")
library(circlize)
#devtools::install_github("jokergoo/ComplexHeatmap")

#source('functional.R')#千萬不要加上
setwd("~/cellchat")
rm(list=ls()) #清空所有变量
options(stringsAsFactors = FALSE)#输入数据不自动转换成因子(防止数据格式错误)

#(A) Starting from a count data matrix
load("data_humanSkin_CellChat.rda")
data.input = data_humanSkin$data
meta = data_humanSkin$meta
cell.use = rownames(meta)[meta$condition == "LS"] # extract the c
data.input = data.input[, cell.use]
meta = meta[cell.use, ]

#(B) Starting from a Seurat object
#data.input <- GetAssayData(seurat_object, assay = "RNA", slot = "data") # normalized data matrix
#labels <- Idents(seurat_object)
#meta <- data.frame(group = labels, row.names = names(labels)) # create a dataframe of the cell labels

#(C) Starting from a SingleCellExperiment object
#data.input <- SingleCellExperiment::logcounts(object) # normalized data matrix
#meta <- as.data.frame(SingleCellExperiment::colData(object)) # extract a dataframe of the cell labels
#meta$labels <- meta[["sce.clusters"]]

#(D) Starting from an Anndata object
# read the data into R using anndata R package
#ad <- read_h5ad("scanpy_object.h5ad")# access count data matrix
#counts <- t(as.matrix(ad$X)) # normalize the count data if the normalized data is not available in the .h5ad file
#library.size <- Matrix::colSums(counts)
#data.input <- as(log1p(Matrix::t(Matrix::t(counts)/library.size)* 10000), "dgCMatrix")
#meta <- ad$obs# access meta data
#meta$labels <- meta[["clusters"]]


#2.Create a CellChat object by following option
#(A) Starting from the digital gene expression matrix and cell label information
cellchat <- createCellChat(object = data.input, meta = meta, group.by = "labels")
# [1] "Create a CellChat object from a data matrix"
# Set cell identities for the new CellChat object
# The cell groups used for CellChat analysis are  APOE+ FIB FBN1+ FIB COL11A1+ FIB Inflam. FIB cDC1 cDC2 LC Inflam. DC TC Inflam. TC CD40LG+ TC NKT
#(B) Starting from a Seurat object
#cellChat <- createCellChat(object = seurat.obj, group.by = "ident", assay = "RNA")
#(C) Starting from a SingleCellExperiment object
#cellChat <- createCellChat(object = sce.obj, group.by = "sce.clusters")
#(D) Starting from an AnnData object
#sce <- zellkonverter::readH5AD(file = "adata.h5ad") # retrieve all the available assays within sce object assayNames(sce)
# add a new assay entry "logcounts" if not available
#counts <- assay(sce, "X") # make sure this is the original count data matrix
#library.size <- Matrix::colSums(counts)
#logcounts(sce) <- log1p(Matrix::t(Matrix::t(counts)/library.size) * 10000)
# extract a cell meta data
#meta <- as.data.frame(SingleCellExperiment::colData(sce)) #
#cellChat <- createCellChat(object = sce, group.by = "sce.clusters")


CellChatDB <- CellChatDB.human
showDatabaseCategory(CellChatDB)
# Show the structure of the database
dplyr::glimpse(CellChatDB$interaction)
# use a subset of CellChatDB for cell-cell communication analysis
CellChatDB.use <- subsetDB(CellChatDB, search = "Secreted Signaling")# use Secreted Signaling
CellChatDB.use <- CellChatDB # simply use the default CellChatDB to use all CellChatDB for cell-cell communication analysis
# set the used database in the object
cellchat@DB <- CellChatDB.use

cellchat <- subsetData(cellchat) # This step is necessary even if using the whole database
future::plan("multisession", workers = 4) # do parallel
cellchat <- identifyOverExpressedGenes(cellchat)
cellchat <- identifyOverExpressedInteractions(cellchat)
#Inference of cell-cell communication network
cellchat <- computeCommunProb(cellchat, type = "triMean")
#triMean is used for calculating the average gene expression per cell group.
#[1] ">>> Run CellChat on sc/snRNA-seq data <<< [2023-12-15 12:49:11.48819]"
#|=============================================================================================================| 100%
#[1] ">>> CellChat inference is done. Parameter values are stored in `object@options$parameter` <<< [2023-12-15 12:51:34.162272]"
cellchat <- filterCommunication(cellchat, min.cells = 10)
cellchat <- computeCommunProbPathway(cellchat)
cellchat <- aggregateNet(cellchat)
saveRDS(cellchat, file = "cellchat_humanSkin_LS.rds")

#Visualization of cell-cell communication network
#(A) Circle plot ## Access all the signaling pathways showing significant communications
pathways.show.all <- cellchat@netP$pathways
# select one pathway
pathways.show <- c("CXCL")
par(mfrow=c(1,1))
netVisual_aggregate(cellchat, signaling = pathways.show, layout = "circle", color.use = NULL, sources.use = NULL, targets.use = NULL, idents.use = NULL)
#(B) Hierarchy plot
vertex.receiver = seq(1,4)
netVisual_aggregate(cellchat, signaling = pathways.show, layout ="hierarchy", vertex.receiver = vertex.receiver)
#(C) Chord diagram
par(mfrow=c(1,1))
netVisual_aggregate(cellchat, signaling = pathways.show, layout ="chord")
par(mfrow=c(1,1))
group.cellType <- c(rep("FIB", 4), rep("DC", 4), rep("TC", 4)) #grouping cell clusters into fibroblast, DC and TC cells
names(group.cellType) <- levels(cellchat@idents)
netVisual_chord_cell(cellchat, signaling = pathways.show, group =group.cellType, title.name = paste0(pathways.show, " signaling network"))
#(D) Heatmap plot
par(mfrow=c(1,1))
netVisual_heatmap(cellchat, signaling = pathways.show, color.heatmap = "Reds")

netAnalysis_contribution(cellchat, signaling = pathways.show)
pairLR.CXCL <- extractEnrichedLR(cellchat, signaling = pathways.show, geneLR.return = FALSE)
LR.show <- pairLR.CXCL[1,]
netVisual_individual(cellchat, signaling = pathways.show, pairLR.use = LR.show, layout = "circle")

#(A) Bubble plot
# (1) show all the significant interactions (L-R pairs) from some cell groups (defined by 'sources.use') to other cell groups (defined by 'targets.use')
netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), remove.isolate = FALSE)
# (2) show all the significant interactions (L-R pairs) associated with certain signaling pathways
netVisual_bubble(cellchat, sources.use = 4, targets.use = c(5:11), signaling = c("CCL","CXCL"), remove.isolate = FALSE)
## (3) show all the significant interactions (L-R pairs) based on user's input (defined by `pairLR.use`)
pairLR.use <- extractEnrichedLR(cellchat, signaling = c("CCL","CXCL","FGF"))
netVisual_bubble(cellchat, sources.use = c(3,4), targets.use = c(5:8), pairLR.use = pairLR.use, remove.isolate = TRUE)
# set the order of interacting cell pairs on x-axis
# (4) Default: first sort cell pairs based on the appearance of sources in levels(object@idents), and then based on the appearance of targets in levels(object@idents)
# (5) sort cell pairs based on the targets.use defined by users
netVisual_bubble(cellchat, targets.use = c("LC","Inflam. DC","cDC2","CD40LG+ TC"), pairLR.use = pairLR.use,
                 remove.isolate = TRUE, sort.by.target = T)
# (6) sort cell pairs based on the sources.use defined by users
netVisual_bubble(cellchat, sources.use = c("FBN1+ FIB","APOE+ FIB","Inflam. FIB"),
                 pairLR.use = pairLR.use, remove.isolate = TRUE,sort.by.source = T)
# (7) sort cell pairs based on the sources.use and then targets.use defined by users
netVisual_bubble(cellchat, sources.use = c("FBN1+ FIB","APOE+ FIB","Inflam. FIB"), targets.use = c("LC","Inflam. DC","cDC2","CD40LG+ TC"), pairLR.use = pairLR.use, remove.isolate = TRUE,
                 sort.by.source = T, sort.by.target = T)
# (8) sort cell pairs based on the targets.use and then sources.use defined by users
netVisual_bubble(cellchat, sources.use = c("FBN1+ FIB","APOE+ FIB","Inflam. FIB"), targets.use = c("LC","Inflam. DC","cDC2","CD40LG+ TC"),
                 pairLR.use = pairLR.use, remove.isolate = TRUE, sort.by.source = T, sort.by.target = T, sort.by.source.priority = FALSE)

#(B) Chord diagram
# show all the significant interactions (L-R pairs) from some cell groups (defined by 'sources.use') to other cell groups (defined by 'targets.use')
# show all the interactions sending from Inflam.FIB
netVisual_chord_gene(cellchat, sources.use = 4, targets.use = c(5:11), lab.cex = 0.5,legend.pos.y = 30)
# show all the interactions received by Inflam.DC
netVisual_chord_gene(cellchat, sources.use = c(1,2,3,4), targets.use = 8, legend.pos.x = 15)
# show all the significant interactions (L-R pairs) associated with certain signaling pathways
netVisual_chord_gene(cellchat, sources.use = c(1,2,3,4), targets.use = c(5:11), signaling = c("CCL","CXCL"),legend.pos.x = 8)
# show all the significant signaling pathways from some cell groups (defined by 'sources.use') to other cell groups (defined by 'targets.use')
netVisual_chord_gene(cellchat, sources.use = c(1,2,3,4), targets.use = c(5:11), slot.name = "netP", legend.pos.x = 10)
plotGeneExpression(cellchat, signaling = "CXCL", enriched.only =TRUE)

#(A)Compute and visualize the network centrality scores
cellchat <- netAnalysis_computeCentrality(cellchat, slot.name = "netP")# the slot 'netP' means the inferred intercellular communication network of signaling pathways
# Visualize the computed centrality scores using heatmap, allowing ready identification of major signaling roles of cell groupsnetAnalysis_signalingRole_network(cellchat, signaling = pathways.show, width = 8, height = 2.5, font.size = 10)
netAnalysis_signalingRole_network(cellchat, signaling = pathways.show, width = 8, height = 2.5, font.size = 10)
#(B) Visualize dominant senders (sources) and receivers (targets) in a 2D space
netAnalysis_signalingRole_scatter(cellchat, signaling = NULL)
#(C) Identify signals contributing the most to outgoing or incoming signaling of certain cell groups
ht1 <- netAnalysis_signalingRole_heatmap(cellchat, pattern = "outgoing")
ht2 <- netAnalysis_signalingRole_heatmap(cellchat, pattern = "incoming")
ht1 + ht2

#(A) Identify and visualize outgoing communication pattern of secreting cells
# infer the number of patterns.
selectK(cellchat, pattern ="outgoing")
# Both Cophenetic and Silhouette values begin to drop suddenly when the number of outgoing patterns is 3.
nPatterns = 3
cellchat <- identifyCommunicationPatterns(cellchat, pattern ="outgoing", k = nPatterns)
netAnalysis_river(cellchat, pattern ="outgoing")# river plot
netAnalysis_dot(cellchat, pattern ="outgoing")# dot plot

#(B) Identify and visualize incoming communication pattern of target cells
selectK(cellchat, pattern = "incoming")
nPatterns = 4
cellchat <- identifyCommunicationPatterns(cellchat, pattern = "incoming", k = nPatterns)
netAnalysis_river(cellchat, pattern = "incoming")# river plot
netAnalysis_dot(cellchat, pattern = "incoming")# dot plot

#(A) Functional similarity
cellchat <- computeNetSimilarity(cellchat, type = "functional")
cellchat <- netEmbedding(cellchat, type = "functional")#install through "pip install umap-learn"
#或者下面三條命令都可以運行
#cellchat <- netEmbedding(cellchat, umap.method='uwot',type ="functional")
#cellchat <- netEmbedding(cellchat, umap.method='umap-learn',type ="functional")
cellchat <- netClustering(cellchat, type = "functional",do.parallel=FALSE)#加上"do.parallel=FALSE"
netVisual_embedding(cellchat, type = "functional", label.size =3.5)
netVisual_embeddingZoomIn(cellchat, type = "functional", nCol = 2)

@yueli8
Copy link
Author

yueli8 commented Jan 22, 2024 via email

@yueli8
Copy link
Author

yueli8 commented Jan 22, 2024

@maciejmotyka

Try:

netVisual_embeddingPairwiseZoomIn

@yueli8
Copy link
Author

yueli8 commented Jan 22, 2024 via email

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants