Closed weiyouzi321 closed 5 months ago
Thank you for taking the time to write your issue. Can you please provide the code that you used to create the Seurat object?
thank you for your attention! there two ways to build my own Seurat object;the object with which i encounter to error was built by first way,i will try whether the object built by second way can sovle this error first way is to use the transform code to trans .h5ad to rds and then use readRDS to get Seurat object
library(SeuratDisk)
library(Seurat)
library(ggplot2)
library(dplyr)
library(rjson)
library(argparser)
args <- arg_parser("Converting h5ad file(.h5ad) to RDS.")
args <- add_argument(args, "--infile", help = "input .h5ad file")
args <- add_argument(args, "--outfile", help = "output RDS file")
argv <- parse_args(args)
infile <- argv$infile
outfile <- argv$outfile
print("Converting h5ad to h5seurat file.")
Convert(infile, dest = "h5seurat",assay = "Spatial", overwrite = TRUE)
h5file<-paste(paste(unlist(strsplit(infile,"h5ad",fixed=TRUE)),collapse='h5ad'),"h5seurat",sep="")
print("Loading h5seurat file.")
Stdata <- LoadH5Seurat(h5file)
if(!is.null(Stdata@reductions$ignore)){
Stdata@reductions$ignore <- NULL
}
if(!is.null(Stdata@reductions$spatial)){
Stdata@reductions$spatial <- NULL
}
if(!is.null(Stdata@misc$raw_counts)){
if(!is.null(Stdata@misc$raw_genename)){
Stdata@misc$raw_counts@Dimnames[[1]] = Stdata@misc$raw_genename
Stdata@misc$raw_genename<-NULL
}
if(!is.null(Stdata@misc$raw_cellname)){
Stdata@misc$raw_counts@Dimnames[[2]] = Stdata@misc$raw_cellname
Stdata@misc$raw_cellname<-NULL
}
print("Adding misc raw_counts to Spatial assay as counts.")
Stdata@assays$Spatial@counts=Stdata@misc$raw_counts
if(dim(Stdata[['Spatial']]@scale.data)[1]>0){
print("Adding misc raw_counts to Spatial assay as data.")
Stdata@assays$Spatial@data=Stdata@misc$raw_counts
}
Stdata@misc$raw_counts<-NULL
}
if(!is.null(Stdata@misc$sct_data)){
print("Creating SCT assay.")
Stdata@assays$SCT=Stdata@assays$Spatial
Stdata@assays$SCT@data=Stdata@misc$sct_data
Stdata@misc$sct_data<-NULL
Stdata@assays$Spatial@scale.data=matrix(,nrow=10,ncol=0)
f_len<-length(Stdata@assays$SCT@meta.features)
if(f_len>0){
Stdata[['SCT']]@meta.features <- Stdata[['SCT']]@meta.features[,-(1:f_len)]
}
if(!is.null(Stdata@misc$sct_genename)){
print("Adding gene dimnames to SCT data.")
Stdata@assays$SCT@data@Dimnames[[1]] = Stdata@misc$sct_genename
}
if(!is.null(Stdata@misc$sct_cellname)){
print("Adding cell dimnames to SCT data.")
Stdata@assays$SCT@data@Dimnames[[2]] = Stdata@misc$sct_cellname
}
#Stdata@assays$SCT@data@Dimnames=Stdata@assays$Spatial@data@Dimnames
Stdata@assays$SCT@counts=Stdata@misc$sct_counts
Stdata@misc$sct_counts<-NULL
if(!is.null(Stdata@misc$sct_genename)){
print("Adding gene dimnames to SCT counts.")
Stdata@assays$SCT@counts@Dimnames[[1]] = Stdata@misc$sct_genename
}
if(!is.null(Stdata@misc$sct_cellname)){
print("Adding cell dimnames to SCT counts.")
Stdata@assays$SCT@counts@Dimnames[[2]] = Stdata@misc$sct_cellname
}
#Stdata@assays$SCT@counts@Dimnames=Stdata@assays$Spatial@counts@Dimnames
DefaultAssay(Stdata)<-"SCT"
Stdata@misc$sct_genename<-NULL
Stdata@misc$sct_cellname<-NULL
}
## add image
cell_coords=unique(Stdata@meta.data[, c('x', 'y')])
cell_coords['cell']=row.names(cell_coords)
cell_coords$x <- cell_coords$x - min(cell_coords$x) + 1
cell_coords$y <- cell_coords$y - min(cell_coords$y) + 1
# object of images$slice1@image, all illustrated as 1 since no concrete pic
tissue_lowres_image <- matrix(1, max(cell_coords$y), max(cell_coords$x))
# object of images$slice1@coordinates, concrete coordinate of X and Y
tissue_positions_list <- data.frame(row.names = cell_coords$cell,
tissue = 1,
row = cell_coords$y, col = cell_coords$x,
imagerow = cell_coords$y, imagecol = cell_coords$x)
##@images$slice1@scale.factors
scalefactors_json <- toJSON(list(fiducial_diameter_fullres = 1,tissue_hires_scalef = 1,tissue_lowres_scalef = 1))
# generate object @images$slice1
generate_BGI_spatial <- function(image, scale.factors, tissue.positions, filter.matrix = TRUE){
if (filter.matrix) {
tissue.positions <- tissue.positions[which(tissue.positions$tissue == 1), , drop = FALSE]
}
unnormalized.radius <- scale.factors$fiducial_diameter_fullres * scale.factors$tissue_lowres_scalef
spot.radius <- unnormalized.radius / max(dim(x = image))
return(new(Class = 'VisiumV1',
image = image,
scale.factors = scalefactors(spot = scale.factors$tissue_hires_scalef,
fiducial = scale.factors$fiducial_diameter_fullres,
hires = scale.factors$tissue_hires_scalef,
lowres = scale.factors$tissue_lowres_scalef),
coordinates = tissue.positions,
spot.radius = spot.radius))
}
BGI_spatial <- generate_BGI_spatial(image = tissue_lowres_image,
scale.factors = fromJSON(scalefactors_json),
tissue.positions = tissue_positions_list)
# can be thought of as a background of spatial
#' import image into seurat object
Stdata@images[['slice1']] <-BGI_spatial
Stdata@images$slice1@key<-"slice1_"
Stdata@images$slice1@assay<-"Spatial"
# conversion done, save
saveRDS(Stdata,outfile)
print("Finished RDS.")
another way is to read [.h5ad] by scanpy and built Seurat object from original matrix
library("reticulate")
unloadNamespace("ggplot2")
library("scater")
#library("Seurat")
Sys.setenv(RETICULATE_PYTHON="D:\\Anaconda3\\python.exe")
sc<-import("scanpy")
pd<-import("pandas")
adata <- sc$read_h5ad("D:\\HDMouse\\2023bin100\\cellbin\\Mouse_brain_cell_bin.h5ad")
adata <- sc$read_h5ad("E:\\Mouse_embroys\\data\\E16.5_E1S3_cell_bin_whole_brain.h5ad")
counts1 <- t(adata$layers["counts"])
colnames(counts1) <- adata$obs_names$to_list()
rownames(counts1) <- adata$var_names$to_list()
counts1 <- Matrix::Matrix(as.matrix(counts1), sparse = T)
seurat <- CreateSeuratObject(counts1)
seurat <- AddMetaData(seurat,adata$obsm['spatial'])
seurat <- AddMetaData(seurat,adata$uns['sim anno_colors'])
Based on this information it seems like this issue is outside of the scope of hdWGCNA since it has to do with the way that you have chosen to construct your Seurat object rather than to do with the behavior of hdWGCNA. Personally I have not had success with packages that try to convert betweeen scanpy/R formats like SeuratDisk for example.
Describe the bug Error in Matrix(from, sparse = TRUE, doDiag = FALSE) : invalid 'data'
exciting work!i have tried the example 10X data (sagittal brain section) it worked well and showed well reproducibility,so package installation and R enviroment may be approriate;but when trying hdWGCNA on my own project,i encounter error in MetaspotsByGroups()
Steps to reproduce i used another public spatial transcriptomic data,Stereoseq of a half brain section of adult mouse from MOSTA(Cell,2022),and here is the link https://db.cngb.org/stomics/mosta/download/ the seurat object was bulit manually so i suspect the error may be caused by the procedure of the seurat object. i will be appreciate any suggestion from you!
Screenshots
traceback 7: stop("invalid 'data'") 6: Matrix(from, sparse = TRUE, doDiag = FALSE) 5: asMethod(object) 4: as(agg_X, "sparseMatrix") 3: (function (cur_seurat, mode = "sum", assay = "Spatial", slot = "counts") { X <- GetAssayData(cur_seurat, slot = "counts") if (sum(unlist(lapply(Images(cur_seurat), function(x) { nrow(cur_seurat@images[[x]]@coordinates) != 0 }))) != 1) { stop("More than one sample present in grouping. Please specify a metadata column with group.by indicating different ST samples.") } row_range <- range(cur_seurat$row) col_range <- range(cur_seurat$col) col_bounds <- col_range[1]:col_range[2] if (length(col_bounds) >= 4) { col_bounds <- col_bounds[which(1:length(col_bounds)%%4 == 0)] } else if (length(col_bounds) == 3) { warning("The selected grouping is spatially constrained and might fail the metaspot aggregation step. You may wish to change the group.by parameter to form larger groups.") col_bounds <- col_bounds[2] } else if (length(col_bounds) >= 1) { ... 2: mapply(ConstructMetaspots, cur_seurat = seurat_list, MoreArgs = list(mode = mode, assay = assay, slot = slot)) 1: MetaspotsByGroups(seurat_obj, group.by = c("orig.ident"), ident.group = "orig.ident", assay = "Spatial", slot = "counts", min_spots = 30)