## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5,
  fig.align = "center"
)

## ----library------------------------------------------------------------------
library(betaregscale)

## ----var-sim------------------------------------------------------------------
set.seed(11)
d <- data.frame(x1 = rnorm(300), x2 = rbinom(300, 1, 0.5), z1 = rnorm(300))
sv <- brs_sim(~ x1 + x2 | z1, data = d, beta = c(-0.2, 0.5, -0.5),
              zeta = c(qlogis(0.15), 0.6), ncuts = 10)
table(sv$y)

## ----var-fit------------------------------------------------------------------
fit_const <- brs(y ~ x1 + x2, data = sv)
fit_var <- brs(y ~ x1 + x2 | z1, data = sv)
anova(fit_const, fit_var)
summary(fit_var)

## ----var-coef-----------------------------------------------------------------
coef(fit_var, model = "precision")
nd <- data.frame(x1 = 0, x2 = 0, z1 = c(-1, 0, 1))
cbind(nd, sigma = predict(fit_var, nd, type = "precision"),
      sd_latent = 10 * sqrt(predict(fit_var, nd, type = "variance")))

## ----cut-sim------------------------------------------------------------------
set.seed(1)
heap <- brs_sim(~ x1 + x2, data = d, beta = c(0, 0.5, -0.6),
                phi = qlogis(0.2), ncuts = 10, cutpoints = c(0.12, 0.88))
table(heap$y)

## ----cut-fit------------------------------------------------------------------
fit_fix <- brs(y ~ x1 + x2, data = heap)
fit_bnd <- brs(y ~ x1 + x2, data = heap, cutpoints = "boundary")
anova(fit_fix, fit_bnd)

## ----cut-summary--------------------------------------------------------------
summary(fit_bnd)
confint(fit_bnd, model = "cutpoints")

## ----cut-pmf------------------------------------------------------------------
obs <- prop.table(table(factor(heap$y, levels = 0:10)))
round(cbind(observed = as.numeric(obs),
            fixed = colMeans(brs_predict_scoreprob(fit_fix)),
            boundary = colMeans(brs_predict_scoreprob(fit_bnd))), 3)

## ----cut-cv-------------------------------------------------------------------
set.seed(2)
cv_fix <- brs_cv(y ~ x1 + x2, data = heap, k = 5)
set.seed(2)
cv_bnd <- brs_cv(y ~ x1 + x2, data = heap, k = 5, cutpoints = "boundary")
c(fixed = mean(cv_fix$log_score), boundary = mean(cv_bnd$log_score))

## ----links--------------------------------------------------------------------
fits <- lapply(c(logit = "logit", probit = "probit", cloglog = "cloglog"),
               function(l) brs(y ~ x1 + x2 | z1, data = sv, link = l))
brs_table(models = fits, sort_by = "AIC")

## ----ordinal------------------------------------------------------------------
X <- model.matrix(~ x1 + x2, data = heap)[, -1]
s <- heap$y
K <- 10
# Negative log-likelihood; thresholds kept ordered by positive increments
nll_ord <- function(par) {
  theta <- cumsum(c(par[1], exp(par[2:K])))
  eta <- drop(X %*% par[-(1:K)])
  cum <- cbind(0, plogis(outer(-eta, theta, "+")), 1)
  -sum(log(cum[cbind(seq_along(s), s + 2)] - cum[cbind(seq_along(s), s + 1)]))
}
start <- c(qlogis(mean(s == 0)), rep(log(0.4), K - 1), 0, 0)
ord <- optim(start, nll_ord, method = "BFGS", control = list(maxit = 1000))
ord$convergence

ll <- c(brs_fixed = as.numeric(logLik(fit_fix)),
        brs_boundary = as.numeric(logLik(fit_bnd)),
        cumulative_logit = -ord$value)
df <- c(length(coef(fit_fix)), length(coef(fit_bnd)), length(ord$par))
data.frame(logLik = ll, df = df, AIC = -2 * ll + 2 * df)

## ----mc-design, eval = FALSE--------------------------------------------------
# R <- 200L
# beta <- c(0.5, 0.2, -0.7)
# grid <- expand.grid(sigma = c(0.08, 0.2, 0.4), n = c(100L, 500L),
#                     K = c(10L, 100L))
# one_cell <- function(sigma, n, K) {
#   set.seed(1000 + n + K + round(100 * sigma))
#   d <- data.frame(x1 = rnorm(n), x2 = rbinom(n, 1, 0.5))   # fixed design
#   truth <- c(beta, qlogis(sigma))
#   est <- se <- matrix(NA_real_, R, 4)
#   for (r in seq_len(R)) {
#     s <- brs_sim(~ x1 + x2, data = d, beta = beta, phi = qlogis(sigma),
#                  ncuts = K)
#     f <- tryCatch(brs(y ~ x1 + x2, data = s), error = function(e) NULL)
#     if (is.null(f) || f$convergence != 0L) next
#     est[r, ] <- coef(f)
#     se[r, ] <- sqrt(diag(vcov(f)))
#   }
#   ok <- stats::complete.cases(est, se)
#   err <- est[ok, ] - rep(truth, each = sum(ok))
#   data.frame(sigma, n, K, par = c("b0", "b1", "b2", "logit_sigma"),
#              bias = colMeans(err), rmse = sqrt(colMeans(err^2)),
#              cover = colMeans(abs(err) <= qnorm(0.975) * se[ok, ]))
# }
# res <- do.call(rbind, Map(one_cell, grid$sigma, grid$n, grid$K))

