Last active
August 18, 2024 09:07
-
-
Save slowkow/faf168c0b8dedbf337f424e07091437a to your computer and use it in GitHub Desktop.
UMAP on 30k cells with different values for min_dist and spread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(uwot) | |
library(scattermore) | |
library(foreach) | |
library(doParallel) | |
library(data.table) | |
library(ggplot2) | |
library(scales) | |
library(glue) | |
# This code snippet assumes we have these objects: | |
# | |
# pca | |
# A matrix with PCA scores, one column for each PC. | |
# | |
# nn_method | |
# A list with two matrices "idx" and "dist" | |
# Each matrix has nrow = cells, ncol = num neighbors | |
# idx has the ids of neighbor cells | |
# dist has euclidean distances to each neighbor cell | |
# | |
# obs | |
# A table with one row per cell, and a column called "cluster" | |
umap_params <- expand.grid( | |
spread = c(1, 2, 4, 8, 16, 24), | |
min_dist = c(0.01) | |
) | |
# Run 8 jobs in parallel | |
my_cluster <- parallel::makeCluster(8, type = "FORK") | |
doParallel::registerDoParallel(cl = my_cluster) | |
umaps <- foreach( | |
spread = umap_params$spread, | |
min_dist = umap_params$min_dist, | |
.packages = c("uwot", "Matrix") | |
) %dopar% { | |
uwot::umap( | |
X = NULL, | |
init = pca[,1:2], | |
nn_method = nn_method, | |
spread = spread, | |
min_dist = min_dist, | |
n_threads = 2 | |
) | |
} | |
parallel::stopCluster(cl = my_cluster) | |
d <- rbindlist(lapply(seq(nrow(umap_params)), function(i) { | |
data.table( | |
x = umaps[[i]][,1], | |
y = umaps[[i]][,2], | |
spread = umap_params$spread[i], | |
min_dist = umap_params$min_dist[i], | |
group = as.character(obs[["cluster"]]) | |
) | |
})) | |
p <- ggplot(d) + | |
geom_scattermore( | |
mapping = aes(x = x, y = y, color = group), | |
pointsize = 1, | |
pixels = c(1000, 1000) | |
) + | |
theme( | |
axis.text = element_blank(), | |
axis.ticks = element_blank(), | |
axis.title = element_blank(), | |
legend.position = "none" | |
) + | |
facet_wrap(~ spread, scales = "free") + | |
labs( | |
title = glue("{comma(nrow(umaps[[1]]))} cells in UMAP, adjusting spread") | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment