├── .Rproj.user ├── shared │ └── notebooks │ │ ├── paths │ │ └── patch-chunk-names └── 16D545D7 │ ├── console06 │ └── INDEX001 │ ├── sources │ └── prop │ │ ├── C6642F52 │ │ ├── 370AE732 │ │ ├── 3F7C5D62 │ │ ├── 8CF873B8 │ │ ├── B6BA9F26 │ │ ├── DF095DE0 │ │ └── INDEX │ ├── rmd-outputs │ ├── saved_source_markers │ ├── pcs │ ├── source-pane.pper │ ├── workbench-pane.pper │ ├── debug-breakpoints.pper │ ├── files-pane.pper │ └── windowlayoutstate.pper │ ├── cpp-complilation-config │ ├── persistent-state │ └── cpp-definition-cache ├── .Rbuildignore ├── src ├── MatrixFact.dll ├── Makevars ├── Makevars.win ├── SemiNMF.cpp ├── Lee_NMF.cpp ├── nmf_log.cpp ├── lognmf_test.cpp ├── ONMF.cpp ├── lognmf.cpp ├── SO_NMF.cpp ├── SO_Bin3.cpp ├── sobin_test.cpp └── RcppExports.cpp ├── .gitignore ├── NAMESPACE ├── MatrixFact.Rproj ├── Read-and-delete-me ├── DESCRIPTION ├── man ├── bin.test.Rd └── nmf.main.Rd ├── R ├── RcppExports.R └── main.R ├── others ├── lognmf_test.cpp └── sobin_test.cpp ├── README.md ├── .Rhistory └── LICENSE /.Rproj.user/shared/notebooks/paths: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/console06/INDEX001: -------------------------------------------------------------------------------- 1 | [] -------------------------------------------------------------------------------- /.Rproj.user/shared/notebooks/patch-chunk-names: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/sources/prop/C6642F52: -------------------------------------------------------------------------------- 1 | { 2 | } -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/rmd-outputs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/saved_source_markers: -------------------------------------------------------------------------------- 1 | {"active_set":"","sets":[]} -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/pcs/source-pane.pper: -------------------------------------------------------------------------------- 1 | { 2 | "activeTab" : 0 3 | } -------------------------------------------------------------------------------- /src/MatrixFact.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cralo31/MatrixFact/HEAD/src/MatrixFact.dll -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | src/*.o 6 | src/*.so 7 | src/*.dll 8 | -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/sources/prop/370AE732: -------------------------------------------------------------------------------- 1 | { 2 | "cursorPosition" : "28,48", 3 | "scrollLine" : "0" 4 | } -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/sources/prop/3F7C5D62: -------------------------------------------------------------------------------- 1 | { 2 | "cursorPosition" : "24,1", 3 | "scrollLine" : "4" 4 | } -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/sources/prop/8CF873B8: -------------------------------------------------------------------------------- 1 | { 2 | "cursorPosition" : "7,37", 3 | "scrollLine" : "0" 4 | } -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/sources/prop/B6BA9F26: -------------------------------------------------------------------------------- 1 | { 2 | "cursorPosition" : "0,0", 3 | "scrollLine" : "101" 4 | } -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/pcs/workbench-pane.pper: -------------------------------------------------------------------------------- 1 | { 2 | "TabSet1" : 3, 3 | "TabSet2" : 3, 4 | "TabZoom" : { 5 | } 6 | } -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/pcs/debug-breakpoints.pper: -------------------------------------------------------------------------------- 1 | { 2 | "debugBreakpointsState" : { 3 | "breakpoints" : [ 4 | ] 5 | } 6 | } -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/sources/prop/DF095DE0: -------------------------------------------------------------------------------- 1 | { 2 | "cursorPosition" : "36,106", 3 | "scrollLine" : "15", 4 | "tempName" : "Untitled1" 5 | } -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(bin.test) 4 | export(nmf.main) 5 | import(irlba) 6 | import(pracma) 7 | importFrom(Rcpp,evalCpp) 8 | useDynLib(MatrixFact, .registration = TRUE) 9 | -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/pcs/files-pane.pper: -------------------------------------------------------------------------------- 1 | { 2 | "path" : "C:/Users/yuton/Dropbox/packages/MatrixFact", 3 | "sortOrder" : [ 4 | { 5 | "ascending" : true, 6 | "columnIndex" : 2 7 | } 8 | ] 9 | } -------------------------------------------------------------------------------- /MatrixFact.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | BuildType: Package 16 | PackageUseDevtools: Yes 17 | PackageInstallArgs: --no-multiarch --with-keep.source 18 | -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/pcs/windowlayoutstate.pper: -------------------------------------------------------------------------------- 1 | { 2 | "left" : { 3 | "panelheight" : 966, 4 | "splitterpos" : 402, 5 | "topwindowstate" : "NORMAL", 6 | "windowheight" : 1004 7 | }, 8 | "right" : { 9 | "panelheight" : 966, 10 | "splitterpos" : 602, 11 | "topwindowstate" : "NORMAL", 12 | "windowheight" : 1004 13 | } 14 | } -------------------------------------------------------------------------------- /Read-and-delete-me: -------------------------------------------------------------------------------- 1 | * Edit the help file skeletons in 'man', possibly combining help files for multiple functions. 2 | * Edit the exports in 'NAMESPACE', and add necessary imports. 3 | * Put any C/C++/Fortran code in 'src'. 4 | * If you have compiled code, add a useDynLib() directive to 'NAMESPACE'. 5 | * Run R CMD build to build the package tarball. 6 | * Run R CMD check to check the package tarball. 7 | 8 | Read "Writing R Extensions" for more information. 9 | -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/cpp-complilation-config: -------------------------------------------------------------------------------- 1 | { 2 | "args" : [ 3 | "-IE:/R/RStudio/resources/libclang/builtin-headers/3.4", 4 | "-IC:/Users/yuton/Documents/R/win-library/3.5/Rcpp/include", 5 | "-IC:/Users/yuton/Documents/R/win-library/3.5/RcppArmadillo/include", 6 | "-std=gnu++11", 7 | "-IC:/PROGRA~1/R/R-35~1.3/include", 8 | "-DNDEBUG", 9 | "-fopenmp" 10 | ], 11 | "hash" : "154129465615412789841541278984", 12 | "is_cpp" : true, 13 | "pch" : "Rcpp" 14 | } -------------------------------------------------------------------------------- /src/Makevars: -------------------------------------------------------------------------------- 1 | 2 | ## With R 3.1.0 or later, you can uncomment the following line to tell R to 3 | ## enable compilation with C++11 (where available) 4 | ## 5 | ## Also, OpenMP support in Armadillo prefers C++11 support. However, for wider 6 | ## availability of the package we do not yet enforce this here. It is however 7 | ## recommended for client packages to set it. 8 | ## 9 | ## And with R 3.4.0, and RcppArmadillo 0.7.960.*, we turn C++11 on as OpenMP 10 | ## support within Armadillo prefers / requires it 11 | CXX_STD = CXX11 12 | 13 | PKG_CXXFLAGS = $(SHLIB_OPENMP_CXXFLAGS) 14 | PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) 15 | -------------------------------------------------------------------------------- /src/Makevars.win: -------------------------------------------------------------------------------- 1 | 2 | ## With R 3.1.0 or later, you can uncomment the following line to tell R to 3 | ## enable compilation with C++11 (where available) 4 | ## 5 | ## Also, OpenMP support in Armadillo prefers C++11 support. However, for wider 6 | ## availability of the package we do not yet enforce this here. It is however 7 | ## recommended for client packages to set it. 8 | ## 9 | ## And with R 3.4.0, and RcppArmadillo 0.7.960.*, we turn C++11 on as OpenMP 10 | ## support within Armadillo prefers / requires it 11 | CXX_STD = CXX11 12 | 13 | PKG_CXXFLAGS = $(SHLIB_OPENMP_CXXFLAGS) 14 | PKG_LIBS = $(SHLIB_OPENMP_CXXFLAGS) $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) 15 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: MatrixFact 2 | Type: Package 3 | Title: Algorithms for Non-negative Matrix Factorization 4 | Version: 1.0.0 5 | Date: 2019-06-11 6 | Author: Yutong Li, Ruoqing Zhu, and Annie Qu 7 | Maintainer: Yutong Li 8 | Description: This package performs 6 variations of the Non-negative Matrix Factorization method for matrices with either continuous or binary entries, such as the original NMF by Lee & Seung (1999) and SONMF by Li et. al(2018) . 9 | Encoding: UTF-8 10 | License: GPL (>= 2) 11 | RoxygenNote: 6.1.1 12 | Imports: Rcpp (>= 0.12.18), irlba, pracma 13 | LinkingTo: Rcpp, RcppArmadillo, irlba, pracma 14 | -------------------------------------------------------------------------------- /man/bin.test.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/main.R 3 | \name{bin.test} 4 | \alias{bin.test} 5 | \title{Function Specific for Binary Simulation} 6 | \usage{ 7 | bin.test(X, k, F.init, G.init, method, prob, iter = 500, tol = 1e-05, 8 | tau = 0.5, step_bin = 0.05, step_log = 0.001, factor = 2) 9 | } 10 | \description{ 11 | This function is for simulation purposes only. 12 | } 13 | \details{ 14 | This function is the same as nmf.main(), with the additional parameter of an input 15 | true probability matrix for simulation purpose. This is not applicable in actual 16 | scenarios, since there is no way of knowing the true underlying probability matrix 17 | beforehand. 18 | } 19 | -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/sources/prop/INDEX: -------------------------------------------------------------------------------- 1 | C%3A%2FUsers%2Fyuton%2FDropbox%2FJack%20Li%2FJASA%20Submission%2FMatrixFact%2FR%2Fmain.R="8EEE7971" 2 | C%3A%2FUsers%2Fyuton%2FDropbox%2FJack%20Li%2FJASA%20Submission%2FMatrixFact%2Fsrc%2FRcppExports.cpp="2CE7D1E4" 3 | C%3A%2FUsers%2Fyuton%2FDropbox%2FJack%2FSONMF%2Fpackage%2Fexamples.R="DF095DE0" 4 | C%3A%2FUsers%2Fyuton%2FDropbox%2Fpackages%2FMatrixFact%2FR%2FRcppExports.R="CC46F632" 5 | C%3A%2FUsers%2Fyuton%2FDropbox%2Fpackages%2FMatrixFact%2FR%2Fmain.R="370AE732" 6 | C%3A%2FUsers%2Fyuton%2FDropbox%2Fpackages%2FMatrixFact%2Fman%2FMatrixFact-package.Rd="3F7C5D62" 7 | C%3A%2FUsers%2Fyuton%2FDropbox%2Fpackages%2FMatrixFact%2Fsrc%2FLee_NMF.cpp="68C444E4" 8 | C%3A%2FUsers%2Fyuton%2FDropbox%2Fpackages%2FMatrixFact%2Fsrc%2FRcppExports.cpp="B6BA9F26" 9 | C%3A%2FUsers%2Fyuton%2FDropbox%2Fpackages%2FMatrixFact%2Fvignettes%2Fintroduction.Rmd="C6642F52" 10 | C%3A%2FUsers%2Fyuton%2FDropbox%2Fpackages%2ForthoDr%2FR%2ForthoDr_surv.r="8CF873B8" 11 | C%3A%2FUsers%2Fyuton%2FDropbox%2Fpackages%2ForthoDr%2Fsrc%2Freg_seff_solver.cpp="4233E1AE" 12 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | NMF <- function(X, k, F_init, G_init, error, iter) { 5 | .Call(`_MatrixFact_NMF`, X, k, F_init, G_init, error, iter) 6 | } 7 | 8 | ONMF <- function(X, k, F_init, G_init, error, iter) { 9 | .Call(`_MatrixFact_ONMF`, X, k, F_init, G_init, error, iter) 10 | } 11 | 12 | SO_BIN3 <- function(X, k, F_init, G_init, error, iter, tau, factor, step) { 13 | .Call(`_MatrixFact_SO_BIN3`, X, k, F_init, G_init, error, iter, tau, factor, step) 14 | } 15 | 16 | SO_NMF <- function(X, k, F_init, G_init, error, iter, tau, factor) { 17 | .Call(`_MatrixFact_SO_NMF`, X, k, F_init, G_init, error, iter, tau, factor) 18 | } 19 | 20 | SemiNMF <- function(X, k, F_init, G_init, error, iter) { 21 | .Call(`_MatrixFact_SemiNMF`, X, k, F_init, G_init, error, iter) 22 | } 23 | 24 | lognmf <- function(X, k, F_init, G_init, error, iter, tau, step) { 25 | .Call(`_MatrixFact_lognmf`, X, k, F_init, G_init, error, iter, tau, step) 26 | } 27 | 28 | log_test <- function(X, k, F_init, G_init, prob_t, error, iter, step) { 29 | .Call(`_MatrixFact_log_test`, X, k, F_init, G_init, prob_t, error, iter, step) 30 | } 31 | 32 | NMF_LOG <- function(X, k, F_init, G_init, error, iter, step) { 33 | .Call(`_MatrixFact_NMF_LOG`, X, k, F_init, G_init, error, iter, step) 34 | } 35 | 36 | sobin_test <- function(X, k, F_init, G_init, prob_t, error, iter, tau, factor, step) { 37 | .Call(`_MatrixFact_sobin_test`, X, k, F_init, G_init, prob_t, error, iter, tau, factor, step) 38 | } 39 | 40 | -------------------------------------------------------------------------------- /src/SemiNMF.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | using namespace arma; 9 | 10 | // [[Rcpp::export]] 11 | List SemiNMF(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, const double error, const int iter) 12 | { 13 | mat F, F_p, G, G_p, FG, t1, t2, b1, b2, ratio, info, X_F, F_F; 14 | vec all_res(iter), all_tol(iter); 15 | int count = 1, i_e = 0; 16 | 17 | // Initialize F & G 18 | G_p = G_init; 19 | F_p = F_init; 20 | FG = F_p * G_p.t(); 21 | 22 | all_tol(i_e) = 1; 23 | all_res(i_e) = mean(mean(square((X - FG)))); 24 | 25 | // Update F & G through iteration until convergence 26 | while (abs(all_tol(i_e)) > error && count != iter) { 27 | 28 | i_e += 1; 29 | 30 | // Perform matrix-wise update Scheme 31 | 32 | X_F = X.t()*F_p; 33 | F_F = F_p.t()*F_p; 34 | t1 = (abs(X_F) + X_F)/2; 35 | t2 = G_p*((abs(F_F) - F_F)/2); 36 | b1 = (abs(X_F) - X_F)/2; 37 | b2 = G_p*((abs(F_F) + F_F)/2); 38 | ratio = (t1 + t2) / (b1 + b2); 39 | G = G_p % sqrt(ratio); 40 | F = X*G*inv(G.t()*G); 41 | 42 | // Update information 43 | FG = F * G.t(); 44 | all_res(i_e) = mean(mean(square((X - FG)))); 45 | all_tol(i_e) = all_res(i_e - 1) - all_res(i_e); 46 | G_p = G; 47 | F_p = F; 48 | 49 | count += 1; 50 | } 51 | 52 | info = join_rows(all_tol, all_res); 53 | 54 | return List::create(_["F"]=F, _["G"]=G, _["info"] = info, 55 | _["final_tol"] = all_tol[i_e], _["final_res"] = all_res[i_e], _["iter"] = count); 56 | } 57 | 58 | -------------------------------------------------------------------------------- /src/Lee_NMF.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | using namespace arma; 9 | 10 | // [[Rcpp::export]] 11 | List NMF(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, const double error, 12 | const int iter) 13 | { 14 | //___________________ Initialization ___________________ 15 | arma::mat F_p = F_init; 16 | arma::mat G_p = G_init; 17 | arma::vec all_res(iter), all_tol(iter); 18 | int count = 1, i_e = 0; 19 | double eps = 1e-10; 20 | arma::mat F, G, FG, info; 21 | 22 | //___________________ Begin Algorithmn ___________________ 23 | 24 | FG = F_p * G_p.t(); 25 | 26 | all_res.fill(0); all_tol.fill(0); 27 | all_tol(i_e) = 1; 28 | all_res(i_e) = accu(square(X - FG)) / X.size(); 29 | 30 | 31 | while (all_tol(i_e) > error && count < iter) { 32 | 33 | i_e += 1; 34 | 35 | // Update G using multiplicative updates 36 | G = ((X.t() * F_p) / (G_p * F_p.t() * F_p + eps)) % G_p; 37 | G_p = G; 38 | 39 | // Update F using multiplicative updates 40 | F = F_p % ((X * G) / (F_p * G.t() * G + eps)); 41 | F_p = F; 42 | 43 | // Update Error 44 | FG = F * G.t(); 45 | 46 | all_res(i_e) = accu(square(X - FG)) / X.size(); 47 | all_tol(i_e) = all_res(i_e - 1) - all_res(i_e); 48 | count += 1; 49 | 50 | } 51 | 52 | // Enforce all values less than a certain threshold to be 0. 53 | F(find(F == eps)).fill(0); 54 | G(find(G == eps)).fill(0); 55 | 56 | 57 | info = join_rows(all_tol, all_res); 58 | 59 | return List::create(_["F"] = F, _["G"] = G, _["info"] = info,_["iter"] = count, _["final_tol"] = all_tol[i_e], 60 | _["final_res"] = all_res[i_e]); 61 | } 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /src/nmf_log.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | using namespace arma; 9 | 10 | // [[Rcpp::export]] 11 | List NMF_LOG(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, 12 | const double error, const int iter, double step) 13 | { 14 | //___________________ Initialization ___________________ 15 | arma::mat F_p = F_init; 16 | arma::mat G_p = G_init; 17 | arma::vec tempG, all_cost(iter), all_tol(iter); 18 | int count = 1, i_e = 0; 19 | double final_cost; 20 | arma::mat FG, F, G, info, proj_F, proj_G; 21 | arma::mat I = eye(k, k); 22 | arma::mat I_2 = eye(2*k, 2*k); 23 | arma::mat one = ones(size(X)); 24 | 25 | //___________________ Begin Algorithmn ___________________ 26 | 27 | FG = F_p * G_p.t(); 28 | 29 | // Initiate vectors to track errors 30 | all_cost.fill(0); all_tol.fill(0); 31 | all_tol(i_e) = 1; 32 | all_cost(i_e) = mean(mean(log(one + exp(FG)) - X % FG)); 33 | //all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 34 | 35 | while (all_tol(i_e) > error && count < iter) { 36 | 37 | i_e += 1; 38 | 39 | // Update F 40 | F = F_p + step * ((2 * X - one) / (one + exp((2*X - one) % (F_p * G_p.t())))) * G_p; 41 | F(find(F < 0)).zeros(); 42 | 43 | 44 | // Update G 45 | G = G_p + step * ((2 * X - one) / (one + exp((2*X - one) % (F * G_p.t())))).t() * F; 46 | 47 | F_p = F; G_p = G; 48 | 49 | // Update probability and projection error 50 | FG = F_p * G_p.t(); 51 | 52 | all_cost(i_e) = mean(mean(log(one + exp(FG)) - X % FG)); 53 | //all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 54 | all_tol(i_e) = all_cost(i_e - 1) - all_cost(i_e); 55 | count += 1; 56 | } 57 | 58 | FG = F * G.t(); 59 | final_cost = mean(mean(log(one + exp(FG)) - X % FG)); 60 | 61 | info = join_rows(all_tol, all_cost); //info = join_rows(info, all_prob); 62 | 63 | return List::create(_["F"] = F, _["G"] = G, _["info"] = info, _["iter"] = count, _["final_res"] = final_cost); 64 | } 65 | -------------------------------------------------------------------------------- /src/lognmf_test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | using namespace arma; 9 | 10 | // [[Rcpp::export]] 11 | List log_test(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, arma::mat prob_t, 12 | const double error, const int iter, double step) 13 | { 14 | //___________________ Initialization ___________________ 15 | arma::mat F_p = F_init; 16 | arma::mat G_p = G_init; 17 | arma::vec tempG, all_cost(iter), all_tol(iter), all_prob(iter); 18 | int count = 1, i_e = 0; 19 | double final_cost; 20 | arma::mat FG, F, G, info, proj_F, proj_G; 21 | arma::mat I = eye(k, k); 22 | arma::mat I_2 = eye(2*k, 2*k); 23 | arma::mat one = ones(size(X)); 24 | 25 | //___________________ Begin Algorithmn ___________________ 26 | 27 | FG = F_p * G_p.t(); 28 | 29 | // Initiate vectors to track errors 30 | all_cost.fill(0); all_tol.fill(0); 31 | all_tol(i_e) = 1; 32 | all_cost(i_e) = mean(mean(log(one + exp(FG)) - X % FG)); 33 | all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 34 | 35 | while (all_tol(i_e) > error && count < iter) { 36 | 37 | i_e += 1; 38 | 39 | // Update F 40 | F = F_p + step * ((2 * X - one) / (one + exp((2*X - one) % (F_p * G_p.t())))) * G_p; 41 | F(find(F < 0)).zeros(); 42 | 43 | 44 | // Update G 45 | G = G_p + step * ((2 * X - one) / (one + exp((2*X - one) % (F * G_p.t())))).t() * F; 46 | 47 | F_p = F; G_p = G; 48 | 49 | // Update probability and projection error 50 | FG = F_p * G_p.t(); 51 | 52 | all_cost(i_e) = mean(mean(log(one + exp(FG)) - X % FG)); 53 | all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 54 | all_tol(i_e) = all_cost(i_e - 1) - all_cost(i_e); 55 | count += 1; 56 | } 57 | 58 | FG = F * G.t(); 59 | final_cost = mean(mean(log(one + exp(FG)) - X % FG)); 60 | 61 | info = join_rows(all_tol, all_cost); info = join_rows(info, all_prob); 62 | 63 | return List::create(_["F"] = F, _["G"] = G, _["info"] = info, _["iter"] = count, _["final_res"] = final_cost); 64 | } 65 | -------------------------------------------------------------------------------- /others/lognmf_test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | using namespace arma; 9 | 10 | // [[Rcpp::export]] 11 | List log_test(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, arma::mat prob_t, 12 | const double error, const int iter, double step) 13 | { 14 | //___________________ Initialization ___________________ 15 | arma::mat F_p = F_init; 16 | arma::mat G_p = G_init; 17 | arma::vec tempG, all_cost(iter), all_tol(iter), all_prob(iter); 18 | int count = 1, i_e = 0; 19 | double final_cost; 20 | arma::mat FG, F, G, info, proj_F, proj_G; 21 | arma::mat I = eye(k, k); 22 | arma::mat I_2 = eye(2*k, 2*k); 23 | arma::mat one = ones(size(X)); 24 | 25 | //___________________ Begin Algorithmn ___________________ 26 | 27 | FG = F_p * G_p.t(); 28 | 29 | // Initiate vectors to track errors 30 | all_cost.fill(0); all_tol.fill(0); 31 | all_tol(i_e) = 1; 32 | all_cost(i_e) = mean(mean(log(one + exp(FG)) - X % FG)); 33 | all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 34 | 35 | while (all_tol(i_e) > error && count < iter) { 36 | 37 | i_e += 1; 38 | 39 | // Update F 40 | F = F_p + step * ((2 * X - one) / (one + exp((2*X - one) % (F_p * G_p.t())))) * G_p; 41 | F(find(F < 0)).zeros(); 42 | 43 | 44 | // Update G 45 | G = G_p + step * ((2 * X - one) / (one + exp((2*X - one) % (F * G_p.t())))).t() * F; 46 | 47 | F_p = F; G_p = G; 48 | 49 | // Update probability and projection error 50 | FG = F_p * G_p.t(); 51 | 52 | all_cost(i_e) = mean(mean(log(one + exp(FG)) - X % FG)); 53 | all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 54 | all_tol(i_e) = all_cost(i_e - 1) - all_cost(i_e); 55 | count += 1; 56 | } 57 | 58 | FG = F * G.t(); 59 | final_cost = mean(mean(log(one + exp(FG)) - X % FG)); 60 | 61 | info = join_rows(all_tol, all_cost); info = join_rows(info, all_prob); 62 | 63 | return List::create(_["F"] = F, _["G"] = G, _["info"] = info, _["iter"] = count, _["final_res"] = final_cost); 64 | } 65 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MatrixFact 2 | R Package for Semi-orthogonal Non-negative Matrix Factorization (SONMF) and other NMF methods 3 | 4 | Developer: Yutong Li (Novartis Pharmaceuticals) 5 | 6 | # Description 7 | This R package is developed for the Semi-orthogonal Non-negative Matrix Factorization method proposed in the "Topic Modeling on Triage Notes with Semi-orthognal Non-negative Matrix Factorization" manuscript published in the Journal of the American Statistical Association (link: https://www.tandfonline.com/doi/full/10.1080/01621459.2020.1862667). 8 | 9 | # Installation 10 | Execute the following code in R to install the package. 11 | ```{r} 12 | # Need the "devtools" library to install packages from Github 13 | install.packages("devtools") 14 | 15 | # Install the "MatrixFact" library 16 | devtools::install_github('cralo31/MatrixFact') 17 | ``` 18 | 19 | # Example 20 | It is recommended to run the following examples to have an idea of how SONMF works. 21 | 22 | ```{r} 23 | n = 100 24 | X = matrix(rnorm(n^2, 0, 1), n, n) # Construct a 100-by-100 matrix with random elements 25 | X[X < 0] = 0 # Truncate all negative values to create a non-negative matix 26 | mode = 1 # Set mode to 1 for matrix with continuous entries 27 | k = 5 # Set target factorization rank to be k 28 | iter = 200 # Set number of iterations to be 200 29 | tol = 1e-5 # Set convergence threshold to 1e-5 30 | 31 | # Run SONMF with svd initialization 32 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 33 | 34 | # Run NMF with random initialization 35 | nmf.X = nmf.main(X, mode, k, "nmf", "random", iter, tol); nmf.X 36 | 37 | # Run ONMF with random initialization 38 | onmf.X = nmf.main(X, mode, k, "onmf", "random", iter, tol); onmf.X 39 | 40 | # Run Semi-NMF with kmeans initialization 41 | semi.X = nmf.main(X, mode, k, "semi", "kmeans", iter, tol); semi.X 42 | 43 | ## Binary Case 44 | 45 | X.bin = matrix(rbinom(n^2, 1, runif(n^2, 0.25, 0.75)), n, n) # Construct a 100-by-100 46 | # matrix with random binary elements 47 | mode.2 = 2 48 | 49 | # Run Binary SONMF with svd initialization 50 | sobin.X = nmf.main(X.bin, mode.2, k, "so_bin", "svd", iter, tol); sobin.X 51 | 52 | # Run logNMF with random initialization 53 | lognmf.X = nmf.main(X.bin, mode.2, k, "log_nmf", "random", iter, tol); lognmf.X 54 | ``` 55 | -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/persistent-state: -------------------------------------------------------------------------------- 1 | build-last-errors="[]" 2 | build-last-errors-base-dir="C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/" 3 | build-last-outputs="[{\"output\":\"==> Rcpp::compileAttributes()\\n\\n\",\"type\":0},{\"output\":\"* Updated R/RcppExports.R\\r\\n\",\"type\":1},{\"output\":\"\\n\",\"type\":1},{\"output\":\"==> Rcmd.exe INSTALL --no-multiarch --with-keep.source MatrixFact\\n\\n\",\"type\":0},{\"output\":\"* installing to library 'C:/Users/yuton/Documents/R/win-library/3.5'\\r\\n\",\"type\":1},{\"output\":\"* installing *source* package 'MatrixFact' ...\\r\\n\",\"type\":1},{\"output\":\"\",\"type\":1},{\"output\":\"** libs\\r\\n\",\"type\":1},{\"output\":\"\",\"type\":1},{\"output\":\"make: Nothing to be done for 'all'.\\n\",\"type\":1},{\"output\":\"\",\"type\":1},{\"output\":\"installing to C:/Users/yuton/Documents/R/win-library/3.5/MatrixFact/libs/x64\\r\\n\",\"type\":1},{\"output\":\"** R\\r\\n\",\"type\":1},{\"output\":\"** byte-compile and prepare package for lazy loading\\r\\n\",\"type\":1},{\"output\":\"\",\"type\":1},{\"output\":\"** help\\r\\n\",\"type\":1},{\"output\":\"\",\"type\":1},{\"output\":\" converting help for package 'MatrixFact'\\r\\n\",\"type\":1},{\"output\":\" bin.test html \\r\\n\",\"type\":1},{\"output\":\" nmf.main html \",\"type\":1},{\"output\":\"*** installing help indices\\r\\n\",\"type\":1},{\"output\":\" finding HTML links ... done\\r\\n\",\"type\":1},{\"output\":\"\",\"type\":1},{\"output\":\"\\r\\n\",\"type\":1},{\"output\":\"\",\"type\":1},{\"output\":\"** building package indices\\r\\n\",\"type\":1},{\"output\":\"** testing if installed package can be loaded\\r\\n\",\"type\":1},{\"output\":\"\",\"type\":1},{\"output\":\"* DONE (MatrixFact)\\r\\n\",\"type\":1},{\"output\":\"\",\"type\":1},{\"output\":\"In R CMD INSTALL\\r\\n\",\"type\":1},{\"output\":\"\",\"type\":1},{\"output\":\"WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:\\n\\nhttps://cran.rstudio.com/bin/windows/Rtools/\\n\\n\",\"type\":2}]" 4 | compile_pdf_state="{\"errors\":[],\"output\":\"\",\"running\":false,\"tab_visible\":false,\"target_file\":\"\"}" 5 | files.monitored-path="" 6 | find-in-files-state="{\"handle\":\"\",\"input\":\"\",\"path\":\"\",\"regex\":true,\"results\":{\"file\":[],\"line\":[],\"lineValue\":[],\"matchOff\":[],\"matchOn\":[]},\"running\":false}" 7 | imageDirtyState="1" 8 | saveActionState="-1" 9 | -------------------------------------------------------------------------------- /src/ONMF.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | using namespace arma; 9 | 10 | // [[Rcpp::export]] 11 | List ONMF(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, const double error, 12 | const int iter) 13 | { 14 | //___________________ Initialization ___________________ 15 | arma::mat F = F_init; 16 | arma::mat G = G_init; 17 | arma::mat pF = F_init; 18 | arma::mat pG = G_init; 19 | arma::vec F_j, h, tempF, tempG, all_res(iter), all_tol(iter), all_orth(iter); 20 | int count = 1, i_e = 0; 21 | double eps = 1e-10; 22 | arma::mat A, B, C, D, pFG, FG, F_orig, F_1, F_2, Z, Q, info; 23 | arma::mat I = eye(k, k); 24 | 25 | //___________________ Begin Algorithmn ___________________ 26 | 27 | arma::vec one = ones(k); 28 | arma::mat U = F * one; 29 | 30 | FG = F * G.t(); 31 | 32 | all_res.fill(0); all_orth.fill(0); all_tol.fill(0); 33 | all_tol(i_e) = 1; 34 | all_res(i_e) = accu(square(X - FG)) / X.size(); 35 | all_orth(i_e) = accu((F.t() * F - I) % (F.t() * F - I)); 36 | 37 | while (abs(all_tol(i_e)) > error && count < iter) { 38 | 39 | i_e += 1; 40 | 41 | // Update F in column-wise fashion 42 | A = X * G; 43 | B = G.t() * G; 44 | for (int j = 0; j < k; ++j) { 45 | F_j = U - F.col(j); 46 | h = A.col(j) - F * B.col(j) + F.col(j) * B(j,j); 47 | tempF = F.col(j); 48 | tempF = h - F_j * (((F_j.t() * h) / (F_j.t() * F_j))); 49 | tempF(find(tempF < 0)).fill(eps); 50 | F.col(j) = tempF; 51 | F.col(j) = F.col(j) * inv(sqrt(F.col(j).t() * F.col(j))); // Normalize columns of F as you update 52 | U = F_j + F.col(j); 53 | } 54 | 55 | // Update G in column-wise fashion 56 | C = X.t() * F; 57 | D = F.t() * F; 58 | for (int j = 0; j < k; ++j) { 59 | tempG = G.col(j); 60 | tempG = C.col(j) - G * D.col(j) + G.col(j) * D(j,j); 61 | tempG(find(tempG < 0)).fill(eps); 62 | G.col(j) = tempG; 63 | } 64 | 65 | // Update Error 66 | FG = F * G.t(); 67 | 68 | all_res(i_e) = accu(square(X - FG)) / X.size(); 69 | all_tol(i_e) = all_res(i_e - 1) - all_res(i_e); 70 | all_orth(i_e) = accu((F.t() * F - I) % (F.t() * F - I)); 71 | 72 | count += 1; 73 | } 74 | 75 | info = join_rows(all_tol, all_res); info = join_rows(info, all_orth); 76 | 77 | return List::create(_["F"] = F, _["G"] = G, _["info"] = info, 78 | _["iter"] = count, _["final_tol"] = all_tol[i_e], _["final_res"] = all_res[i_e], 79 | _["final_orth"] = all_orth[i_e]); 80 | } 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /src/lognmf.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | using namespace arma; 9 | 10 | // [[Rcpp::export]] 11 | List lognmf(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, 12 | const double error, const int iter, double tau, double step) 13 | { 14 | //___________________ Initialization ___________________ 15 | arma::mat F_p = F_init; 16 | arma::mat G_p = G_init; 17 | arma::vec tempG, all_cost(iter), all_tol(iter), all_tau(iter); 18 | int count = 1, i_e = 0, counter; 19 | double tol = 1, prev_cost, temp_cost, final_cost; 20 | arma::mat FG, F, G, info, F_temp, FG_temp; 21 | arma::mat I = eye(k, k); 22 | arma::mat I_2 = eye(2*k, 2*k); 23 | arma::mat one = ones(size(X)); 24 | 25 | //___________________ Begin Algorithmn ___________________ 26 | 27 | FG = F_p * G_p.t(); 28 | 29 | // Initiate vectors to track errors 30 | all_cost.fill(0); all_tol.fill(0); 31 | all_tol(i_e) = tol; 32 | all_cost(i_e) = mean(mean(log(one + exp(FG)) - X % FG)); 33 | all_tau(i_e) = tau; 34 | prev_cost = all_tol(0); 35 | // all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 36 | 37 | while (all_tol(i_e) > error && count < iter) { 38 | 39 | i_e += 1; 40 | 41 | // Update G 42 | G = G_p + step * ((2 * X - one) / (one + exp((2*X - one) % (F_p * G_p.t())))).t() * F_p; 43 | G_p = G; 44 | 45 | // Update F 46 | counter = 0; 47 | while (tol < 0 || counter == 0) { 48 | F_temp = F_p + tau * ((2 * X - one) / (one + exp((2*X - one) % (F_p * G.t())))) * G; 49 | F_temp(find(F_temp < 0)).zeros(); 50 | FG_temp = F_temp * G.t(); 51 | temp_cost = mean(mean(log(one + exp(FG_temp)) - X % FG_temp)); 52 | tol = prev_cost - temp_cost; 53 | counter += 1; 54 | 55 | if (tol <= 0 && counter <= 50) { 56 | tau = tau / 2; 57 | } else if (tol > 0){ 58 | F = F_temp; 59 | tau = tau * 2; 60 | prev_cost = temp_cost; 61 | all_cost(i_e) = temp_cost; all_tol(i_e) = tol; all_tau(i_e) = tau; 62 | } else { 63 | cout << "Cannot find suitable step size" << endl; 64 | F = F_p; 65 | break; 66 | } 67 | 68 | } 69 | 70 | F_p = F; 71 | 72 | FG = F * G.t(); 73 | final_cost = mean(mean(log(one + exp(FG)) - X % FG)); 74 | 75 | 76 | // Update probability and projection error 77 | // all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 78 | count += 1; 79 | 80 | } 81 | 82 | info = join_rows(all_tol, all_cost); info = join_rows(info, all_tau); 83 | 84 | 85 | //colnames(info) = ("Tol", "Cost", "Ortho", "Prob", "Tau", "Counter"); 86 | 87 | return List::create(_["F"] = F, _["G"] = G, _["info"] = info, _["iter"] = count, 88 | _["final_res"] = final_cost); 89 | } 90 | 91 | 92 | -------------------------------------------------------------------------------- /src/SO_NMF.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | using namespace arma; 9 | 10 | // [[Rcpp::export]] 11 | List SO_NMF(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, const double error, 12 | const int iter, double tau, const int factor) 13 | { 14 | //___________________ Initialization ___________________ 15 | arma::mat F = F_init, G = G_init; 16 | arma::vec tempG, all_res(iter), all_tol(iter), all_orth(iter), all_tau(iter), all_counter(iter), all_res2(iter); 17 | double prev_mse, temp_mse; 18 | int count = 1, i_e = 0, counter; 19 | double eps = 0, tol = 1; 20 | arma::mat C, D, FG, F_new, R, FG_temp, U, V, info, V_U, V_F; 21 | arma::mat I = eye(k, k); 22 | arma::mat I_2 = eye(2*k, 2*k); 23 | arma::vec one = ones(k); 24 | 25 | //___________________ Begin Algorithmn ___________________ 26 | 27 | FG = F * G.t(); 28 | prev_mse = mean(mean(square((X - FG)))); 29 | 30 | all_res.fill(0); all_orth.fill(0); all_tol.fill(0); 31 | all_tol(i_e) = 1; 32 | all_res(i_e) = prev_mse; 33 | all_orth(i_e) = accu((F.t() * F - I) % (F.t() * F - I)); 34 | all_tau(i_e) = 1/2; 35 | all_counter(i_e) = 1; 36 | all_res2(i_e) = accu(square(X - FG)) / accu(square(X)); 37 | 38 | 39 | while (abs(all_tol(i_e)) > error && count < iter) { 40 | 41 | i_e += 1; 42 | 43 | // Update G in column-wise fashion 44 | G = X.t() * F; 45 | G(find(G < 0)).fill(eps); 46 | 47 | // Solve for F 48 | // Set the residual in the direction of the gradient 49 | R = X * G * (-2) + F * G.t() * G * 2; 50 | 51 | // Set up U and V where Z = U(V^T) 52 | U = join_rows(R, F); 53 | V = join_rows(F, -R); 54 | 55 | // Find orthogonal Q via Crank-Nicolson, then use Q to project onto original F_1 56 | // to create corrected columns 57 | counter = 0; 58 | V_U = V.t() * U; 59 | V_F = V.t() * F; 60 | while (tol < 0 || counter == 0) { 61 | F_new = F - U * inv(I_2 + V_U * tau/2) * V_F * tau; 62 | FG_temp = F_new * G.t(); 63 | temp_mse = accu(square(X - FG_temp)) / X.size(); 64 | tol = prev_mse - temp_mse; 65 | counter += 1; 66 | 67 | if (tol > 0) { 68 | tau = tau * factor; 69 | F = F_new; 70 | all_tau(i_e) = tau; all_counter(i_e) = counter; all_res(i_e) = temp_mse; 71 | prev_mse = temp_mse; 72 | } else if (tol <= 0 && counter <= 50) { 73 | tau = tau / factor; 74 | } else { 75 | break; 76 | } 77 | } 78 | 79 | // Update Error 80 | FG = F * G.t(); 81 | all_tol(i_e) = all_res(i_e - 1) - all_res(i_e); 82 | all_orth(i_e) = accu((F.t() * F - I) % (F.t() * F - I)); 83 | 84 | count += 1; 85 | 86 | } 87 | 88 | // Merge info into one matrix 89 | info = join_rows(all_tol, all_res); info = join_rows(info, all_orth); 90 | info = join_rows(info, all_tau); info = join_rows(info, all_counter); 91 | 92 | return List::create(_["F"] = F, _["G"] = G, _["info"] = info, _["iter"] = count, _["final_tol"] = all_tol[i_e], 93 | _["final_res"] = all_res[i_e], _["final_orth"] = all_orth[i_e]); 94 | } 95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /src/SO_Bin3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | using namespace arma; 9 | 10 | // [[Rcpp::export]] 11 | List SO_BIN3(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, 12 | const double error, const int iter, double tau, const int factor, double step) 13 | { 14 | //___________________ Initialization ___________________ 15 | arma::mat F = F_init; 16 | arma::mat G_p = G_init; 17 | arma::vec tempG, all_cost(iter), all_tol(iter), all_orth(iter), all_tau(iter), all_counter(iter); 18 | double prev_cost, temp_cost; 19 | int count = 1, i_e = 0, counter; 20 | double tol = 1; 21 | arma::mat C, D, FG, F_new, R, FG_temp, U, V, nume, deno, G, info, V_U, V_F; 22 | arma::mat I = eye(k, k); 23 | arma::mat I_2 = eye(2*k, 2*k); 24 | arma::mat one = ones(size(X)); 25 | 26 | 27 | //___________________ Begin Algorithmn ___________________ 28 | 29 | FG = F * G_p.t(); 30 | 31 | // Initiate vectors to track errors 32 | all_cost.fill(0); all_orth.fill(0); all_tol.fill(0); 33 | all_tol(i_e) = 1; 34 | all_cost(i_e) = mean(mean(log(one + exp(FG)) - X % FG)); 35 | all_orth(i_e) = accu((F.t() * F - I) % (F.t() * F - I)); 36 | all_tau(i_e) = tau; 37 | all_counter(i_e) = 1; 38 | prev_cost = all_cost(0); 39 | 40 | while (all_tol(i_e) > error && count < iter) { 41 | 42 | i_e += 1; 43 | 44 | // Update G using Newton-Rhapson 45 | FG = F * G_p.t(); 46 | nume = (one / (one + exp(-(FG))) - X).t() * F; 47 | deno = (exp(FG) / square(one + exp(FG))).t() * square(F); 48 | G = G_p - step * (nume / deno); 49 | G(find(G < 0)).zeros(); 50 | G_p = G; 51 | 52 | // Solve for F 53 | // Set gradient of F 54 | R = (one / (one + exp(-(F * G.t()))) - X) * G; 55 | 56 | // Set up U and V where Z = U(V^T) 57 | U = join_rows(R, F); 58 | V = join_rows(F, -R); 59 | 60 | // Find orthogonal Q via Crank-Nicolson, then use Q to project onto original F_1 61 | // to create corrected columns 62 | counter = 0; 63 | V_U = V.t() * U; 64 | V_F = V.t() * F; 65 | while (tol < 0 || counter == 0) { 66 | F_new = F - tau * U * inv(I_2 + tau/2 * V_U) * V_F; 67 | FG_temp = F_new * G.t(); 68 | temp_cost = mean(mean(log(one + exp(FG_temp)) - X % FG_temp)); 69 | tol = prev_cost - temp_cost; 70 | counter += 1; 71 | 72 | if (tol > 0) { 73 | all_cost(i_e) = temp_cost;all_tol(i_e) = tol; all_tau(i_e) = tau; all_counter(i_e) = counter; 74 | tau = tau * factor; 75 | F = F_new; 76 | prev_cost = temp_cost; 77 | } else if (tol <= 0 && counter <= 50) { 78 | tau = tau / factor; 79 | } else { 80 | break; 81 | } 82 | } 83 | 84 | // Update probability and projection error 85 | FG = F * G.t(); 86 | all_orth(i_e) = accu((F.t() * F - I) % (F.t() * F - I)); 87 | count += 1; 88 | 89 | } 90 | 91 | info = join_rows(all_tol, all_cost); info = join_rows(info, all_orth); info = join_rows(info, all_tau); 92 | info = join_rows(info, all_counter); 93 | 94 | return List::create(_["F"] = F, _["G"] = G, _["info"] = info, _["iter"] = count, 95 | _["final_res"] = all_cost[i_e], _["final_ortho"] = all_orth[i_e]); 96 | } 97 | 98 | 99 | -------------------------------------------------------------------------------- /others/sobin_test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | using namespace arma; 9 | 10 | // [[Rcpp::export]] 11 | List sobin_test(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, arma::mat prob_t, 12 | const double error, const int iter, double tau, const int factor, double step) 13 | { 14 | //___________________ Initialization ___________________ 15 | arma::mat F = F_init; 16 | arma::mat G_p = G_init; 17 | arma::vec tempG, all_cost(iter), all_tol(iter), all_orth(iter), all_tau(iter), all_counter(iter), all_prob(iter); 18 | double prev_cost, temp_cost; 19 | int count = 1, i_e = 0, counter; 20 | double tol = 1; 21 | arma::mat C, D, FG, F_new, R, FG_temp, U, V, nume, deno, G, info; 22 | arma::mat I = eye(k, k); 23 | arma::mat I_2 = eye(2*k, 2*k); 24 | arma::mat one = ones(size(X)); 25 | 26 | 27 | //___________________ Begin Algorithmn ___________________ 28 | 29 | FG = F * G_p.t(); 30 | 31 | // Initiate vectors to track errors 32 | all_cost.fill(0); all_orth.fill(0); all_tol.fill(0); 33 | all_tol(i_e) = 1; 34 | all_cost(i_e) = mean(mean(log(one + exp(FG)) - X % FG)); 35 | all_orth(i_e) = accu((F.t() * F - I) % (F.t() * F - I)); 36 | all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 37 | all_tau(i_e) = tau; 38 | all_counter(i_e) = 1; 39 | prev_cost = all_cost(0); 40 | 41 | while (all_tol(i_e) > error && count < iter) { 42 | 43 | i_e += 1; 44 | 45 | // Update G using Newton-Rhapson 46 | FG = F * G_p.t(); 47 | nume = (one / (one + exp(-(FG))) - X).t() * F; 48 | deno = (exp(FG) / square(one + exp(FG))).t() * square(F); 49 | G = G_p - step * (nume / deno); 50 | G(find(G < 0)).zeros(); 51 | G_p = G; 52 | 53 | // Solve for F 54 | // Set gradient of F 55 | R = (one / (one + exp(-(F * G.t()))) - X) * G; 56 | 57 | // Set up U and V where Z = U(V^T) 58 | U = join_rows(R, F); 59 | V = join_rows(F, -R); 60 | 61 | // Find orthogonal Q via Crank-Nicolson, then use Q to project onto original F_1 62 | // to create corrected columns 63 | counter = 0; 64 | while (tol < 0 || counter == 0) { 65 | F_new = F - tau * U * inv(I_2 + tau/2 * V.t() * U) * V.t() * F; 66 | FG_temp = F_new * G.t(); 67 | temp_cost = mean(mean(log(one + exp(FG_temp)) - X % FG_temp)); 68 | tol = prev_cost - temp_cost; 69 | counter += 1; 70 | 71 | if (tol > 0) { 72 | all_cost(i_e) = temp_cost;all_tol(i_e) = tol; all_tau(i_e) = tau; all_counter(i_e) = counter; 73 | tau = tau * factor; 74 | F = F_new; 75 | prev_cost = temp_cost; 76 | } else if (tol <= 0 && counter <= 50) { 77 | tau = tau / factor; 78 | } else { 79 | break; 80 | } 81 | } 82 | 83 | // Update probability and projection error 84 | FG = F * G.t(); 85 | all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 86 | all_orth(i_e) = accu((F.t() * F - I) % (F.t() * F - I)); 87 | count += 1; 88 | 89 | } 90 | 91 | info = join_rows(all_tol, all_cost); 92 | info = join_rows(info, all_prob); 93 | info = join_rows(info, all_orth); 94 | 95 | return List::create(_["F"] = F, _["G"] = G, _["info"] = info, _["iter"] = count, 96 | _["final_res"] = all_cost[i_e], _["final_ortho"] = all_orth[i_e]); 97 | } 98 | 99 | 100 | -------------------------------------------------------------------------------- /src/sobin_test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | 6 | using namespace Rcpp; 7 | using namespace std; 8 | using namespace arma; 9 | 10 | // [[Rcpp::export]] 11 | List sobin_test(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, arma::mat prob_t, 12 | const double error, const int iter, double tau, const int factor, double step) 13 | { 14 | //___________________ Initialization ___________________ 15 | arma::mat F = F_init; 16 | arma::mat G_p = G_init; 17 | arma::vec tempG, all_cost(iter), all_tol(iter), all_orth(iter), all_tau(iter), all_counter(iter), all_prob(iter); 18 | double prev_cost, temp_cost; 19 | int count = 1, i_e = 0, counter; 20 | double tol = 1; 21 | arma::mat C, D, FG, F_new, R, FG_temp, U, V, nume, deno, G, info; 22 | arma::mat I = eye(k, k); 23 | arma::mat I_2 = eye(2*k, 2*k); 24 | arma::mat one = ones(size(X)); 25 | 26 | 27 | //___________________ Begin Algorithmn ___________________ 28 | 29 | FG = F * G_p.t(); 30 | 31 | // Initiate vectors to track errors 32 | all_cost.fill(0); all_orth.fill(0); all_tol.fill(0); 33 | all_tol(i_e) = 1; 34 | all_cost(i_e) = mean(mean(log(one + exp(FG)) - X % FG)); 35 | all_orth(i_e) = accu((F.t() * F - I) % (F.t() * F - I)); 36 | all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 37 | all_tau(i_e) = tau; 38 | all_counter(i_e) = 1; 39 | prev_cost = all_cost(0); 40 | 41 | while (all_tol(i_e) > error && count < iter) { 42 | 43 | i_e += 1; 44 | 45 | // Update G using Newton-Rhapson 46 | FG = F * G_p.t(); 47 | nume = (one / (one + exp(-(FG))) - X).t() * F; 48 | deno = (exp(FG) / square(one + exp(FG))).t() * square(F); 49 | G = G_p - step * (nume / deno); 50 | G(find(G < 0)).zeros(); 51 | G_p = G; 52 | 53 | // Solve for F 54 | // Set gradient of F 55 | R = (one / (one + exp(-(F * G.t()))) - X) * G; 56 | 57 | // Set up U and V where Z = U(V^T) 58 | U = join_rows(R, F); 59 | V = join_rows(F, -R); 60 | 61 | // Find orthogonal Q via Crank-Nicolson, then use Q to project onto original F_1 62 | // to create corrected columns 63 | counter = 0; 64 | while (tol < 0 || counter == 0) { 65 | F_new = F - tau * U * inv(I_2 + tau/2 * V.t() * U) * V.t() * F; 66 | FG_temp = F_new * G.t(); 67 | temp_cost = mean(mean(log(one + exp(FG_temp)) - X % FG_temp)); 68 | tol = prev_cost - temp_cost; 69 | counter += 1; 70 | 71 | if (tol > 0) { 72 | all_cost(i_e) = temp_cost;all_tol(i_e) = tol; all_tau(i_e) = tau; all_counter(i_e) = counter; 73 | tau = tau * factor; 74 | F = F_new; 75 | prev_cost = temp_cost; 76 | } else if (tol <= 0 && counter <= 50) { 77 | tau = tau / factor; 78 | } else { 79 | break; 80 | } 81 | } 82 | 83 | // Update probability and projection error 84 | FG = F * G.t(); 85 | all_prob(i_e) = sqrt(accu(square(one / (one + exp(-(FG))) - prob_t))); 86 | all_orth(i_e) = accu((F.t() * F - I) % (F.t() * F - I)); 87 | count += 1; 88 | 89 | } 90 | 91 | info = join_rows(all_tol, all_cost); 92 | info = join_rows(info, all_prob); 93 | info = join_rows(info, all_orth); 94 | 95 | return List::create(_["F"] = F, _["G"] = G, _["info"] = info, _["iter"] = count, 96 | _["final_res"] = all_cost[i_e], _["final_ortho"] = all_orth[i_e]); 97 | } 98 | 99 | 100 | -------------------------------------------------------------------------------- /man/nmf.main.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/main.R 3 | \name{nmf.main} 4 | \alias{nmf.main} 5 | \title{Algorithms for Nonnegative Matrix Factorization (Vanilla)} 6 | \usage{ 7 | nmf.main(X, mode = 1, k, method = "nmf", init = "random", 8 | iter = 200, tol = 1e-05, tau = 0.1, step_bin = 0.05, 9 | step_log = 0.001, factor = 2, sparse_svd = TRUE, seed = 0) 10 | } 11 | \arguments{ 12 | \item{X}{Matrix; An n-by-p matrix with either continous or binary entries.} 13 | 14 | \item{mode}{Integer; Define the type of the input matrix. 1 for continuous, 2 for binary.} 15 | 16 | \item{k}{Clusters; Number of clusters / factors to solve for. Must not exceed the minimum of n or p.} 17 | 18 | \item{method}{String; Determine which NMF algorithm to use. Choices include 'nmf', 'onmf', 'semi', 'sonmf' for 19 | continuous matrices and "so_bin", "log_bin" for binary matrices. Defaults to 'nmf'.} 20 | 21 | \item{init}{String; Determine the type of initialization to use. Choices include 'random', 'kmeans', and 'svd'. Defaults to 'random'.} 22 | 23 | \item{iter}{Integer; Number of iterations to run. Defaults to 200.} 24 | 25 | \item{tol}{Double; Stop the algorithm when the difference between two iterations is less than this specified 26 | threshold. Defaults to 1e-5.} 27 | 28 | \item{tau}{Double; Initial step size for the line search algorithm in sonmf. Defaults to 0.5.} 29 | 30 | \item{step_bin}{Double; Step size for the update algorithm in binary SONMF. Defaults to 0.05.} 31 | 32 | \item{step_log}{Double; Step size for both gradient descent updates for logNMF. Defaults to 0.001. This value should be tuned with caution, 33 | as convergence performance is rather unstable. Recommend to leave it as default.} 34 | 35 | \item{factor}{Double; The factor in which the step size in sonmf is increased/decreased during the line search. Defaults to 2.} 36 | 37 | \item{sparse_svd}{Boolean; Determine whether to use the exact SVD decomposition from \code{svd()} or the fast-truncated SVD 38 | from \code{irlba()} for 'svd' initialization.} 39 | 40 | \item{seed}{Integer; Set seed for reproducibility. Defaults to no seed set.} 41 | } 42 | \value{ 43 | A \code{MatrixFact} object; a list consisting of 44 | \item{F}{The final F matrix} 45 | \item{G}{The final G matrix} 46 | \item{info}{A table with the tolerance, averaged residual, and orthogonal residual(if applicable) at each iteration} 47 | \item{final_res}{A vector with the final factorized residual and orthogonal residual(if applicable) and the number 48 | of iterations} 49 | } 50 | \description{ 51 | Function to apply various methods of NMF on the input matrix for both continuous and binary entries. 52 | } 53 | \details{ 54 | The Non-negative Matrix Factorization aims to factorize/approximate a target matrix X as the product of two lower-rank 55 | matrices, F and G. 56 | } 57 | \examples{ 58 | 59 | ### Create an arbitrary 100-by-100 non-negative matrix to factorize. ### 60 | 61 | # Run Regular NMF with random initialization # 62 | 63 | n = 100 64 | X = matrix(rnorm(n * n, 0, 1), n, n) 65 | X[X < 0] = 0 66 | mode = 1 67 | k = 10 68 | method = "nmf" 69 | init = "random" 70 | iter = 200 71 | tol = 1e-5 72 | 73 | result.1 = nmf.main(X, mode, k, method, init, iter, tol) 74 | 75 | # Run SONMF with SVD initialization using the same X as above # 76 | 77 | method = "sonmf" 78 | init = "svd" 79 | 80 | result.2 = nmf.main(X, mode, k, method, init, iter, tol) 81 | 82 | # Run binary SONMF with SVD initialization for binary X. 83 | 84 | n = 100 85 | X = matrix(rbinom(n^2, 1, runif(n^2, 0.25, 0.75)), n, n) 86 | mode = 2 87 | k = 10 88 | method = "so_bin" 89 | init = "svd" 90 | iter = 200 91 | tol = 1e-6 92 | 93 | result.3 = nmf.main(X, mode, k, method, init, iter, tol) 94 | 95 | } 96 | \references{ 97 | Lee, D. D., & Seung, H. S. (2001). Algorithms for non-negative matrix factorization. In Advances in neural information processing systems (pp. 556-562). 98 | DOI: \url{http://papers.nips.cc/paper/1861-algorithms-for-non-negative-matrix-factorization}. 99 | 100 | Ding, C. H., Li, T., & Jordan, M. I. (2010). Convex and semi-nonnegative matrix factorizations. IEEE transactions on pattern analysis and machine intelligence, 32(1), 45-55. 101 | DOI: \url{http://dx.doi.org/10.1109/TPAMI.2008.277} 102 | 103 | Wen, Z. and Yin, W., "A feasible method for optimization with orthogonality constraints." Mathematical Programming 142.1-2 (2013): 397-434. 104 | DOI: \url{https://doi.org/10.1007/s10107-012-0584-1}. 105 | 106 | Kimura, K., Tanaka, Y., & Kudo, M. (2015, February). A fast hierarchical alternating least squares algorithm for orthogonal nonnegative matrix factorization. In Asian Conference on Machine Learning (pp. 129-141). 107 | DOI: \url{http://proceedings.mlr.press/v39/kimura14.pdf} 108 | 109 | Tomé, A. M., Schachtner, R., Vigneron, V., Puntonet, C. G., & Lang, E. W. (2015). A logistic non-negative matrix factorization approach to binary data sets. Multidimensional Systems and Signal Processing, 26(1), 125-143. 110 | DOI: \url{https://doi.org/10.1007/s11045-013-0240-9} 111 | 112 | Li, J. Y., Zhu, R., Qu, A., Ye, H., & Sun, Z. (2018). Semi-Orthogonal Non-Negative Matrix Factorization. arXiv preprint arXiv:1805.02306. 113 | DOI: \url{https://arxiv.org/abs/1805.02306} 114 | } 115 | -------------------------------------------------------------------------------- /src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | #include 6 | 7 | using namespace Rcpp; 8 | 9 | // NMF 10 | List NMF(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, const double error, const int iter); 11 | RcppExport SEXP _MatrixFact_NMF(SEXP XSEXP, SEXP kSEXP, SEXP F_initSEXP, SEXP G_initSEXP, SEXP errorSEXP, SEXP iterSEXP) { 12 | BEGIN_RCPP 13 | Rcpp::RObject rcpp_result_gen; 14 | Rcpp::RNGScope rcpp_rngScope_gen; 15 | Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP); 16 | Rcpp::traits::input_parameter< const int >::type k(kSEXP); 17 | Rcpp::traits::input_parameter< arma::mat >::type F_init(F_initSEXP); 18 | Rcpp::traits::input_parameter< arma::mat >::type G_init(G_initSEXP); 19 | Rcpp::traits::input_parameter< const double >::type error(errorSEXP); 20 | Rcpp::traits::input_parameter< const int >::type iter(iterSEXP); 21 | rcpp_result_gen = Rcpp::wrap(NMF(X, k, F_init, G_init, error, iter)); 22 | return rcpp_result_gen; 23 | END_RCPP 24 | } 25 | // ONMF 26 | List ONMF(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, const double error, const int iter); 27 | RcppExport SEXP _MatrixFact_ONMF(SEXP XSEXP, SEXP kSEXP, SEXP F_initSEXP, SEXP G_initSEXP, SEXP errorSEXP, SEXP iterSEXP) { 28 | BEGIN_RCPP 29 | Rcpp::RObject rcpp_result_gen; 30 | Rcpp::RNGScope rcpp_rngScope_gen; 31 | Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP); 32 | Rcpp::traits::input_parameter< const int >::type k(kSEXP); 33 | Rcpp::traits::input_parameter< arma::mat >::type F_init(F_initSEXP); 34 | Rcpp::traits::input_parameter< arma::mat >::type G_init(G_initSEXP); 35 | Rcpp::traits::input_parameter< const double >::type error(errorSEXP); 36 | Rcpp::traits::input_parameter< const int >::type iter(iterSEXP); 37 | rcpp_result_gen = Rcpp::wrap(ONMF(X, k, F_init, G_init, error, iter)); 38 | return rcpp_result_gen; 39 | END_RCPP 40 | } 41 | // SO_BIN3 42 | List SO_BIN3(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, const double error, const int iter, double tau, const int factor, double step); 43 | RcppExport SEXP _MatrixFact_SO_BIN3(SEXP XSEXP, SEXP kSEXP, SEXP F_initSEXP, SEXP G_initSEXP, SEXP errorSEXP, SEXP iterSEXP, SEXP tauSEXP, SEXP factorSEXP, SEXP stepSEXP) { 44 | BEGIN_RCPP 45 | Rcpp::RObject rcpp_result_gen; 46 | Rcpp::RNGScope rcpp_rngScope_gen; 47 | Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP); 48 | Rcpp::traits::input_parameter< const int >::type k(kSEXP); 49 | Rcpp::traits::input_parameter< arma::mat >::type F_init(F_initSEXP); 50 | Rcpp::traits::input_parameter< arma::mat >::type G_init(G_initSEXP); 51 | Rcpp::traits::input_parameter< const double >::type error(errorSEXP); 52 | Rcpp::traits::input_parameter< const int >::type iter(iterSEXP); 53 | Rcpp::traits::input_parameter< double >::type tau(tauSEXP); 54 | Rcpp::traits::input_parameter< const int >::type factor(factorSEXP); 55 | Rcpp::traits::input_parameter< double >::type step(stepSEXP); 56 | rcpp_result_gen = Rcpp::wrap(SO_BIN3(X, k, F_init, G_init, error, iter, tau, factor, step)); 57 | return rcpp_result_gen; 58 | END_RCPP 59 | } 60 | // SO_NMF 61 | List SO_NMF(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, const double error, const int iter, double tau, const int factor); 62 | RcppExport SEXP _MatrixFact_SO_NMF(SEXP XSEXP, SEXP kSEXP, SEXP F_initSEXP, SEXP G_initSEXP, SEXP errorSEXP, SEXP iterSEXP, SEXP tauSEXP, SEXP factorSEXP) { 63 | BEGIN_RCPP 64 | Rcpp::RObject rcpp_result_gen; 65 | Rcpp::RNGScope rcpp_rngScope_gen; 66 | Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP); 67 | Rcpp::traits::input_parameter< const int >::type k(kSEXP); 68 | Rcpp::traits::input_parameter< arma::mat >::type F_init(F_initSEXP); 69 | Rcpp::traits::input_parameter< arma::mat >::type G_init(G_initSEXP); 70 | Rcpp::traits::input_parameter< const double >::type error(errorSEXP); 71 | Rcpp::traits::input_parameter< const int >::type iter(iterSEXP); 72 | Rcpp::traits::input_parameter< double >::type tau(tauSEXP); 73 | Rcpp::traits::input_parameter< const int >::type factor(factorSEXP); 74 | rcpp_result_gen = Rcpp::wrap(SO_NMF(X, k, F_init, G_init, error, iter, tau, factor)); 75 | return rcpp_result_gen; 76 | END_RCPP 77 | } 78 | // SemiNMF 79 | List SemiNMF(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, const double error, const int iter); 80 | RcppExport SEXP _MatrixFact_SemiNMF(SEXP XSEXP, SEXP kSEXP, SEXP F_initSEXP, SEXP G_initSEXP, SEXP errorSEXP, SEXP iterSEXP) { 81 | BEGIN_RCPP 82 | Rcpp::RObject rcpp_result_gen; 83 | Rcpp::RNGScope rcpp_rngScope_gen; 84 | Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP); 85 | Rcpp::traits::input_parameter< const int >::type k(kSEXP); 86 | Rcpp::traits::input_parameter< arma::mat >::type F_init(F_initSEXP); 87 | Rcpp::traits::input_parameter< arma::mat >::type G_init(G_initSEXP); 88 | Rcpp::traits::input_parameter< const double >::type error(errorSEXP); 89 | Rcpp::traits::input_parameter< const int >::type iter(iterSEXP); 90 | rcpp_result_gen = Rcpp::wrap(SemiNMF(X, k, F_init, G_init, error, iter)); 91 | return rcpp_result_gen; 92 | END_RCPP 93 | } 94 | // lognmf 95 | List lognmf(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, const double error, const int iter, double tau, double step); 96 | RcppExport SEXP _MatrixFact_lognmf(SEXP XSEXP, SEXP kSEXP, SEXP F_initSEXP, SEXP G_initSEXP, SEXP errorSEXP, SEXP iterSEXP, SEXP tauSEXP, SEXP stepSEXP) { 97 | BEGIN_RCPP 98 | Rcpp::RObject rcpp_result_gen; 99 | Rcpp::RNGScope rcpp_rngScope_gen; 100 | Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP); 101 | Rcpp::traits::input_parameter< const int >::type k(kSEXP); 102 | Rcpp::traits::input_parameter< arma::mat >::type F_init(F_initSEXP); 103 | Rcpp::traits::input_parameter< arma::mat >::type G_init(G_initSEXP); 104 | Rcpp::traits::input_parameter< const double >::type error(errorSEXP); 105 | Rcpp::traits::input_parameter< const int >::type iter(iterSEXP); 106 | Rcpp::traits::input_parameter< double >::type tau(tauSEXP); 107 | Rcpp::traits::input_parameter< double >::type step(stepSEXP); 108 | rcpp_result_gen = Rcpp::wrap(lognmf(X, k, F_init, G_init, error, iter, tau, step)); 109 | return rcpp_result_gen; 110 | END_RCPP 111 | } 112 | // log_test 113 | List log_test(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, arma::mat prob_t, const double error, const int iter, double step); 114 | RcppExport SEXP _MatrixFact_log_test(SEXP XSEXP, SEXP kSEXP, SEXP F_initSEXP, SEXP G_initSEXP, SEXP prob_tSEXP, SEXP errorSEXP, SEXP iterSEXP, SEXP stepSEXP) { 115 | BEGIN_RCPP 116 | Rcpp::RObject rcpp_result_gen; 117 | Rcpp::RNGScope rcpp_rngScope_gen; 118 | Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP); 119 | Rcpp::traits::input_parameter< const int >::type k(kSEXP); 120 | Rcpp::traits::input_parameter< arma::mat >::type F_init(F_initSEXP); 121 | Rcpp::traits::input_parameter< arma::mat >::type G_init(G_initSEXP); 122 | Rcpp::traits::input_parameter< arma::mat >::type prob_t(prob_tSEXP); 123 | Rcpp::traits::input_parameter< const double >::type error(errorSEXP); 124 | Rcpp::traits::input_parameter< const int >::type iter(iterSEXP); 125 | Rcpp::traits::input_parameter< double >::type step(stepSEXP); 126 | rcpp_result_gen = Rcpp::wrap(log_test(X, k, F_init, G_init, prob_t, error, iter, step)); 127 | return rcpp_result_gen; 128 | END_RCPP 129 | } 130 | // NMF_LOG 131 | List NMF_LOG(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, const double error, const int iter, double step); 132 | RcppExport SEXP _MatrixFact_NMF_LOG(SEXP XSEXP, SEXP kSEXP, SEXP F_initSEXP, SEXP G_initSEXP, SEXP errorSEXP, SEXP iterSEXP, SEXP stepSEXP) { 133 | BEGIN_RCPP 134 | Rcpp::RObject rcpp_result_gen; 135 | Rcpp::RNGScope rcpp_rngScope_gen; 136 | Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP); 137 | Rcpp::traits::input_parameter< const int >::type k(kSEXP); 138 | Rcpp::traits::input_parameter< arma::mat >::type F_init(F_initSEXP); 139 | Rcpp::traits::input_parameter< arma::mat >::type G_init(G_initSEXP); 140 | Rcpp::traits::input_parameter< const double >::type error(errorSEXP); 141 | Rcpp::traits::input_parameter< const int >::type iter(iterSEXP); 142 | Rcpp::traits::input_parameter< double >::type step(stepSEXP); 143 | rcpp_result_gen = Rcpp::wrap(NMF_LOG(X, k, F_init, G_init, error, iter, step)); 144 | return rcpp_result_gen; 145 | END_RCPP 146 | } 147 | // sobin_test 148 | List sobin_test(arma::mat X, const int k, arma::mat F_init, arma::mat G_init, arma::mat prob_t, const double error, const int iter, double tau, const int factor, double step); 149 | RcppExport SEXP _MatrixFact_sobin_test(SEXP XSEXP, SEXP kSEXP, SEXP F_initSEXP, SEXP G_initSEXP, SEXP prob_tSEXP, SEXP errorSEXP, SEXP iterSEXP, SEXP tauSEXP, SEXP factorSEXP, SEXP stepSEXP) { 150 | BEGIN_RCPP 151 | Rcpp::RObject rcpp_result_gen; 152 | Rcpp::RNGScope rcpp_rngScope_gen; 153 | Rcpp::traits::input_parameter< arma::mat >::type X(XSEXP); 154 | Rcpp::traits::input_parameter< const int >::type k(kSEXP); 155 | Rcpp::traits::input_parameter< arma::mat >::type F_init(F_initSEXP); 156 | Rcpp::traits::input_parameter< arma::mat >::type G_init(G_initSEXP); 157 | Rcpp::traits::input_parameter< arma::mat >::type prob_t(prob_tSEXP); 158 | Rcpp::traits::input_parameter< const double >::type error(errorSEXP); 159 | Rcpp::traits::input_parameter< const int >::type iter(iterSEXP); 160 | Rcpp::traits::input_parameter< double >::type tau(tauSEXP); 161 | Rcpp::traits::input_parameter< const int >::type factor(factorSEXP); 162 | Rcpp::traits::input_parameter< double >::type step(stepSEXP); 163 | rcpp_result_gen = Rcpp::wrap(sobin_test(X, k, F_init, G_init, prob_t, error, iter, tau, factor, step)); 164 | return rcpp_result_gen; 165 | END_RCPP 166 | } 167 | 168 | static const R_CallMethodDef CallEntries[] = { 169 | {"_MatrixFact_NMF", (DL_FUNC) &_MatrixFact_NMF, 6}, 170 | {"_MatrixFact_ONMF", (DL_FUNC) &_MatrixFact_ONMF, 6}, 171 | {"_MatrixFact_SO_BIN3", (DL_FUNC) &_MatrixFact_SO_BIN3, 9}, 172 | {"_MatrixFact_SO_NMF", (DL_FUNC) &_MatrixFact_SO_NMF, 8}, 173 | {"_MatrixFact_SemiNMF", (DL_FUNC) &_MatrixFact_SemiNMF, 6}, 174 | {"_MatrixFact_lognmf", (DL_FUNC) &_MatrixFact_lognmf, 8}, 175 | {"_MatrixFact_log_test", (DL_FUNC) &_MatrixFact_log_test, 8}, 176 | {"_MatrixFact_NMF_LOG", (DL_FUNC) &_MatrixFact_NMF_LOG, 7}, 177 | {"_MatrixFact_sobin_test", (DL_FUNC) &_MatrixFact_sobin_test, 10}, 178 | {NULL, NULL, 0} 179 | }; 180 | 181 | RcppExport void R_init_MatrixFact(DllInfo *dll) { 182 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 183 | R_useDynamicSymbols(dll, FALSE); 184 | } 185 | -------------------------------------------------------------------------------- /.Rproj.user/16D545D7/cpp-definition-cache: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "definitions" : [ 4 | { 5 | "column" : 6, 6 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/Lee_NMF.cpp", 7 | "kind" : 6, 8 | "line" : 11, 9 | "name" : "NMF(arma::mat, const int, arma::mat, arma::mat, const double, const int)", 10 | "parent_name" : "", 11 | "usr" : "c:@F@NMF#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#" 12 | } 13 | ], 14 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/Lee_NMF.cpp", 15 | "file_last_write" : 1541291927 16 | }, 17 | { 18 | "definitions" : [ 19 | { 20 | "column" : 6, 21 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/ONMF.cpp", 22 | "kind" : 6, 23 | "line" : 11, 24 | "name" : "ONMF(arma::mat, const int, arma::mat, arma::mat, const double, const int)", 25 | "parent_name" : "", 26 | "usr" : "c:@F@ONMF#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#" 27 | } 28 | ], 29 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/ONMF.cpp", 30 | "file_last_write" : 1537299833 31 | }, 32 | { 33 | "definitions" : [ 34 | { 35 | "column" : 6, 36 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/SO_Bin3.cpp", 37 | "kind" : 6, 38 | "line" : 11, 39 | "name" : "SO_BIN3(arma::mat, const int, arma::mat, arma::mat, const double, const int, double, const int, double)", 40 | "parent_name" : "", 41 | "usr" : "c:@F@SO_BIN3#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#d#1I#d#" 42 | } 43 | ], 44 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/SO_Bin3.cpp", 45 | "file_last_write" : 1558815776 46 | }, 47 | { 48 | "definitions" : [ 49 | { 50 | "column" : 6, 51 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/SO_NMF.cpp", 52 | "kind" : 6, 53 | "line" : 11, 54 | "name" : "SO_NMF(arma::mat, const int, arma::mat, arma::mat, const double, const int, double, const int)", 55 | "parent_name" : "", 56 | "usr" : "c:@F@SO_NMF#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#d#1I#" 57 | } 58 | ], 59 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/SO_NMF.cpp", 60 | "file_last_write" : 1558812526 61 | }, 62 | { 63 | "definitions" : [ 64 | { 65 | "column" : 6, 66 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/SemiNMF.cpp", 67 | "kind" : 6, 68 | "line" : 11, 69 | "name" : "SemiNMF(arma::mat, const int, arma::mat, arma::mat, const double, const int)", 70 | "parent_name" : "", 71 | "usr" : "c:@F@SemiNMF#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#" 72 | } 73 | ], 74 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/SemiNMF.cpp", 75 | "file_last_write" : 1537299842 76 | }, 77 | { 78 | "definitions" : [ 79 | { 80 | "column" : 6, 81 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/lognmf.cpp", 82 | "kind" : 6, 83 | "line" : 11, 84 | "name" : "lognmf(arma::mat, const int, arma::mat, arma::mat, const double, const int, double, double)", 85 | "parent_name" : "", 86 | "usr" : "c:@F@lognmf#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#d#d#" 87 | } 88 | ], 89 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/lognmf.cpp", 90 | "file_last_write" : 1539833003 91 | }, 92 | { 93 | "definitions" : [ 94 | { 95 | "column" : 6, 96 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/lognmf_test.cpp", 97 | "kind" : 6, 98 | "line" : 11, 99 | "name" : "log_test(arma::mat, const int, arma::mat, arma::mat, arma::mat, const double, const int, double)", 100 | "parent_name" : "", 101 | "usr" : "c:@F@log_test#$@N@arma@C@Mat>#d#1I#S0_#S0_#S0_#1d#1I#d#" 102 | } 103 | ], 104 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/lognmf_test.cpp", 105 | "file_last_write" : 1540087950 106 | }, 107 | { 108 | "definitions" : [ 109 | { 110 | "column" : 6, 111 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/nmf_log.cpp", 112 | "kind" : 6, 113 | "line" : 11, 114 | "name" : "NMF_LOG(arma::mat, const int, arma::mat, arma::mat, const double, const int, double)", 115 | "parent_name" : "", 116 | "usr" : "c:@F@NMF_LOG#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#d#" 117 | } 118 | ], 119 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/nmf_log.cpp", 120 | "file_last_write" : 1539828651 121 | }, 122 | { 123 | "definitions" : [ 124 | { 125 | "column" : 6, 126 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/sobin_test.cpp", 127 | "kind" : 6, 128 | "line" : 11, 129 | "name" : "sobin_test(arma::mat, const int, arma::mat, arma::mat, arma::mat, const double, const int, double, const int, double)", 130 | "parent_name" : "", 131 | "usr" : "c:@F@sobin_test#$@N@arma@C@Mat>#d#1I#S0_#S0_#S0_#1d#1I#d#1I#d#" 132 | } 133 | ], 134 | "file" : "C:/Users/yuton/Dropbox/Jack Li/JASA Submission/MatrixFact/src/sobin_test.cpp", 135 | "file_last_write" : 1540087996 136 | }, 137 | { 138 | "definitions" : [ 139 | { 140 | "column" : 6, 141 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/Lee_NMF.cpp", 142 | "kind" : 6, 143 | "line" : 11, 144 | "name" : "NMF(arma::mat, const int, arma::mat, arma::mat, const double, const int)", 145 | "parent_name" : "", 146 | "usr" : "c:@F@NMF#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#" 147 | } 148 | ], 149 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/Lee_NMF.cpp", 150 | "file_last_write" : 1541291927 151 | }, 152 | { 153 | "definitions" : [ 154 | { 155 | "column" : 6, 156 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/ONMF.cpp", 157 | "kind" : 6, 158 | "line" : 11, 159 | "name" : "ONMF(arma::mat, const int, arma::mat, arma::mat, const double, const int)", 160 | "parent_name" : "", 161 | "usr" : "c:@F@ONMF#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#" 162 | } 163 | ], 164 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/ONMF.cpp", 165 | "file_last_write" : 1537299833 166 | }, 167 | { 168 | "definitions" : [ 169 | { 170 | "column" : 6, 171 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/SO_Bin3.cpp", 172 | "kind" : 6, 173 | "line" : 11, 174 | "name" : "SO_BIN3(arma::mat, const int, arma::mat, arma::mat, const double, const int, double, const int, double)", 175 | "parent_name" : "", 176 | "usr" : "c:@F@SO_BIN3#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#d#1I#d#" 177 | } 178 | ], 179 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/SO_Bin3.cpp", 180 | "file_last_write" : 1539917550 181 | }, 182 | { 183 | "definitions" : [ 184 | { 185 | "column" : 6, 186 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/SO_NMF.cpp", 187 | "kind" : 6, 188 | "line" : 11, 189 | "name" : "SO_NMF(arma::mat, const int, arma::mat, arma::mat, const double, const int, double, const int)", 190 | "parent_name" : "", 191 | "usr" : "c:@F@SO_NMF#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#d#1I#" 192 | } 193 | ], 194 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/SO_NMF.cpp", 195 | "file_last_write" : 1537301727 196 | }, 197 | { 198 | "definitions" : [ 199 | { 200 | "column" : 6, 201 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/SemiNMF.cpp", 202 | "kind" : 6, 203 | "line" : 11, 204 | "name" : "SemiNMF(arma::mat, const int, arma::mat, arma::mat, const double, const int)", 205 | "parent_name" : "", 206 | "usr" : "c:@F@SemiNMF#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#" 207 | } 208 | ], 209 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/SemiNMF.cpp", 210 | "file_last_write" : 1537299842 211 | }, 212 | { 213 | "definitions" : [ 214 | { 215 | "column" : 6, 216 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/lognmf.cpp", 217 | "kind" : 6, 218 | "line" : 11, 219 | "name" : "lognmf(arma::mat, const int, arma::mat, arma::mat, const double, const int, double, double)", 220 | "parent_name" : "", 221 | "usr" : "c:@F@lognmf#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#d#d#" 222 | } 223 | ], 224 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/lognmf.cpp", 225 | "file_last_write" : 1539833003 226 | }, 227 | { 228 | "definitions" : [ 229 | { 230 | "column" : 6, 231 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/nmf_log.cpp", 232 | "kind" : 6, 233 | "line" : 11, 234 | "name" : "NMF_LOG(arma::mat, const int, arma::mat, arma::mat, const double, const int, double)", 235 | "parent_name" : "", 236 | "usr" : "c:@F@NMF_LOG#$@N@arma@C@Mat>#d#1I#S0_#S0_#1d#1I#d#" 237 | } 238 | ], 239 | "file" : "C:/Users/yuton/Dropbox/packages/MatrixFact/src/nmf_log.cpp", 240 | "file_last_write" : 1539828651 241 | } 242 | ] -------------------------------------------------------------------------------- /R/main.R: -------------------------------------------------------------------------------- 1 | ########################################################################################## 2 | ################################ Main Function to Perform NMF ############################ 3 | 4 | #' 5 | #' Algorithms for Nonnegative Matrix Factorization (Vanilla) 6 | #' 7 | #' Function to apply various methods of NMF on the input matrix for both continuous and binary entries. 8 | #' 9 | #' @useDynLib MatrixFact, .registration = TRUE 10 | #' @importFrom Rcpp evalCpp 11 | #' @import pracma 12 | #' @import irlba 13 | #' 14 | #' @param X Matrix; An n-by-p matrix with either continous or binary entries. 15 | #' @param mode Integer; Define the type of the input matrix. 1 for continuous, 2 for binary. 16 | #' @param k Clusters; Number of clusters / factors to solve for. Must not exceed the minimum of n or p. 17 | #' @param method String; Determine which NMF algorithm to use. Choices include 'nmf', 'onmf', 'semi', 'sonmf' for 18 | #' continuous matrices and "so_bin", "log_bin" for binary matrices. Defaults to 'nmf'. 19 | #' @param init String; Determine the type of initialization to use. Choices include 'random', 'kmeans', and 'svd'. Defaults to 'random'. 20 | #' @param iter Integer; Number of iterations to run. Defaults to 200. 21 | #' @param tol Double; Stop the algorithm when the difference between two iterations is less than this specified 22 | #' threshold. Defaults to 1e-5. 23 | #' @param tau Double; Initial step size for the line search algorithm in sonmf. Defaults to 0.5. 24 | #' @param step_bin Double; Step size for the update algorithm in binary SONMF. Defaults to 0.05. 25 | #' @param step_log Double; Step size for both gradient descent updates for logNMF. Defaults to 0.001. This value should be tuned with caution, 26 | #' as convergence performance is rather unstable. Recommend to leave it as default. 27 | #' @param factor Double; The factor in which the step size in sonmf is increased/decreased during the line search. Defaults to 2. 28 | #' @param sparse_svd Boolean; Determine whether to use the exact SVD decomposition from \code{svd()} or the fast-truncated SVD 29 | #' from \code{irlba()} for 'svd' initialization. 30 | #' @param seed Integer; Set seed for reproducibility. Defaults to no seed set. 31 | #' 32 | #' @details The Non-negative Matrix Factorization aims to factorize/approximate a target matrix X as the product of two lower-rank 33 | #' matrices, F and G. 34 | #' 35 | #' @return A \code{MatrixFact} object; a list consisting of 36 | #' \item{F}{The final F matrix} 37 | #' \item{G}{The final G matrix} 38 | #' \item{info}{A table with the tolerance, averaged residual, and orthogonal residual(if applicable) at each iteration} 39 | #' \item{final_res}{A vector with the final factorized residual and orthogonal residual(if applicable) and the number 40 | #' of iterations} 41 | #' 42 | #' @references Lee, D. D., & Seung, H. S. (2001). Algorithms for non-negative matrix factorization. In Advances in neural information processing systems (pp. 556-562). 43 | #' DOI: \url{http://papers.nips.cc/paper/1861-algorithms-for-non-negative-matrix-factorization}. 44 | #' @references Ding, C. H., Li, T., & Jordan, M. I. (2010). Convex and semi-nonnegative matrix factorizations. IEEE transactions on pattern analysis and machine intelligence, 32(1), 45-55. 45 | #' DOI: \url{http://dx.doi.org/10.1109/TPAMI.2008.277} 46 | #' @references Wen, Z. and Yin, W., "A feasible method for optimization with orthogonality constraints." Mathematical Programming 142.1-2 (2013): 397-434. 47 | #' DOI: \url{https://doi.org/10.1007/s10107-012-0584-1}. 48 | #' @references Kimura, K., Tanaka, Y., & Kudo, M. (2015, February). A fast hierarchical alternating least squares algorithm for orthogonal nonnegative matrix factorization. In Asian Conference on Machine Learning (pp. 129-141). 49 | #' DOI: \url{http://proceedings.mlr.press/v39/kimura14.pdf} 50 | #' @references Tomé, A. M., Schachtner, R., Vigneron, V., Puntonet, C. G., & Lang, E. W. (2015). A logistic non-negative matrix factorization approach to binary data sets. Multidimensional Systems and Signal Processing, 26(1), 125-143. 51 | #' DOI: \url{https://doi.org/10.1007/s11045-013-0240-9} 52 | #' @references Li, J. Y., Zhu, R., Qu, A., Ye, H., & Sun, Z. (2018). Semi-Orthogonal Non-Negative Matrix Factorization. arXiv preprint arXiv:1805.02306. 53 | #' DOI: \url{https://arxiv.org/abs/1805.02306} 54 | #' 55 | #' 56 | #' @examples 57 | #' 58 | #' ### Create an arbitrary 100-by-100 non-negative matrix to factorize. ### 59 | #' 60 | #' # Run Regular NMF with random initialization # 61 | #' 62 | #' n = 100 63 | #' X = matrix(rnorm(n * n, 0, 1), n, n) 64 | #' X[X < 0] = 0 65 | #' mode = 1 66 | #' k = 10 67 | #' method = "nmf" 68 | #' init = "random" 69 | #' iter = 200 70 | #' tol = 1e-5 71 | #' 72 | #' result.1 = nmf.main(X, mode, k, method, init, iter, tol) 73 | #' 74 | #' # Run SONMF with SVD initialization using the same X as above # 75 | #' 76 | #' method = "sonmf" 77 | #' init = "svd" 78 | #' 79 | #' result.2 = nmf.main(X, mode, k, method, init, iter, tol) 80 | #' 81 | #' # Run binary SONMF with SVD initialization for binary X. 82 | #' 83 | #' n = 100 84 | #' X = matrix(rbinom(n^2, 1, runif(n^2, 0.25, 0.75)), n, n) 85 | #' mode = 2 86 | #' k = 10 87 | #' method = "so_bin" 88 | #' init = "svd" 89 | #' iter = 200 90 | #' tol = 1e-6 91 | #' 92 | #' result.3 = nmf.main(X, mode, k, method, init, iter, tol) 93 | #' 94 | #' @export 95 | 96 | nmf.main = function(X, mode = 1, k, method = "nmf", init = "random", iter = 200, tol = 1e-5, tau = 0.1, 97 | step_bin = 0.05, step_log = 0.001, factor = 2, sparse_svd = TRUE, seed = 0) { 98 | 99 | # Convert input X into matrix 100 | X = as.matrix(X) 101 | 102 | # Check if any input parameter is invalid and prints either an error or warning message accordingly 103 | error.mess(X, mode, k, method, init, iter, tol, tau, step_bin, step_log, seed) 104 | 105 | # Set seed for reproducibility 106 | if (seed > 0) { 107 | set.seed(seed) 108 | } 109 | 110 | # Initialize basic parameters 111 | n = nrow(X); p = ncol(X) 112 | eps = 1e-10 113 | 114 | # Initialization for F and G 115 | if (init == "random") { 116 | 117 | if (method != "sonmf") { 118 | F.init = matrix(rnorm(n * k, 0, 1), n, k) 119 | } else { 120 | F.init = randortho(n)[,1:k] 121 | warning("Random initialization for sonmf is inefficient. Recommend using 'svd' initilization instead.") 122 | } 123 | G.init = matrix(rnorm(p * k, 0, 1), p, k) 124 | 125 | # K-means initialization 126 | } else if (init == "kmeans") { 127 | 128 | fit = kmeans(t(X), k) 129 | G.kmeans = matrix(0, ncol(X), k) 130 | for(i in 1:length(fit$cluster)) { 131 | G.kmeans[i, fit$cluster[i]] = 1 132 | } 133 | G.init = G.kmeans + 0.2 134 | F.init = fit$centers 135 | 136 | # SVD-based initialization 137 | } else { 138 | 139 | # Initialize with svd 140 | if (sparse_svd) { svd.X = irlba(as.matrix(X), nu = k, nv = k) } else { svd.X = svd(as.matrix(X), nu = k, nv = k) } 141 | 142 | # Set up F init, force to be the same sign for consistency 143 | if (svd.X$u[1,1] < 0) {F.init = svd.X$u[,1:k] * -1} else {F.init = svd.X$u[,1:k]} 144 | 145 | G.init = t(X) %*% F.init 146 | } 147 | 148 | F.init = as.matrix(F.init) 149 | G.init = as.matrix(G.init) 150 | 151 | # Continuous Matrix 152 | if (mode == 1) { 153 | 154 | # Set initialization of G to be non-negative 155 | G.init[G.init < 0] = eps 156 | 157 | # NMF 158 | if (method == "nmf") { 159 | F.init[F.init < 0] = eps 160 | solution = NMF(X, k, F.init, G.init, tol, iter) 161 | 162 | # Semi NMF 163 | } else if (method == "semi") { 164 | G.init = G.init + 0.2 165 | F.init = X %*% G.init %*% pinv(t(G.init) %*% G.init) 166 | solution = SemiNMF(X, k, F.init, G.init, tol, iter) 167 | 168 | # ONMF 169 | } else if (method == "onmf") { 170 | F.init[F.init < 0] = 0 171 | solution = ONMF(X, k, F.init, G.init, tol, iter) 172 | 173 | # SONMF 174 | } else { 175 | 176 | if (init == "kmeans") { 177 | stop("Use random or SVD initialization for SONMF.") 178 | } 179 | 180 | solution = SO_NMF(X, k, F.init, G.init, tol, iter, tau, 2) 181 | } 182 | 183 | 184 | # Matrix Factorization for binary matrices 185 | } else { 186 | 187 | 188 | # Binary SONMF 189 | if (method == "so_bin") { 190 | G.init[G.init < 0] = eps; 191 | solution = SO_BIN3(X, k, F.init, G.init, tol, iter, tau, factor, step_bin) 192 | 193 | # Tome's log_bin 194 | } else if (method == "log_nmf") { 195 | F.init[F.init < 0] = eps; 196 | solution = NMF_LOG(X, k, F.init, G.init, tol, iter, step_log) 197 | 198 | } else if (method == "line_lognmf") { 199 | F.init[F.init < 0] = eps 200 | solution = lognmf(X, k, F.init, G.init, tol, iter, tau, step_log) 201 | } 202 | 203 | } 204 | 205 | # Force all elements beneath a threshold to 0. 206 | solution$F[which(abs(solution$F) <= 1e-10)] = 0 207 | solution$G[which(abs(solution$G) <= 1e-10)] = 0 208 | 209 | # Reorganize result and return an NMF object 210 | solution = organize(method, solution) 211 | 212 | return(solution) 213 | 214 | } 215 | 216 | ############################################################# 217 | # Error function 218 | # 219 | # Outputs error and warning messages 220 | # This function examines the input parameters and output corresponding error or warning message. 221 | 222 | error.mess = function(X, mode, k, method, init, iter, tol, tau, step_bin, step_log, seed) { 223 | 224 | ### X ### 225 | if(!is.matrix(X)) { stop("X must be a matrix.") } # Input X is not a matrix. 226 | if(!is.numeric(X)) { stop("X must be numerical.") } # Input X is not a numerical matrix. 227 | 228 | ### mode ### 229 | if (!(mode %in% c("1","2"))) { 230 | stop("Input mode must be either '1' for continuous matrix and '2' for binary matrix.") 231 | } 232 | 233 | ### k ### 234 | if(k < 0) { stop("The input k is negative. k must be a positive value.") } 235 | if(k > nrow(X) | k > ncol(X)) { stop("k must not be larger than max[nrow(X), ncol(X)].") } 236 | 237 | 238 | ### method ### 239 | 240 | # The input method is not one of the six implemented methods. 241 | if (!(method %in% c("nmf","onmf","semi","sonmf","so_bin","log_nmf"))) { 242 | stop ("Input method needs to be either 'nmf','onmf','semi','sonmf','so_bin or 'log_nmf'.") 243 | } 244 | 245 | # Input method does not match with the input mode. For example, a method for continuous matrix 246 | if (mode == 1) { 247 | if (method %in% c("so_bin","log_nmf")) { 248 | stop("Input mode is for continuous matrix but method is for binary matrix. Please input a method for continuous matrix.") 249 | } 250 | } else if (mode == 2) { 251 | if (method %in% c("nmf","onmf","semi","sonmf")) { 252 | stop("Input mode is for binary matrix but method is for continuous matrix. Please input a method for binary matrix.") 253 | } 254 | } 255 | 256 | ### init ### 257 | if (!(init %in% c("random","kmeans","svd"))) { 258 | stop("Input initialization needs to be either 'random','kmeans', or 'svd'.") 259 | } 260 | 261 | ### iter ### 262 | if (iter < 0) { 263 | stop("Number of iterations set to run must be a positive number.") 264 | } 265 | 266 | ### tol ### 267 | if (tol <= 0) { 268 | stop("Convergence threshold needs to be a positive number.") 269 | } else if (tol > 0.1) { 270 | warning("Convergence threshold is too large. Algorithm may not have converged. 271 | It is recommended to set this positive value to at most 0.0001.") 272 | } 273 | 274 | ### tau ### 275 | if (tau < 0) { 276 | stop("Step size for sonmf needs to be positive value.") 277 | } else if (tau > 2) { 278 | warning("Step size for sonmf is too large. Please choose a smaller step size.") 279 | } 280 | 281 | ### step_bin ### 282 | if (step_bin < 0) { 283 | stop("Step size for the update of G (so_bin) needs to be a positive value.") 284 | } 285 | if (method == 'so_bin') { 286 | if (step_bin > 0.5) { 287 | warning('The input step size is quite large. Please choose a smaller step size for more stable performance.') 288 | } else if (step_bin > 1) { 289 | stop('The input step size is too large. Convergence issue may arise. Please choose a smaller step size.') 290 | } 291 | 292 | } else if (method == "log_nmf") { 293 | if (step_log > 0.001) { 294 | warning("The input step size quite large. Please choose a smaller step size for more stable performance.") 295 | } else if(step_log > 0.01) { 296 | stop('The input step size is too large. Convergence issue may arise. Please choose a smaller step size.') 297 | } 298 | } 299 | } 300 | 301 | ########################################################### 302 | # Reorganize result from NMF and returns an NMF object 303 | 304 | organize = function(method, nmf.res) { 305 | 306 | 307 | # For methods with orthogonal residuals 308 | if (method %in% c("sonmf", "onmf", "so_bin")) { 309 | 310 | iteration_info = nmf.res$info[1:nmf.res$iter, 1:3] 311 | colnames(iteration_info) = c("Tolerance", "Averaged Residual", "Orthogonal Residual") 312 | info = c(nmf.res$final_res, nmf.res$final_orth, floor(nmf.res$iter)) 313 | names(info) = c("Averaged Residual", "Orthogonal Residual", "Iterations") 314 | 315 | # For methods without orthogonal residuals 316 | } else { 317 | 318 | iteration_info = nmf.res$info[1:nmf.res$iter, 1:2] 319 | colnames(iteration_info) = c("Tolerance", "Averaged Residual") 320 | info = c(nmf.res$final_res, floor(nmf.res$iter)) 321 | names(info) = c("Averaged Residual", "Iterations") 322 | 323 | } 324 | 325 | res = list(F = nmf.res$F, G = nmf.res$G, info = iteration_info, final_result = info) 326 | class(res) = c("F", "G", "info", "final_result") 327 | 328 | return(res) 329 | } 330 | 331 | ############################################################ 332 | #' Function Specific for Binary Simulation 333 | #' 334 | #' This function is for simulation purposes only. 335 | #' 336 | #' This function is the same as nmf.main(), with the additional parameter of an input 337 | #' true probability matrix for simulation purpose. This is not applicable in actual 338 | #' scenarios, since there is no way of knowing the true underlying probability matrix 339 | #' beforehand. 340 | #' 341 | #' @useDynLib MatrixFact, .registration = TRUE 342 | #' @importFrom Rcpp evalCpp 343 | #' @import pracma 344 | #' @import irlba 345 | #' 346 | #' @export 347 | 348 | bin.test = function(X, k, F.init, G.init, method, prob, iter = 500, tol = 1e-5, tau = 0.5, 349 | step_bin = 0.05, step_log = 0.001, factor = 2) { 350 | 351 | if (method == "so_bin") { 352 | res = sobin_test(X, k, F.init, G.init, prob, tol, iter, tau, factor, step_bin) 353 | } else if (method == "log_nmf") { 354 | res = log_test(X, k, F.init, G.init, prob, tol, iter, step_log) 355 | } else { 356 | stop("Input method must be either 'so_bin' or 'log_nmf'.") 357 | } 358 | return (res) 359 | } 360 | 361 | -------------------------------------------------------------------------------- /.Rhistory: -------------------------------------------------------------------------------- 1 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 2 | library(MatrixFact) 3 | # Run SONMF with svd initialization 4 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 5 | # Run NMF with random initialization 6 | nmf.X = nmf.main(X, mode, k, "nmf", "random", iter, tol); nmf.X 7 | # Run ONMF with random initialization 8 | onmf.X = nmf.main(X, mode, k, "onmf", "random", iter, tol); onmf.X 9 | # Run Semi-NMF with kmeans initialization 10 | semi.X = nmf.main(X, mode, k, "semi", "kmeans", iter, tol); semi.X 11 | library(MatrixFact) 12 | n = 100 13 | X = matrix(rnorm(n^2, 0, 1), n, n) # Construct a 100-by-100 matrix with random elements 14 | X[X < 0] = 0 # Truncate all negative values to create a non-negative matix 15 | mode = 1 # Set mode to 1 for matrix with continuous entries 16 | k = 10 # Set target factorization rank to be k 17 | iter = 200 # Set number of iterations to be 200 18 | tol = 1e-5 # Set convergence threshold to 1e-5 19 | # Run SONMF with svd initialization 20 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 21 | # Run NMF with random initialization 22 | nmf.X = nmf.main(X, mode, k, "nmf", "random", iter, tol); nmf.X 23 | # Run ONMF with random initialization 24 | onmf.X = nmf.main(X, mode, k, "onmf", "random", iter, tol); onmf.X 25 | # Run Semi-NMF with kmeans initialization 26 | semi.X = nmf.main(X, mode, k, "semi", "kmeans", iter, tol); semi.X 27 | # Run SONMF with svd initialization 28 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 29 | # Run NMF with random initialization 30 | nmf.X = nmf.main(X, mode, k, "nmf", "random", iter, tol); nmf.X 31 | # Run ONMF with random initialization 32 | onmf.X = nmf.main(X, mode, k, "onmf", "random", iter, tol); onmf.X 33 | X.bin = matrix(rbinom(n^2, 1, runif(n^2, 0.25, 0.75)), n, n) # Construct a 100-by-100 matrix with binary elements 34 | mode.2 = 2 35 | # Run Binary SONMF with svd initialization 36 | sobin.X = nmf.main(X.bin, mode.2, k, "so_bin", "svd", iter, tol); sobin.X 37 | # Run logNMF with random initialization 38 | lognmf.X = nmf.main(X.bin, mode.2, k, "log_nmf", "random", iter, tol); lognmf.X 39 | G.init[G.init < 0] = eps; 40 | solution = SO_BIN3(X, k, F.init, G.init, tol, iter, tau, factor, step_bin) 41 | X = X.bin 42 | # Convert input X into matrix 43 | X = as.matrix(X) 44 | # Check if any input parameter is invalid and prints either an error or warning message accordingly 45 | error.mess(X, mode, k, method, init, iter, tol, tau, step_bin, step_log, seed) 46 | # Initialize basic parameters 47 | n = nrow(X); p = ncol(X) 48 | eps = 1e-10 49 | F.init = matrix(rnorm(n * k, 0, 1), n, k) 50 | G.init = matrix(rnorm(p * k, 0, 1), p, k) 51 | G.init[G.init < 0] = eps; 52 | solution = SO_BIN3(X, k, F.init, G.init, tol, iter, tau, factor, step_bin) 53 | k 54 | F.init 55 | G.init 56 | tol 57 | iter 58 | tau 59 | factor 60 | factor = 2 61 | step_bin 62 | solution = SO_BIN3(X, k, F.init, G.init, tol, iter, tau, factor, step_bin) 63 | solution 64 | library(MatrixFact) 65 | # Run Binary SONMF with svd initialization 66 | sobin.X = nmf.main(X.bin, mode.2, k, "so_bin", "svd", iter, tol); sobin.X 67 | # Run logNMF with random initialization 68 | lognmf.X = nmf.main(X.bin, mode.2, k, "log_nmf", "random", iter, tol); lognmf.X 69 | # Run Binary SONMF with svd initialization 70 | sobin.X = nmf.main(X.bin, mode.2, k, "so_bin", "svd", iter, tol); sobin.X 71 | # Run logNMF with random initialization 72 | lognmf.X = nmf.main(X.bin, mode.2, k, "log_nmf", "random", iter, tol); lognmf.X 73 | library(MatrixFact) 74 | # Run SONMF with svd initialization 75 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 76 | library(MatrixFact) 77 | # Run SONMF with svd initialization 78 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 79 | # Run NMF with random initialization 80 | nmf.X = nmf.main(X, mode, k, "nmf", "random", iter, tol); nmf.X 81 | # Run ONMF with random initialization 82 | onmf.X = nmf.main(X, mode, k, "onmf", "random", iter, tol); onmf.X 83 | # Run Semi-NMF with kmeans initialization 84 | semi.X = nmf.main(X, mode, k, "semi", "kmeans", iter, tol); semi.X 85 | # Run SONMF with svd initialization 86 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 87 | library(MatrixFact) 88 | # Run SONMF with svd initialization 89 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 90 | # Run NMF with random initialization 91 | nmf.X = nmf.main(X, mode, k, "nmf", "random", iter, tol); nmf.X 92 | # Run ONMF with random initialization 93 | onmf.X = nmf.main(X, mode, k, "onmf", "random", iter, tol); onmf.X 94 | # Run Semi-NMF with kmeans initialization 95 | semi.X = nmf.main(X, mode, k, "semi", "kmeans", iter, tol); semi.X 96 | # Run SONMF with svd initialization 97 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 98 | # Run Semi-NMF with kmeans initialization 99 | semi.X = nmf.main(X, mode, k, "semi", "kmeans", iter, tol); semi.X 100 | # Run SONMF with svd initialization 101 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 102 | n = 100 103 | X = matrix(rnorm(n^2, 0, 1), n, n) # Construct a 100-by-100 matrix with random elements 104 | X[X < 0] = 0 # Truncate all negative values to create a non-negative matix 105 | mode = 1 # Set mode to 1 for matrix with continuous entries 106 | k = 10 # Set target factorization rank to be k 107 | iter = 200 # Set number of iterations to be 200 108 | tol = 1e-5 109 | # Run SONMF with svd initialization 110 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 111 | # Run NMF with random initialization 112 | nmf.X = nmf.main(X, mode, k, "nmf", "random", iter, tol); nmf.X 113 | # Run ONMF with random initialization 114 | onmf.X = nmf.main(X, mode, k, "onmf", "random", iter, tol); onmf.X 115 | # Run Semi-NMF with kmeans initialization 116 | semi.X = nmf.main(X, mode, k, "semi", "kmeans", iter, tol); semi.X 117 | # Run SONMF with svd initialization 118 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 119 | # Run SONMF with svd initialization 120 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 121 | # Run NMF with random initialization 122 | nmf.X = nmf.main(X, mode, k, "nmf", "random", iter, tol); nmf.X 123 | # Run ONMF with random initialization 124 | onmf.X = nmf.main(X, mode, k, "onmf", "random", iter, tol); onmf.X 125 | # Run Semi-NMF with kmeans initialization 126 | semi.X = nmf.main(X, mode, k, "semi", "kmeans", iter, tol); semi.X 127 | # Run SONMF with svd initialization 128 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 129 | library(MatrixFact) 130 | roxygenize() 131 | library(roxygen2) 132 | roxygenize("MatrixFact") 133 | roxygenize() 134 | roxygenize() 135 | ?nmf.main 136 | library(MatrixFact) 137 | roxygenize() 138 | ?nmf.main 139 | # Run SONMF with svd initialization 140 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 141 | library(MatrixFact) 142 | n = 100 143 | X = matrix(rnorm(n^2, 0, 1), n, n) # Construct a 100-by-100 matrix with random elements 144 | X[X < 0] = 0 # Truncate all negative values to create a non-negative matix 145 | mode = 1 # Set mode to 1 for matrix with continuous entries 146 | k = 10 # Set target factorization rank to be k 147 | iter = 200 # Set number of iterations to be 200 148 | tol = 1e-5 # Set convergence threshold to 1e-5 149 | # Run SONMF with svd initialization 150 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 151 | # Run NMF with random initialization 152 | nmf.X = nmf.main(X, mode, k, "nmf", "random", iter, tol); nmf.X 153 | # Run ONMF with random initialization 154 | onmf.X = nmf.main(X, mode, k, "onmf", "random", iter, tol); onmf.X 155 | # Run SONMF with svd initialization 156 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 157 | # Run NMF with random initialization 158 | nmf.X = nmf.main(X, mode, k, "nmf", "random", iter, tol); nmf.X 159 | # Run ONMF with random initialization 160 | onmf.X = nmf.main(X, mode, k, "onmf", "random", iter, tol); onmf.X 161 | # Run Semi-NMF with kmeans initialization 162 | semi.X = nmf.main(X, mode, k, "semi", "kmeans", iter, tol); semi.X 163 | X.bin = matrix(rbinom(n^2, 1, runif(n^2, 0.25, 0.75)), n, n) # Construct a 100-by-100 matrix with binary elements 164 | mode.2 = 2 165 | # Run Binary SONMF with svd initialization 166 | sobin.X = nmf.main(X.bin, mode.2, k, "so_bin", "svd", iter, tol); sobin.X 167 | # Run logNMF with random initialization 168 | lognmf.X = nmf.main(X.bin, mode.2, k, "log_nmf", "random", iter, tol); lognmf.X 169 | build_vignettes() 170 | library(MatrixFact) 171 | library(MatrixFact) 172 | build() 173 | devtools::use_vignette("introduction") 174 | install_github("cronshells/MatrixFact") 175 | remove.packages("MatrixFact") 176 | remove.packages("matfact") 177 | library(MatrixFact) 178 | library(MatrixFact) 179 | library(MatrixFact) 180 | library(MatrixFact) 181 | remove.packages("matfact") 182 | remove.packages("MatrixFact") 183 | library(MatrixFact) 184 | devtools::install_github("cronshells/MatrixFact") 185 | document() 186 | library(MatrixFact) 187 | document() 188 | document() 189 | library(MatrixFact) 190 | library(MatrixFact) 191 | library(MatrixFact) 192 | library(MatrixFact) 193 | library(MatrixFact) 194 | n = 100 195 | X = matrix(rnorm(n^2, 0, 1), n, n) # Construct a 100-by-100 matrix with random elements 196 | X[X < 0] = 0 # Truncate all negative values to create a non-negative matix 197 | mode = 1 # Set mode to 1 for matrix with continuous entries 198 | k = 10 # Set target factorization rank to be k 199 | iter = 200 # Set number of iterations to be 200 200 | tol = 1e-5 # Set convergence threshold to 1e-5 201 | # Run SONMF with svd initialization 202 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 203 | library(MatrixFact) 204 | document() 205 | library(MatrixFact) 206 | library(MatrixFact) 207 | # Run SONMF with svd initialization 208 | sonmf.X = nmf.main(X, mode, k, "sonmf", "svd", iter, tol); sonmf.X 209 | # Run NMF with random initialization 210 | nmf.X = nmf.main(X, mode, k, "nmf", "random", iter, tol); nmf.X 211 | # Run ONMF with random initialization 212 | onmf.X = nmf.main(X, mode, k, "onmf", "random", iter, tol); onmf.X 213 | # Run Semi-NMF with kmeans initialization 214 | semi.X = nmf.main(X, mode, k, "semi", "kmeans", iter, tol); semi.X 215 | X.bin = matrix(rbinom(n^2, 1, runif(n^2, 0.25, 0.75)), n, n) # Construct a 100-by-100 matrix with binary elements 216 | mode.2 = 2 217 | # Run Binary SONMF with svd initialization 218 | sobin.X = nmf.main(X.bin, mode.2, k, "so_bin", "svd", iter, tol); sobin.X 219 | # Run logNMF with random initialization 220 | lognmf.X = nmf.main(X.bin, mode.2, k, "log_nmf", "random", iter, tol); lognmf.X 221 | # Run Binary SONMF with svd initialization 222 | sobin.X = nmf.main(X.bin, mode.2, k, "so_bin", "svd", iter, tol); sobin.X 223 | # Run logNMF with random initialization 224 | lognmf.X = nmf.main(X.bin, mode.2, k, "log_nmf", "random", iter, tol); lognmf.X 225 | document() 226 | build() 227 | document() 228 | ?nmf.main 229 | system("R CMD Rd2pdf .") 230 | library(MatrixFact) 231 | library(MatrixFact) 232 | document(\) 233 | document() 234 | ?nmf.main 235 | library(MatrixFact) 236 | library(MatrixFact) 237 | document() 238 | ?nmf.main 239 | library(MatrixFact) 240 | library(MatrixFact) 241 | document() 242 | ?nmf.main 243 | document() 244 | ?nmf.main 245 | library(MatrixFact) 246 | ?nmf.main 247 | system("R CMD Rd2pdf MatrixFact") 248 | system("R CMD Rd2pdf .") 249 | system("R CMD Rd2pdf .") 250 | system("R CMD Rd2pdf .") 251 | system("R CMD Rd2pdf .") 252 | build() 253 | library(MatrixFact) 254 | ?nmf.main 255 | library(MatrixFact) 256 | devtools::document() 257 | library(MatrixFact) 258 | ?bin.test 259 | library(MatrixFact) 260 | devtools::document() 261 | library(MatrixFact) 262 | library(MatrixFact) 263 | library(MatrixFact) 264 | devtools::document() 265 | library(MatrixFact) 266 | devtools::document() 267 | library(MatrixFact) 268 | bin.test 269 | load("C:/Users/cronshells/Dropbox/Jack/JASA/code/cont_temp.RData") 270 | # Set directory for the plots 271 | setwd("C:/Users/cronshells/Dropbox/Jack/JASA/code/plot") 272 | # Plot the log of the normalized residual for better visibility 273 | plot.fun = function(res, k, file) { 274 | # Use the Cairo package for better plot resolution 275 | png(filename=paste0(file, ".png"), 276 | type="cairo", 277 | units="in", 278 | width=5, 279 | height=4, 280 | pointsize=12, 281 | res=288) 282 | plot(res$bin[,2], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 283 | lines(res$log[,2], col = "black", pch = 10, type = "l", lwd = 2, lty = 6) 284 | lines(res$log[,2], col = "black", pch = 10, type = "l", lwd = 2, lty = 6) 285 | lines(res$log[,2], col = "black", pch = 10, type = "l", lwd = 2, lty = 6) 286 | abline(h = res$summary[1], col = "purple") 287 | } 288 | # Plot the log of the normalized residual for better visibility 289 | plot.fun = function(res, k, file) { 290 | # Use the Cairo package for better plot resolution 291 | png(filename=paste0(file, ".png"), 292 | type="cairo", 293 | units="in", 294 | width=5, 295 | height=4, 296 | pointsize=12, 297 | res=288) 298 | log.res = log(res + 1) 299 | plot(log.res$bin[,2], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 300 | lines(log.res$log[,2], col = "black", pch = 10, type = "l", lwd = 2, lty = 3) 301 | lines(log.res$log[,2], col = "black", pch = 10, type = "l", lwd = 2, lty = 4) 302 | lines(log.res$log[,2], col = "black", pch = 10, type = "l", lwd = 2, lty = 5) 303 | abline(h = log(res$summary[1] + 1), col = "purple") 304 | legend("topright", legend = c("SONMF", "NMF", "ONMF", "Semi", "True Error"), 305 | col = c("red", "green", "blue", "black", "purple"), lty = c(2, 5, 4, 3, 1)) 306 | } 307 | plot.fun(res.1) 308 | plot.fun(res.1, 10, "1_10") 309 | plot.fun(res.1$res.10, 10, "1_10") 310 | res = res.1$res.10 311 | log.res = log(res + 1) 312 | log.res 313 | # Plot the log of the normalized residual for better visibility 314 | plot.fun = function(res, k, file) { 315 | # Use the Cairo package for better plot resolution 316 | png(filename=paste0(file, ".png"), 317 | type="cairo", 318 | units="in", 319 | width=5, 320 | height=4, 321 | pointsize=12, 322 | res=288) 323 | log.res = log(res + 1) 324 | plot(log.res[,1], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 325 | lines(log.res[,2], col = "black", pch = 10, type = "l", lwd = 2, lty = 3) 326 | lines(log.res[,3], col = "black", pch = 10, type = "l", lwd = 2, lty = 4) 327 | lines(log.res[,4], col = "black", pch = 10, type = "l", lwd = 2, lty = 5) 328 | abline(h = log(res$summary[1] + 1), col = "purple") 329 | legend("topright", legend = c("SONMF", "NMF", "ONMF", "Semi", "True Error"), 330 | col = c("red", "green", "blue", "black", "purple"), lty = c(2, 5, 4, 3, 1)) 331 | } 332 | plot.fun(res.1$res.10, 10, "1_10") 333 | plot(log.res[,1], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 334 | lgo.res[,1] 335 | log.res[,1] 336 | k = 10 337 | plot(log.res[,1], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 338 | plot.new() 339 | plot(log.res[,1], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 340 | lines(log.res[,2], col = "black", pch = 10, type = "l", lwd = 2, lty = 3) 341 | library(Cairo) 342 | plot(log.res[,1], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 343 | load("C:/Users/cronshells/Dropbox/Jack/JASA/code/cont_temp.RData") 344 | # Plot the log of the normalized residual for better visibility 345 | plot.fun = function(res, k, file) { 346 | # Use the Cairo package for better plot resolution 347 | png(filename=paste0(file, ".png"), 348 | type="cairo", 349 | units="in", 350 | width=5, 351 | height=4, 352 | pointsize=12, 353 | res=288) 354 | log.res = log(res + 1) 355 | plot(log.res[,1], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 356 | lines(log.res[,2], col = "black", pch = 10, type = "l", lwd = 2, lty = 3) 357 | lines(log.res[,3], col = "black", pch = 10, type = "l", lwd = 2, lty = 4) 358 | lines(log.res[,4], col = "black", pch = 10, type = "l", lwd = 2, lty = 5) 359 | abline(h = log(res$summary[1] + 1), col = "purple") 360 | legend("topright", legend = c("SONMF", "NMF", "ONMF", "Semi", "True Error"), 361 | col = c("red", "green", "blue", "black", "purple"), lty = c(2, 5, 4, 3, 1)) 362 | } 363 | plot.fun(res.1$res.10, 10, "1_10") 364 | res = res.1$res.10 365 | log.res = log(res + 1) 366 | plot(log.res[,1], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 367 | lines(log.res[,2], col = "black", pch = 10, type = "l", lwd = 2, lty = 3) 368 | dev.off 369 | dev.off() 370 | plot(log.res[,1], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 371 | lines(log.res[,2], col = "black", pch = 10, type = "l", lwd = 2, lty = 3) 372 | lines(log.res[,3], col = "black", pch = 10, type = "l", lwd = 2, lty = 4) 373 | plot(log.res[,1], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 374 | lines(log.res[,2], col = "black", type = "l", lwd = 2, lty = 3) 375 | lines(log.res[,3], col = "blue", type = "l", lwd = 2, lty = 4) 376 | lines(log.res[,4], col = "green", type = "l", lwd = 2, lty = 5) 377 | log.res = log(res + 1) 378 | plot(log.res[,1], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "") 379 | lines(log.res[,2], col = "black", type = "l", lwd = 2, lty = 3) 380 | lines(log.res[,3], col = "blue", type = "l", lwd = 2, lty = 4) 381 | lines(log.res[,4], col = "green", type = "l", lwd = 2, lty = 5) 382 | yrange = c(0, 2) 383 | plot(log.res[,1], col = "red", type = "l", lty = 1, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "", ylim = yrange) 384 | lines(log.res[,2], col = "black", type = "l", lwd = 2, lty = 3) 385 | lines(log.res[,3], col = "blue", type = "l", lwd = 2, lty = 4) 386 | lines(log.res[,4], col = "green", type = "l", lwd = 2, lty = 5) 387 | plot(log.res[,1], col = "red", type = "l", lty = 2, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "", ylim = yrange) 388 | lines(log.res[,2], col = "black", type = "l", lwd = 2, lty = 3) 389 | lines(log.res[,3], col = "blue", type = "l", lwd = 2, lty = 4) 390 | lines(log.res[,4], col = "green", type = "l", lwd = 2, lty = 5) 391 | abline(h = log(res$summary[1] + 1), col = "purple") 392 | # Plot the log of the normalized residual for better visibility 393 | plot.fun = function(res, k, file, yrange) { 394 | # Use the Cairo package for better plot resolution 395 | png(filename=paste0(file, ".png"), 396 | type="cairo", 397 | units="in", 398 | width=5, 399 | height=4, 400 | pointsize=12, 401 | res=288) 402 | log.res = log(res + 1) 403 | plot(log.res[,1], col = "red", type = "l", lty = 2, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "", ylim = yrange) 404 | lines(log.res[,2], col = "black", type = "l", lwd = 2, lty = 3) 405 | lines(log.res[,3], col = "blue", type = "l", lwd = 2, lty = 4) 406 | lines(log.res[,4], col = "green", type = "l", lwd = 2, lty = 5) 407 | abline(h = log(res$summary[1] + 1), col = "purple") 408 | legend("topright", legend = c("SONMF", "NMF", "ONMF", "Semi", "True Error"), 409 | col = c("red", "green", "blue", "black", "purple"), lty = c(2, 5, 4, 3, 1)) 410 | } 411 | plot.fun(res.1$res.10, 10, "1_10", c(0, 1.7)) 412 | # Plot the log of the normalized residual for better visibility 413 | plot.fun = function(res, index, k, file, yrange) { 414 | res.temp = res[[index]] 415 | # Use the Cairo package for better plot resolution 416 | png(filename=paste0(file, ".png"), 417 | type="cairo", 418 | units="in", 419 | width=5, 420 | height=4, 421 | pointsize=12, 422 | res=288) 423 | log.res = log(res.temp + 1) 424 | plot(log.res[,1], col = "red", type = "l", lty = 2, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "", ylim = yrange) 425 | lines(log.res[,2], col = "black", type = "l", lwd = 2, lty = 3) 426 | lines(log.res[,3], col = "blue", type = "l", lwd = 2, lty = 4) 427 | lines(log.res[,4], col = "green", type = "l", lwd = 2, lty = 5) 428 | abline(h = log(res$summary[1] + 1), col = "purple") 429 | legend("topright", legend = c("SONMF", "NMF", "ONMF", "Semi", "True Error"), 430 | col = c("red", "green", "blue", "black", "purple"), lty = c(2, 5, 4, 3, 1)) 431 | } 432 | plot.fun(res.1$res.10, 10, "1_10", c(0, 1.7)) 433 | plot.fun(res.1$res.10, 1, 10, "1_10", c(0, 1.7)) 434 | plot.fun(res.1, 1, 10, "1_10", c(0, 1.7)) 435 | # Set directory for the plots 436 | setwd("C:/Users/cronshells/Dropbox/Jack/JASA/code/plot") 437 | # Plot the log of the normalized residual for better visibility 438 | plot.fun = function(res, index, k, file, yrange) { 439 | res.temp = res[[index]] 440 | # Use the Cairo package for better plot resolution 441 | png(filename=paste0(file, ".png"), 442 | type="cairo", 443 | units="in", 444 | width=5, 445 | height=4, 446 | pointsize=12, 447 | res=288) 448 | log.res = log(res.temp + 1) 449 | plot(log.res[,1], col = "red", type = "l", lty = 2, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "", ylim = yrange) 450 | lines(log.res[,2], col = "black", type = "l", lwd = 2, lty = 3) 451 | lines(log.res[,3], col = "blue", type = "l", lwd = 2, lty = 4) 452 | lines(log.res[,4], col = "green", type = "l", lwd = 2, lty = 5) 453 | abline(h = log(res$summary[1] + 1), col = "purple") 454 | legend("topright", legend = c("SONMF", "NMF", "ONMF", "Semi", "True Error"), 455 | col = c("red", "green", "blue", "black", "purple"), lty = c(2, 5, 4, 3, 1)) 456 | } 457 | plot.fun(res.1, 1, 10, "1_10", c(0, 1.7)) 458 | # Set directory for the plots 459 | setwd("C:/Users/cronshells/Dropbox/Jack/JASA/plot") 460 | # Plot the log of the normalized residual for better visibility 461 | plot.fun = function(res, index, k, file, yrange) { 462 | res.temp = res[[index]] 463 | # Use the Cairo package for better plot resolution 464 | png(filename=paste0(file, ".png"), 465 | type="cairo", 466 | units="in", 467 | width=5, 468 | height=4, 469 | pointsize=12, 470 | res=288) 471 | log.res = log(res.temp + 1) 472 | plot(log.res[,1], col = "red", type = "l", lty = 2, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "", ylim = yrange) 473 | lines(log.res[,2], col = "black", type = "l", lwd = 2, lty = 3) 474 | lines(log.res[,3], col = "blue", type = "l", lwd = 2, lty = 4) 475 | lines(log.res[,4], col = "green", type = "l", lwd = 2, lty = 5) 476 | abline(h = log(res$summary[1] + 1), col = "purple") 477 | legend("topright", legend = c("SONMF", "NMF", "ONMF", "Semi", "True Error"), 478 | col = c("red", "green", "blue", "black", "purple"), lty = c(2, 5, 4, 3, 1)) 479 | } 480 | plot.fun(res.1, 1, 10, "1_10", c(0, 1.7)) 481 | getwd() 482 | # Set directory for the plots 483 | setwd("C:/Users/cronshells/Dropbox/Jack/JASA/plot") 484 | load("C:/Users/cronshells/Dropbox/Jack/JASA/code/cont_temp.RData") 485 | # Set directory for the plots 486 | setwd("C:/Users/cronshells/Dropbox/Jack/JASA/plot") 487 | # Plot the log of the normalized residual for better visibility 488 | plot.fun = function(res, index, k, file, yrange) { 489 | res.temp = res[[index]] 490 | # Use the Cairo package for better plot resolution 491 | png(filename=paste0(file, ".png"), 492 | type="cairo", 493 | units="in", 494 | width=5, 495 | height=4, 496 | pointsize=12, 497 | res=288) 498 | log.res = log(res.temp + 1) 499 | plot(log.res[,1], col = "red", type = "l", lty = 2, lwd = 2, main = paste0("K = ", k), xlab = "Iterations", ylab = "", ylim = yrange) 500 | lines(log.res[,2], col = "black", type = "l", lwd = 2, lty = 3) 501 | lines(log.res[,3], col = "blue", type = "l", lwd = 2, lty = 4) 502 | lines(log.res[,4], col = "green", type = "l", lwd = 2, lty = 5) 503 | abline(h = log(res$summary[1] + 1), col = "purple") 504 | legend("topright", legend = c("SONMF", "NMF", "ONMF", "Semi", "True Error"), 505 | col = c("red", "green", "blue", "black", "purple"), lty = c(2, 5, 4, 3, 1)) 506 | } 507 | plot.fun(res.1, 1, 10, "1_10", c(0, 1.7)) 508 | getwd() 509 | # Set directory for the plots 510 | setwd("C:/Users/cronshells/Dropbox/Jack/JASA/plot") 511 | # Set directory for the plots 512 | setwd("C:/Users/cronshells/Dropbox/Jack/JASA/plot") 513 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------