## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")

## ----install, eval=FALSE------------------------------------------------------
# install.packages("msPCA")

## ----load---------------------------------------------------------------------
library(msPCA)

## ----fit----------------------------------------------------------------------
Sigma <- cor(mtcars)

set.seed(42)
res <- mspca(Sigma, r = 2, ks = c(4, 4), verbose = FALSE)

## ----print--------------------------------------------------------------------
print(res)

## ----summary------------------------------------------------------------------
summary(res)

## ----fit_X--------------------------------------------------------------------
X <- as.matrix(mtcars)

set.seed(42)
res_X <- mspca(X, r = 2, ks = c(4, 4), type = "X", scale = TRUE, verbose = FALSE)
print(res_X)

## ----fit_corr-----------------------------------------------------------------
set.seed(42)
res_corr <- mspca(Sigma, r = 2, ks = c(4, 4),
                  feasibilityConstraintType = 1, verbose = FALSE)
print(res_corr)
summary(res_corr)

## ----nonredundancy------------------------------------------------------------
res_corr$nonredundancy$uncorrelatedness   # the constraint that was enforced
res_corr$nonredundancy$orthogonality      # the one that was not

## ----diagnostics--------------------------------------------------------------
# Orthogonality and zero-correlation violations for the default solution
feasibility_violation_off(Sigma, res$x_best, feasibilityConstraintType = 0)
feasibility_violation_off(Sigma, res$x_best, feasibilityConstraintType = 1)

# The same two numbers, already stored on the fitted object
sum(res$nonredundancy$orthogonality,    na.rm = TRUE)
sum(res$nonredundancy$uncorrelatedness, na.rm = TRUE)

# Total and per-PC fraction of variance explained
fraction_variance_explained(Sigma, res$x_best)
fraction_variance_explained_perPC(Sigma, res$x_best)

## ----dense_pca----------------------------------------------------------------
pca_res <- prcomp(mtcars, scale. = TRUE)
fraction_variance_explained(Sigma, pca_res$rotation[, 1:2])

