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

## ----fit-vine-----------------------------------------------------------------
n <- 120
z <- rnorm(n)
x <- data.frame(
  amount = exp(z + rnorm(n, sd = 0.5)),
  duration = exp(0.5 * z + rnorm(n, sd = 0.8)),
  events = rpois(n, exp(0.3 + 0.25 * z))
)

fit <- vine(
  x,
  var_types = c("c", "c", "d"),
  copula_controls = list(family_set = "onepar"),
  keep_data = TRUE
)
fit
summary(fit)

## ----use-vine-----------------------------------------------------------------
dvine(x[1:4, ], fit)
predict(fit, x[1:4, ], what = "pdf")
logLik(fit)
AIC(fit)

simulated <- rvine(5, fit)
simulated

## ----fit-vinecop--------------------------------------------------------------
u <- pseudo_obs(as.matrix(USArrests))
copula_fit <- vinecop(
  u,
  family_set = c("gaussian", "clayton", "gumbel", "frank")
)
summary(copula_fit)

## ----use-vinecop--------------------------------------------------------------
new_u <- rvinecop(6, copula_fit)
dvinecop(new_u, copula_fit)
pvinecop(new_u[1:2, ], copula_fit, n_mc = 1000)

## ----fit-bicop----------------------------------------------------------------
u2 <- rbicop(200, "clayton", 90, 2)
bivariate_fit <- bicop(u2, family_set = "par")
bivariate_fit

dbicop(u2[1:4, ], bivariate_fit)
tail_dep(bivariate_fit)

## ----fixed-model--------------------------------------------------------------
fixed <- bicop_dist("gaussian", parameters = 0.7)
dbicop(c(0.25, 0.8), fixed)
rbicop(3, fixed)

## ----persistence--------------------------------------------------------------
path <- tempfile(fileext = ".rds")
saveRDS(copula_fit, path)
restored <- readRDS(path)
unlink(path)

set.seed(102)
draws1 <- rvinecop(4, copula_fit)
set.seed(102)
draws2 <- rvinecop(4, restored)
stopifnot(isTRUE(all.equal(draws1, draws2)))

