Skip to content

Commit b8cadfe

Browse files
committed
Try to reduce memory in seurat merge
1 parent bc41142 commit b8cadfe

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

singlecell/resources/chunks/MergeSeurat.R

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,29 +34,46 @@ if (length(seuratObjects) == 1) {
3434
} else {
3535
batchSize <- 20
3636
numBatches <- ceiling(length(seuratObjects) / batchSize)
37-
mergedObjects <- list()
37+
mergedObjectFiles <- list()
3838
for (i in 1:numBatches) {
3939
message(paste0('Merging batch ', i, ' of ', numBatches))
4040
start <- 1 + (i-1)*batchSize
4141
end <- min(start+batchSize-1, length(seuratObjects))
42-
print(paste0('processing: ', start, ' to ', end, ' of ', length(seuratObjects)))
42+
message(paste0('processing: ', start, ' to ', end, ' of ', length(seuratObjects)))
4343

44-
mergedObjects[[i]] <- mergeBatch(seuratObjects[start:end])
44+
fn <- paste0('mergeBatch.', i, '.rds')
45+
saveRDS(mergeBatch(seuratObjects[start:end]), file = fn)
46+
mergedObjectFiles[[i]] <- fn
47+
48+
print('mem used:')
49+
print(pryr::mem_used())
4550
gc()
4651
}
4752

4853
print('Done with batches')
49-
if (length(mergedObjects) == 1) {
50-
seuratObj <- mergedObjects[[1]]
54+
if (length(mergedObjectFiles) == 1) {
55+
seuratObj <- readRDS(mergedObjectFiles[[1]])
56+
unlink(mergedObjectFiles[[1]])
5157
} else {
5258
message('performing final merge')
53-
seuratObj <- merge(x = mergedObjects[[1]], y = mergedObjects[2:length(mergedObjects)], project = mergedObjects[[1]]@project.name)
54-
if (HasSplitLayers(seuratObj)) {
55-
seuratObj <- MergeSplitLayers(seuratObj)
59+
seuratObj <- readRDS(mergedObjectFiles[[1]])
60+
unlink(mergedObjectFiles[[1]])
61+
62+
for (i in 2:length(mergedObjectFiles)) {
63+
print(paste0('Merging final file ', i, ' of ', length(mergedObjectFiles)))
64+
seuratObj <- merge(x = seuratObj, y = readRDS(mergedObjectFiles[[i]]), project = seuratObj@project.name)
65+
if (HasSplitLayers(seuratObj)) {
66+
seuratObj <- MergeSplitLayers(seuratObj)
67+
}
68+
69+
unlink(mergedObjectFiles[[i]])
70+
71+
print('mem used:')
72+
print(pryr::mem_used())
73+
gc()
5674
}
5775
}
5876

59-
rm(mergedObjects)
6077
gc()
6178

6279
saveData(seuratObj, projectName)

0 commit comments

Comments
 (0)