Skip to content

Instantly share code, notes, and snippets.

@slowkow
Last active June 27, 2022 20:09
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save slowkow/faf168c0b8dedbf337f424e07091437a to your computer and use it in GitHub Desktop.
Save slowkow/faf168c0b8dedbf337f424e07091437a to your computer and use it in GitHub Desktop.
UMAP on 30k cells with different values for min_dist and spread
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")
)
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment