## ----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)

## ----data---------------------------------------------------------------------
library("sssvcqr")
data("lucas_housing_sample")
housing <- lucas_housing_sample
str(housing)
summary(housing[, c("log_price", "log_TLA", "log_lotsize", "age_scaled")])

## ----assemble-----------------------------------------------------------------
y <- housing$log_price
Z <- model.matrix(~ log_TLA + log_lotsize + sale_year, data = housing)
X <- as.matrix(housing[, c("age_scaled", "age2_scaled")])
u <- scale(as.matrix(housing[, c("longitude", "latitude")]))
c(n = nrow(housing), q = ncol(Z), p = ncol(X))

## ----graph--------------------------------------------------------------------
graph <- build_graph_laplacian(u, k = 8L)
length(graph$components_list)
range(graph$D_vec)

## ----fit----------------------------------------------------------------------
fit <- ss_svcqr(
  y = y, Z = Z, X = X, u = u,
  tau = 0.5,
  lambda1 = 3, lambda2 = 1, k_nn = 8,
  control = list(max_iter = 100, warn_nonconvergence = FALSE)
)
summary(fit)

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

## ----cv-----------------------------------------------------------------------
cv <- cv_ss_svcqr(
  y = y, Z = Z, X = X, u = u,
  tau = 0.5,
  lambda1_seq = c(2, 3),
  lambda2_seq = c(0.5, 1),
  K_folds = 3, adaptive_weights = FALSE,
  control = list(max_iter = 25, warn_nonconvergence = FALSE)
)
cv

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

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

