Skip to content

Optimize abundance calculation #60

Open

Description

@rguliev

Current implementation of NNLS abundance inversion applies NNLS one by one to each spectrum.
Seems, like this can be significantly optimized. At least, to run in parallel.
I have tried different options. On small/medium size matrices, current default seems to be the best. On larger matrices (50k in this case), using parallel:mclapply allowed to use all cores and resulted in significant speedup.
However, parallel:mclapply crushes the session. At least for me when I try it on a larger dataset (600k+ rows).
So, I'm not sure what is the good way now.

library(future.apply)
library(pracma)

loop_nnls <- function(A,B) {
  res <- matrix(NA_real_, nrow(B), nrow(A))
  for (i in seq_len(nrow(B))) {
    res[i, ] <- nnls::nnls(t(A), B[i, ])[["x"]]
  }
  return(res)
}
mc_nnls <- function(A, B) {
  res <- parallel::mclapply(1:nrow(B), function(i) {
    nnls::nnls(t(A), B[i, ])$x
  }, mc.cores = ncores)
  do.call(rbind, res)
}

a = as.matrix(ems)
b = as.matrix(spc)
subb <- b[sample(nrow(b),50000),]
ncores <- parallel::detectCores()
plan(multisession, workers = ncores)

res <- bench::mark(
  "default" = t(apply(subb, 1, function(x) {nnls::nnls(t(a), x)[["x"]]})),
  "pracma" = t(apply(subb, 1, function(x) {lsqnonneg(t(a), x)[["x"]]})),
  "future_apply" = t(future_apply(subb, 1, function(x) {nnls::nnls(t(a), x)[["x"]]})),
  "loop" = loop_nnls(a,subb),
  "mc_nnls" = mc_nnls(a, subb),
  check = FALSE,
  filter_gc = TRUE,
  min_iterations = 5,
  memory = FALSE
)
print(res)

# For 5k rows
# # A tibble: 5 × 13
#   expression        min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time
# 1 default         1.28s     1.3s    0.716      1.2GB   0          5     0      6.98s
# 2 pracma          3.97s    4.19s    0.239     9.49GB   0.859      5    18     20.94s
# 3 future_apply   12.96s   13.15s    0.0752  296.89MB   0.0903     5     6      1.11m
# 4 loop            1.27s    1.27s    0.764     1.19GB   0.153      5     1      6.54s
# 5 mc_nnls         3.42s    3.51s    0.286        NA        0      5     0      17.5s 


# For 50k rows
# A tibble: 2 × 13
#   expression      min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time
# 1 default      12.98s   13.17s    0.0743        NA   0.0892     5     6      1.12m
# 2 mc_nnls       4.89s    4.99s    0.201         NA   0          5     0     24.82s

Activity

  1. rguliev commented on Mar 2, 2026

    @rguliev
    CollaboratorAuthor

    Another helpful package to consider: mirai

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions