params <-
list(family = "lapis", preset = "homage")

## ----setup-opts, include = FALSE----------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  message = FALSE,
  warning = FALSE,
  fig.width = 7,
  fig.height = 4.1,
  fig.align = "center",
  out.width = "92%",
  dpi = 100
)

## ----albers-classes, echo=FALSE, results='asis'-------------------------------
cat(sprintf(
  paste0(
    '<script>document.addEventListener("DOMContentLoaded",function(){',
    'document.body.classList.remove("palette-red","palette-lapis","palette-ochre","palette-teal","palette-green","palette-violet","preset-homage","preset-interaction","preset-study","preset-structural","preset-adobe","preset-midnight");',
    'document.body.classList.add("palette-%s","preset-%s");',
    '});</script>'
  ),
  params$family,
  params$preset
))

## ----helpers, include = FALSE-------------------------------------------------
# Shared palette + two small base-graphics helpers used throughout the
# vignette. Kept out of the reader's view: the reader sees the API call and
# the picture, never the plotting boilerplate.
ec_blue <- "#2166ac"; ec_red <- "#b2182b"; ec_tol <- "#ef8a62"; ec_grey <- "grey78"

# Per-pair backward error as a stem/dot plot, against the tolerance line.
plot_backward_error <- function(cert, main = NULL, tol = cert$tolerance) {
  be <- pmax(cert$backward_error, .Machine$double.eps)
  k  <- length(be)
  col_pt <- ifelse(cert$converged, ec_blue, ec_red)
  rng  <- range(c(be, tol))
  ylim <- c(rng[1] / 6, rng[2] * 6)
  op <- par(mar = c(4, 4.6, if (is.null(main)) 1 else 2.4, 1)); on.exit(par(op))
  plot(seq_len(k), be, log = "y", type = "n", xlim = c(0.5, k + 0.5),
       ylim = ylim, xaxt = "n", bty = "n", main = main,
       xlab = "returned pair", ylab = "backward error (log scale)")
  axis(1, at = seq_len(k))
  segments(seq_len(k), ylim[1], seq_len(k), be, col = col_pt, lwd = 2)
  points(seq_len(k), be, pch = 19, cex = 1.3, col = col_pt)
  abline(h = tol, col = ec_tol, lty = 2, lwd = 2)
  text(k + 0.45, tol, sprintf("tol = %.0e", tol), col = ec_tol,
       pos = 3, cex = 0.85, xpd = NA)
}

# A computed slice (blue) drawn on top of the full dense spectrum (grey).
plot_spectrum <- function(all_vals, computed, ylab = "value", main = NULL) {
  s <- sort(all_vals, decreasing = TRUE)
  k <- length(computed)
  op <- par(mar = c(4, 4.6, if (is.null(main)) 1 else 2.4, 1)); on.exit(par(op))
  plot(seq_along(s), s, pch = 19, cex = 0.4, col = ec_grey, bty = "n",
       xlab = "rank (largest to smallest)", ylab = ylab, main = main)
  points(seq_len(k), sort(computed, decreasing = TRUE),
         pch = 19, cex = 1.2, col = ec_blue)
  legend("topright", c("full spectrum (dense reference)", "computed by eigencore"),
         pch = 19, pt.cex = c(0.7, 1.2), col = c(ec_grey, ec_blue),
         bty = "n", cex = 0.9)
}

## ----setup--------------------------------------------------------------------
library(eigencore)

## ----make-A-------------------------------------------------------------------
set.seed(1)
n <- 200
A <- crossprod(matrix(rnorm(n * n), n, n)) / n + diag(n)

## ----as-operator--------------------------------------------------------------
Aop <- as_operator(A)
Aop

## ----plan---------------------------------------------------------------------
P    <- eigen_problem(A, structure = hermitian(), target = largest())
plan <- plan_solver(P, k = 5)
plan

## ----solve--------------------------------------------------------------------
fit <- solve(P, k = 5)
fit

## ----certificate--------------------------------------------------------------
fit$certificate

## ----cert-bars, echo = FALSE, fig.cap = "Per-pair backward error for the five returned eigenpairs. Every pair sits well below the dashed tolerance line, so the overall certificate passes.", fig.alt = "Stem plot of backward error for five eigenpairs on a log scale; all five points fall far below the dashed tolerance line at 1e-8."----
plot_backward_error(fit$certificate)

## ----values-------------------------------------------------------------------
fit$values

## ----spectrum, echo = FALSE, fig.cap = "The five largest eigenvalues (blue) located within the full spectrum of A (grey). eigencore computes only the requested slice, then certifies it.", fig.alt = "Scatter plot of all 200 eigenvalues sorted from largest to smallest in grey, with the five largest highlighted in blue at the top-left."----
all_vals <- eigen(A, symmetric = TRUE, only.values = TRUE)$values
plot_spectrum(all_vals, fit$values, ylab = "eigenvalue")

## ----generalized--------------------------------------------------------------
B <- diag(seq(1, 5, length.out = n))
fit_gen <- eig_partial(A, k = 5, target = largest(), B = B,
                       method = lobpcg(maxit = 200))
fit_gen

## ----svd----------------------------------------------------------------------
M <- matrix(rnorm(400 * 50), 400, 50)
svd_fit <- svd_partial(M, rank = 5, target = largest())
svd_fit

## ----svd-scree, echo = FALSE, fig.cap = "The five leading singular values (blue) computed by eigencore, shown against the full singular-value spectrum of M (grey).", fig.alt = "Scatter plot of all 50 singular values of M sorted descending in grey, with the top five highlighted in blue."----
all_sv <- svd(M, nu = 0, nv = 0)$d
plot_spectrum(all_sv, svd_fit$d, ylab = "singular value")

## ----rspectra-----------------------------------------------------------------
res <- eigs_sym(A, k = 5, which = "LA")
str(res, max.level = 1)

## ----rspectra-cert------------------------------------------------------------
res$certificate

