## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(echo = TRUE, cache = FALSE, tidy = TRUE)

## ----message = FALSE, echo = TRUE---------------------------------------------
library(CVglasso)

#  generate data from a sparse matrix
# first compute covariance matrix
S = matrix(0.7, nrow = 5, ncol = 5)
for (i in 1:5){
  for (j in 1:5){
    S[i, j] = S[i, j]^abs(i - j)
  }
}

# generate 100 x 5 matrix with rows drawn from iid N_p(0, S)
set.seed(123)
Z = matrix(rnorm(100*5), nrow = 100, ncol = 5)
out = eigen(S, symmetric = TRUE)
S.sqrt = out$vectors %*% diag(out$values^0.5) %*% t(out$vectors)
X = Z %*% S.sqrt

# snap shot of data
head(X)


## ----message = FALSE, echo = TRUE---------------------------------------------

# print oracle covariance matrix
S

# print inverse covariance matrix (omega)
round(qr.solve(S), 5)


## ----message = FALSE, echo = TRUE---------------------------------------------

# print inverse of sample precision matrix (perhaps a bad estimate)
round(qr.solve(cov(X)*(nrow(X) - 1)/nrow(X)), 5)


## ----message = FALSE, echo = TRUE---------------------------------------------

# cross validation for lam (small grid/folds for vignette speed)
CVglasso(X, nlam = 4, K = 3, trace = "none")


## ----message = FALSE, echo = TRUE---------------------------------------------

# produce CV heat map from the same small vignette fit
CV = CVglasso(X, nlam = 4, K = 3, trace = "none")
plot(CV, type = "heatmap")


## ----message = FALSE, echo = TRUE---------------------------------------------

# produce line graph for CV errors
plot(CV, type = "line")


## ----message = FALSE, echo = TRUE---------------------------------------------

# AIC
plot(CVglasso(X, nlam = 4, K = 3, crit.cv = "AIC", trace = "none"))

# BIC
plot(CVglasso(X, nlam = 4, K = 3, crit.cv = "BIC", trace = "none"))


## ----message = FALSE, echo = TRUE, eval = FALSE-------------------------------
# 
# # keep all estimates using path
# CV = CVglasso(X, path = TRUE, trace = "none")
# 
# # print only first three objects
# CV$Path[,,1:3]
# 

## ----message = FALSE, echo = TRUE, eval = FALSE-------------------------------
# 
# # reduce number of lam to 5
# CV = CVglasso(X, nlam = 5)
# 

## ----message = FALSE, echo = TRUE, eval = FALSE-------------------------------
# 
# # reduce number of folds to 3
# CV = CVglasso(X, K = 3)
# 

## ----message = FALSE, echo = TRUE, eval = FALSE-------------------------------
# 
# # relax convergence criteria
# CV = CVglasso(X, tol = 1e-3)
# 

## ----message = FALSE, echo = TRUE, eval = FALSE-------------------------------
# 
# # adjust maximum number of iterations
# CV = CVglasso(X, maxit = 1e3)
# 

## ----message = FALSE, echo = TRUE, eval = FALSE-------------------------------
# 
# # parallel CV
# CV = CVglasso(X, cores = 3)
# 

