# PLS 206 Friday: parallel computing and big data in R
# Grey Monroe, Fall 2026

# install.packages(c("future.apply", "data.table", "cluster", "ggplot2"))
library(parallel)
library(future.apply)
library(data.table)
library(cluster)
library(ggplot2)

clim <- read.csv("https://greymonroe.github.io/PLS_206/data/colombia_climate.csv")
str(clim)   # 3571 grid cells in Colombia: lon, lat and 19 climate variables (bio1-bio19)


#### Step 1. Time it first ####

# system.time() runs a line of code and reports how long it took.
# "elapsed" is the wall-clock time you waited, in seconds.
system.time(Sys.sleep(2))

# Time each step of a small clustering analysis to find the slow one (the bottleneck)
system.time(clim_scaled <- scale(clim[, 3:21]))
system.time(d <- dist(clim_scaled))
system.time(km <- kmeans(clim_scaled, centers = 6, nstart = 100))
system.time(sil <- silhouette(km$cluster, d))
# kmeans() with 100 random starts is the slow step. That is the one worth speeding up.


#### Step 2. Vectorize before you parallelize ####

# Growing degree days: how far each day's mean temperature is above 10 C (0 if below)
set.seed(1)
temp <- rnorm(1e6, mean = 18, sd = 6)   # a million daily temperatures

# 1. for loop
system.time({
  gdd_loop <- numeric(length(temp))   # make the empty vector first, then fill it
  for (i in seq_along(temp)) {
    if (temp[i] > 10) gdd_loop[i] <- temp[i] - 10 else gdd_loop[i] <- 0
  }
})

# 2. sapply
system.time(gdd_sapply <- sapply(temp, function(t) if (t > 10) t - 10 else 0))

# 3. vectorized: one function call on the whole vector
system.time(gdd_vec <- pmax(temp - 10, 0))

all.equal(gdd_loop, gdd_vec)   # same answer
# The vectorized version is 25 to 70 times faster. No number of cores closes that gap.

# The classic slow loop: growing the answer with c() instead of making the empty vector first
temp_50k <- temp[1:50000]
system.time({
  gdd_grow <- c()
  for (t in temp_50k) gdd_grow <- c(gdd_grow, if (t > 10) t - 10 else 0)
})
# Seconds for just 50,000 values. Each c() copies the whole vector, so doubling the length
# makes it about 4 times slower.


#### Step 3. The apply family is the bridge to parallel ####

# One k-means fit plus its mean silhouette score, for a given number of clusters k
fit_k <- function(k) {
  km <- kmeans(clim_scaled, centers = k, nstart = 100)
  sil <- silhouette(km$cluster, dist(clim_scaled))
  mean(sil[, "sil_width"])
}

fit_k(3)

# Each k is a separate job that does not depend on the others: a perfect job for lapply()
# (we run it for real in Step 5)
# sil_scores <- lapply(2:12, fit_k)
# The parallel version is the same line with one word changed:
# sil_scores <- future_lapply(2:12, fit_k, future.seed = TRUE)


#### Step 4. Parallel on your laptop ####

detectCores()                  # how many cores this computer has
n_workers <- detectCores() - 1 # always leave one free for your computer
n_workers

# A task that just waits 1 second, so we can see the effect clearly
slow_task <- function(i) {
  Sys.sleep(1)
  i^2
}

# Serial: 8 tasks, one after the other
system.time(res_serial <- lapply(1:8, slow_task))

# Parallel: start the workers (separate R sessions in the background)
plan(multisession, workers = n_workers)
nbrOfWorkers()

system.time(res_parallel <- future_lapply(1:8, slow_task))
identical(res_serial, res_parallel)   # same answer, in the same order

# Random numbers in parallel: set the seed AND use future.seed = TRUE
set.seed(206)
boot_a <- future_sapply(1:5, function(i) mean(sample(clim$bio1, replace = TRUE)),
                        future.seed = TRUE)
set.seed(206)
boot_b <- future_sapply(1:5, function(i) mean(sample(clim$bio1, replace = TRUE)),
                        future.seed = TRUE)
identical(boot_a, boot_b)   # TRUE: reproducible

# mclapply() from the parallel package does the same job on Mac and Linux only (not Windows)
# res_mc <- mclapply(1:8, slow_task, mc.cores = n_workers)


#### Step 5. Choosing k for k-means, serial vs parallel ####

ks <- 2:12

# Serial
plan(sequential)
set.seed(206)
t_serial <- system.time(sil_serial <- future_sapply(ks, fit_k, future.seed = TRUE))
t_serial

# Parallel
plan(multisession, workers = n_workers)
set.seed(206)
t_parallel <- system.time(sil_parallel <- future_sapply(ks, fit_k, future.seed = TRUE))
t_parallel

t_serial["elapsed"] / t_parallel["elapsed"]   # the speed-up
all.equal(sil_serial, sil_parallel)           # same answers

# The result: mean silhouette width for each k (higher = better separated clusters)
sil_k <- data.frame(k = ks, silhouette = sil_parallel)
ggplot(sil_k, aes(x = k, y = silhouette)) +
  geom_line() +
  geom_point(size = 3) +
  scale_x_continuous(breaks = ks) +
  labs(x = "Number of clusters (k)", y = "Mean silhouette width") +
  theme_classic()

# Map the best k
best_k <- ks[which.max(sil_parallel)]
set.seed(206)
km_best <- kmeans(clim_scaled, centers = best_k, nstart = 100)
clim$cluster <- factor(km_best$cluster)
ggplot(clim, aes(x = lon, y = lat, fill = cluster)) +
  geom_tile() +
  coord_equal() +
  labs(x = "Longitude", y = "Latitude", fill = "Climate\ncluster") +
  theme_classic()


#### Step 6. Big data: read fast, keep only what you need ####

# Make a big file to practice on: 2 million rows of simulated field sensor data
set.seed(206)
n <- 2e6
sensors <- data.frame(
  plot     = sample(1:5000, n, replace = TRUE),
  site     = sample(c("Davis", "Winters", "Dixon", "Woodland", "Esparto"), n, replace = TRUE),
  date     = as.Date("2021-01-01") + sample(0:1460, n, replace = TRUE),
  temp_c   = round(rnorm(n, 18, 6), 2),
  rain_mm  = round(rexp(n, 1 / 3), 2),
  soil_vwc = round(runif(n, 0.05, 0.45), 3),
  ndvi     = round(runif(n, 0.1, 0.9), 3),
  yield_t  = round(rnorm(n, 8, 1.5), 2)
)
big_file <- file.path(tempdir(), "sensors.csv")
fwrite(sensors, big_file)
file.size(big_file) / 1e6   # size on disk, in MB
rm(sensors)

# read.csv() vs fread()
system.time(big_base <- read.csv(big_file))
system.time(big_dt <- fread(big_file))

# How much memory does it take?
format(object.size(big_dt), units = "MB")

# Keep only the columns you need
system.time(big_small <- fread(big_file, select = c("site", "temp_c", "yield_t")))
format(object.size(big_small), units = "MB")

# Look at the first rows before reading everything
fread(big_file, nrows = 5)

# Work out your code on a random sample, then run it on everything
set.seed(206)
big_sample <- big_dt[sample(.N, 10000)]
big_sample[, .(mean_yield = mean(yield_t)), by = site]

# Summaries by group: base R vs data.table
system.time(aggregate(yield_t ~ site, data = big_base, FUN = mean))
system.time(big_dt[, .(mean_yield = mean(yield_t)), by = site])

# Free the memory when you are done
rm(big_base, big_dt, big_small, big_sample)
invisible(gc())


#### Step 7. When your laptop isn't enough ####

# On a computing cluster, each k can be its own job (a Slurm job array).
# The R script reads which k to fit from the job's task number:
# k <- as.integer(commandArgs(trailingOnly = TRUE)[1])
# result <- fit_k(k)
# saveRDS(result, paste0("sil_k", k, ".rds"))

plan(sequential)   # shut down the background workers
