## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(rvinecopulib)
set.seed(401)

## ----integer-data-------------------------------------------------------------
n <- 100
latent <- rnorm(n)
x <- data.frame(
  value = latent + rnorm(n),
  count = rpois(n, exp(0.5 + 0.3 * latent))
)

fit <- vine(
  x,
  var_types = c("c", "d"),
  copula_controls = list(family_set = "onepar")
)
summary(fit)$margins
dvine(x[1:5, ], fit)

## ----ordered-data-------------------------------------------------------------
survey <- data.frame(
  rating = ordered(
    sample(c("low", "middle", "high"), n, replace = TRUE),
    levels = c("low", "middle", "high")
  ),
  score = rnorm(n)
)

ordered_fit <- vine(
  survey,
  copula_controls = list(family_set = "indep")
)
ordered_draws <- rvine(5, ordered_fit)
str(ordered_draws)

## ----zero-inflated------------------------------------------------------------
amount <- zero_inflated(c(rep(0, 25), rexp(75)))
zi_data <- data.frame(amount = amount, score = rnorm(100))
inherits(zi_data$amount, "zero_inflated")

zi_fit <- vine(
  zi_data,
  copula_controls = list(family_set = "indep")
)
summary(zi_fit)$margins[, c("name", "type")]

## ----layouts------------------------------------------------------------------
n <- 80
raw <- data.frame(
  first = rpois(n, 2),
  middle = rnorm(n),
  last = rpois(n, 4)
)

values <- cbind(
  ppois(raw$first, 2),
  pnorm(raw$middle),
  ppois(raw$last, 4)
)
left_discrete <- cbind(
  ppois(raw$first - 1, 2),
  ppois(raw$last - 1, 4)
)
compact <- cbind(values, left_discrete)

left_all <- cbind(
  ppois(raw$first - 1, 2),
  pnorm(raw$middle),
  ppois(raw$last - 1, 4)
)
expanded <- cbind(values, left_all)

copula_fit <- vinecop(
  compact,
  var_types = c("d", "c", "d"),
  family_set = "indep"
)
stopifnot(isTRUE(all.equal(
  dvinecop(compact, copula_fit),
  dvinecop(expanded, copula_fit)
)))

## ----simulation---------------------------------------------------------------
copula_draws <- rvinecop(4, copula_fit)
dim(copula_draws)

original_draws <- rvine(4, ordered_fit)
is.ordered(original_draws$rating)

## ----discrete-rosenblatt------------------------------------------------------
set.seed(402)
randomized <- rosenblatt(compact, copula_fit)
upper_endpoint <- rosenblatt(
  compact,
  copula_fit,
  randomize_discrete = FALSE
)
head(randomized)
head(upper_endpoint)

