## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>",
  fig.width = 7, fig.height = 5, fig.align = "center")
options(prompt = "R> ", continue = "+  ", width = 80, useFancyQuotes = FALSE)

## ----simulate-----------------------------------------------------------------
library("sssvcqr")
dat <- simulate_sssvcqr_data(n = 120, q = 2, p = 3, seed = 20260505)
str(dat[c("y", "Z", "X", "u", "active", "alpha_true", "beta_G_true")],
  max.level = 1)
dat$active

## ----fit----------------------------------------------------------------------
fit <- ss_svcqr(
  y = dat$y, Z = dat$Z, X = dat$X, u = dat$u,
  tau = 0.5,
  lambda1 = 5, lambda2 = 0.1, k_nn = 8,
  control = list(max_iter = 180, warn_nonconvergence = FALSE)
)
fit

## ----summary------------------------------------------------------------------
summary(fit)
selection_recovery_table(fit, dat)

## ----methods------------------------------------------------------------------
round(unlist(coef(fit)[1:2]), 4)
head(round(fitted(fit), 4))
head(round(residuals(fit), 4))

## ----plots, fig.width = 7, fig.height = 6-------------------------------------
plot(fit, type = "deviation", index = 1)
plot(fit, type = "coefficient", index = 1)
plot(fit, type = "convergence")

## ----predict------------------------------------------------------------------
unew <- dat$u[1:3, , drop = FALSE] + 0.01
round(predict(fit,
  Znew = dat$Z[1:3, , drop = FALSE],
  Xnew = dat$X[1:3, , drop = FALSE],
  unew = unew), 4)
round(predict(fit, type = "coefficients")[1:3, ], 4)

## ----cv-----------------------------------------------------------------------
dat_cv <- simulate_sssvcqr_data(n = 80, q = 2, p = 3, seed = 20260505)
cv <- cv_ss_svcqr(
  y = dat_cv$y, Z = dat_cv$Z, X = dat_cv$X, u = dat_cv$u,
  tau = 0.5,
  lambda1_seq = c(1, 2),
  lambda2_seq = c(0.5, 1),
  K_folds = 3, adaptive_weights = FALSE,
  control = list(max_iter = 25, warn_nonconvergence = FALSE)
)
cv
cv$best

## ----kkt----------------------------------------------------------------------
kkt <- kkt_sssvcqr(dat$y, dat$Z, dat$X, fit)
signif(kkt$max_violation, 3)
signif(kkt$max_centering_violation, 3)

