Last updated: 2022-03-25

Checks: 7 0

Knit directory: scFLASH/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20181103) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 1611b1a. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .DS_Store
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    code/initialization/
    Ignored:    data-raw/10x_assigned_cell_types.R
    Ignored:    data/.DS_Store
    Ignored:    data/10x/
    Ignored:    data/Ensembl2Reactome.txt
    Ignored:    data/droplet.rds
    Ignored:    data/mus_pathways.rds
    Ignored:    output/backfit/
    Ignored:    output/final_montoro/
    Ignored:    output/lowrank/
    Ignored:    output/prior_type/
    Ignored:    output/pseudocount/
    Ignored:    output/pseudocount_redux/
    Ignored:    output/size_factors/
    Ignored:    output/var_reg/
    Ignored:    output/var_type/

Untracked files:
    Untracked:  analysis/NBapprox.Rmd
    Untracked:  analysis/final_pbmc.Rmd
    Untracked:  analysis/trachea4.Rmd
    Untracked:  code/alt_montoro/
    Untracked:  code/final_pbmc/
    Untracked:  code/missing_data.R
    Untracked:  code/prior_type/priortype_fits_pbmc.R
    Untracked:  code/pseudocount_redux/pseudocount_fits_pbmc.R
    Untracked:  code/pulseseq/
    Untracked:  code/size_factors/sizefactor_fits_pbmc.R
    Untracked:  code/trachea4.R
    Untracked:  mixsqp_fail.rds
    Untracked:  output/alt_montoro/
    Untracked:  output/deng/
    Untracked:  output/final_pbmc/
    Untracked:  output/pulseseq_fit.rds
    Untracked:  tmp.txt

Unstaged changes:
    Modified:   code/deng/deng.R
    Modified:   code/utils.R
    Modified:   data-raw/pbmc.R

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/snmf_on_nmf.Rmd) and HTML (docs/snmf_on_nmf.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
Rmd 1611b1a Jason Willwerscheid 2022-03-25 wflow_publish(“./analysis/snmf_on_nmf.Rmd”)
html 12703e1 Jason Willwerscheid 2022-03-25 Build site.
Rmd 73c4bb2 Jason Willwerscheid 2022-03-25 wflow_publish(“./analysis/snmf_on_nmf.Rmd”)
html cbf2aff Jason Willwerscheid 2022-03-24 Build site.
Rmd 8e15872 Jason Willwerscheid 2022-03-24 wflow_publish(“./analysis/snmf_on_nmf.Rmd”)

library(flashier)
#> Loading required package: magrittr
library(tidyverse)
#> ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.1 ──
#> ✓ ggplot2 3.3.5     ✓ purrr   0.3.4
#> ✓ tibble  3.1.6     ✓ dplyr   1.0.8
#> ✓ tidyr   1.2.0     ✓ stringr 1.4.0
#> ✓ readr   2.0.0     ✓ forcats 0.5.1
#> ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
#> x tidyr::extract()   masks magrittr::extract()
#> x dplyr::filter()    masks stats::filter()
#> x dplyr::lag()       masks stats::lag()
#> x purrr::set_names() masks magrittr::set_names()

sim_data <- function(n = 100, 
                     p = 200, 
                     K = 6, 
                     L.nn = 10, 
                     F.nn = 20, 
                     se = 0.1, 
                     K.dense = 1, 
                     seed = 666) {
  set.seed(seed)
  
  LL <- matrix(rexp(n * K), nrow = n, ncol = K)
  FF <- matrix(rexp(p * K), nrow = p, ncol = K)
  
  # "Mean" factor.
  LL[, 1] <- 3
  
  # Additional sparse nonnegative factors.
  for (k in (K.dense + 1):K) {
    L.nn.idx <- seq((k - K.dense - 1) * L.nn + 1, (k - K.dense) * L.nn)
    F.nn.idx <- seq((k - K.dense - 1) * (F.nn / 2) + 1, (k + K.dense) * (F.nn / 2))
    LL[setdiff(1:n, L.nn.idx), k] <- 0
    FF[setdiff(1:p, F.nn.idx), k] <- 0
  }
  
  # Add normal noise.
  Y <- LL %*% t(FF) + rnorm(n * p, sd = se)
  
  # Add a constant (which can be absorbed by mean factor) to ensure nonnegativity.
  Y <- Y - min(Y)
  
  return(list(LL = LL, FF = FF, Y = Y))
}

plot_it <- function(simdat, nnmf_res, snmf_res) {
  LL <- simdat$LL

  to_tibble <- function(mat, type) {
    mat <- scale(mat, center = FALSE, scale = apply(mat, 2, function(x) max(abs(x))))
    return(
      as_tibble(mat, .name_repair = "unique") %>%
        mutate(row = row_number()) %>%
        pivot_longer(!row, names_to = "k", values_to = "value") %>%
        add_column(type = type)     
    )
  }
  
  
  suppressMessages({
    tib <- to_tibble(simdat$LL, "True loadings") %>%
      bind_rows(to_tibble(simdat$FF, "True factors")) %>%
      bind_rows(to_tibble(snmf_res$L.pm, "SNMF loadings")) %>%
      bind_rows(to_tibble(snmf_res$F.pm, "SNMF factors")) 
    if (inherits(nnmf_res, "flash")) {
      tib <- tib %>%
        bind_rows(to_tibble(nnmf_res$L.pm, "NMF loadings")) %>%
        bind_rows(to_tibble(nnmf_res$F.pm, "NMF factors")) 
    } else {
      tib <- tib %>%
        bind_rows(to_tibble(nnmf_res$W, "NMF loadings")) %>%
        bind_rows(to_tibble(t(nnmf_res$H), "NMF factors")) 
    }
    tib <- tib %>%
      mutate(k = as.numeric(str_remove_all(k, "\\."))) %>%
      mutate(type = factor(type, levels = c(
        "True loadings", "NMF loadings", "SNMF loadings",
        "True factors", "NMF factors", "SNMF factors"
      )))
  })
  
  ggplot(tib, aes(x = k, y = row, fill = value)) +
    geom_tile() +
    scale_fill_gradient2() +
    facet_wrap(~type, nrow = 2, ncol = 3, dir = "h", scales = "free") +
    theme_void()
 }

I simulate data \[ Y = LF' + E \] where both \(L\) and \(F\) are nonnegative and \(E\) is Gaussian noise. For details, refer to the code above. I refer to this model as the NMF model. I then fit an NMF using NNLM with the correct number of factors, as well as semi-nonnegative EBMF using flashier with the correct number of factors:

sim1 <- sim_data(K = 6)

# Use true value of K.
nnmf_res1 <- NNLM::nnmf(sim1$Y, k = 6, verbose = 0)
snmf_res1 <- flash.init(sim1$Y) %>%
  flash.set.verbose(0) %>%
  flash.add.greedy(
    Kmax = 6,
    ebnm.fn = c(ebnm::ebnm_point_normal, ebnm::ebnm_point_exponential),
    init.fn = function(fl) init.fn.default(fl, dim.signs = c(0, 1))
  ) %>%
  flash.backfit() %>%
  flash.nullcheck()

plot_it(sim1, nnmf_res1, snmf_res1)

Version Author Date
12703e1 Jason Willwerscheid 2022-03-25
cbf2aff Jason Willwerscheid 2022-03-24

Not only is SNMF basically nonnegative, but it does a better job recovering the true factors than NMF!

Next I fit NMF and SNMF using more factors than necessary:

nnmf_res1b <- NNLM::nnmf(sim1$Y, k = 10, verbose = 0)
snmf_res1b <- flash.init(sim1$Y) %>%
  flash.set.verbose(0) %>%
  flash.add.greedy(
    Kmax = 10,
    ebnm.fn = c(ebnm::ebnm_point_normal, ebnm::ebnm_point_exponential),
    init.fn = function(fl) init.fn.default(fl, dim.signs = c(0, 1))
  ) %>%
  flash.backfit() %>%
  flash.nullcheck()

plot_it(sim1, nnmf_res1b, snmf_res1b)

Version Author Date
12703e1 Jason Willwerscheid 2022-03-25
cbf2aff Jason Willwerscheid 2022-03-24

SNMF (almost) recovers the correct number of factors, which NMF is of course unable to do. Interestingly, however, if I use EBMF to fit NMF, I get approximately the same fit as SNMF:

nnmf_res1c <- flash.init(sim1$Y) %>%
  flash.set.verbose(0) %>%
  flash.add.greedy(
    Kmax = 10,
    ebnm.fn = ebnm::ebnm_point_exponential,
    init.fn = function(fl) init.fn.default(fl, dim.signs = c(1, 1))
  ) %>%
  flash.backfit() %>%
  flash.nullcheck()
#> Warning in scale.EF(EF): Fitting stopped after the initialization function
#> failed to find a non-zero factor.

plot_it(sim1, nnmf_res1c, snmf_res1b)

Version Author Date
12703e1 Jason Willwerscheid 2022-03-25

Finally I make the simulation scenario a bit more difficult (more noise, less sparsity, additional dense factors) and try again with the correct number of factors:

sim2 <- sim_data(K = 8, se = 1, L.nn = 20, F.nn = 40, K.dense = 3)

nnmf_res2 <- NNLM::nnmf(sim2$Y, k = 8, verbose = 0)
snmf_res2 <- flash.init(sim2$Y) %>%
  flash.set.verbose(0) %>%
  flash.add.greedy(
    Kmax = 8,
    ebnm.fn = c(ebnm::ebnm_point_normal, ebnm::ebnm_point_exponential),
    init.fn = function(fl) init.fn.default(fl, dim.signs = c(0, 1))
  ) %>%
  flash.backfit() %>%
  flash.nullcheck()

plot_it(sim2, nnmf_res2, snmf_res2)

Version Author Date
12703e1 Jason Willwerscheid 2022-03-25
cbf2aff Jason Willwerscheid 2022-03-24

SNMF again does quite a bit better on the sparse factors, but the dense factors now show a mixture of positive and negative loadings.

I try this more complex scenario again but use EBMF to fit NMF:

nnmf_res2b <- flash.init(sim2$Y) %>%
  flash.set.verbose(0) %>%
  flash.add.greedy(
    Kmax = 8,
    ebnm.fn = ebnm::ebnm_point_exponential,
    init.fn = function(fl) init.fn.default(fl, dim.signs = c(1, 1))
  ) %>%
  flash.backfit() %>%
  flash.nullcheck()

plot_it(sim2, nnmf_res2b, snmf_res2)


sessionInfo()
#> R version 3.5.3 (2019-03-11)
#> Platform: x86_64-apple-darwin15.6.0 (64-bit)
#> Running under: macOS Mojave 10.14.6
#> 
#> Matrix products: default
#> BLAS: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
#> LAPACK: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRlapack.dylib
#> 
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#>  [1] forcats_0.5.1   stringr_1.4.0   dplyr_1.0.8     purrr_0.3.4    
#>  [5] readr_2.0.0     tidyr_1.2.0     tibble_3.1.6    ggplot2_3.3.5  
#>  [9] tidyverse_1.3.1 flashier_0.2.27 magrittr_2.0.2  workflowr_1.6.2
#> 
#> loaded via a namespace (and not attached):
#>  [1] fs_1.5.0          lubridate_1.7.10  httr_1.4.2        rprojroot_2.0.2  
#>  [5] tools_3.5.3       backports_1.1.3   bslib_0.3.1       utf8_1.2.2       
#>  [9] R6_2.5.1          irlba_2.3.3       DBI_1.0.0         colorspace_2.0-3 
#> [13] withr_2.5.0       tidyselect_1.1.2  compiler_3.5.3    git2r_0.28.0     
#> [17] cli_3.2.0         rvest_1.0.0       xml2_1.3.2        labeling_0.4.2   
#> [21] horseshoe_0.2.0   sass_0.4.0        scales_1.1.1      SQUAREM_2021.1   
#> [25] mixsqp_0.3-43     digest_0.6.29     rmarkdown_2.11    deconvolveR_1.2-1
#> [29] pkgconfig_2.0.3   htmltools_0.5.2   highr_0.9         dbplyr_2.1.1     
#> [33] fastmap_1.1.0     invgamma_1.1      rlang_1.0.2       readxl_1.3.1     
#> [37] rstudioapi_0.13   jquerylib_0.1.4   generics_0.1.2    farver_2.1.0     
#> [41] jsonlite_1.8.0    Matrix_1.3-4      Rcpp_1.0.8        munsell_0.5.0    
#> [45] fansi_1.0.2       lifecycle_1.0.1   stringi_1.4.6     whisker_0.3-2    
#> [49] yaml_2.3.5        grid_3.5.3        parallel_3.5.3    promises_1.2.0.1 
#> [53] crayon_1.5.0      lattice_0.20-38   haven_2.3.1       splines_3.5.3    
#> [57] hms_1.1.1         knitr_1.33        pillar_1.7.0      softImpute_1.4-1 
#> [61] reprex_2.0.0      glue_1.6.2        evaluate_0.14     trust_0.1-8      
#> [65] modelr_0.1.8      vctrs_0.3.8       tzdb_0.1.1        httpuv_1.5.2     
#> [69] cellranger_1.1.0  gtable_0.3.0      ebnm_1.0-11       assertthat_0.2.1 
#> [73] ashr_2.2-54       xfun_0.29         broom_0.7.6       NNLM_0.4.2       
#> [77] later_1.3.0       truncnorm_1.0-8   ellipsis_0.3.2