---
title: "Get started"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Get started}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---
  
```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  message = FALSE,
  warning = FALSE,
  comment = "#>",
  eval = FALSE,
  include = TRUE,
  out.width = "100%"
)
```

The model can be used with the usual formula interface or using the `tidymodels` and `censored` structure.

Formula interface:

```{r eval = TRUE, include = TRUE}
library(lnmixsurv)
library(readr)

mod1 <- survival_ln_mixture(Surv(y, delta) ~ x,
                            sim_data$data,
                            starting_seed = 20)

mod1
```

Tidymodels approach:

```{r eval=TRUE, include=TRUE}
library(censored)
library(ggplot2)
library(dplyr)
library(tidyr)
library(purrr)

mod_spec <- survival_reg() |>
  set_engine("survival_ln_mixture", starting_seed = 20) |>
  set_mode("censored regression")

mod2 <- mod_spec |>
  fit(Surv(y, delta) ~ x, sim_data$data)      
```

The estimates are easily obtained using tidy method. See `?tidy.survival_ln_mixture` for extra options.

```{r eval = TRUE}
tidy(mod1)
tidy(mod2)
```

The predictions can be easily obtained from a fit.

```{r prediction}
library(ggplot2)
library(dplyr)
library(tidyr)
library(purrr)

models <- list(formula = mod1, tidymodels = mod2)

new_data <- sim_data$data |> distinct(x)
pred_sob <- map(models, ~ predict(.x, new_data,
                                  type = "survival",
                                  eval_time = seq(120)
))

bind_rows(pred_sob, .id = "modelo") |>
  group_by(modelo) |>
  mutate(id = new_data$x) |>
  ungroup() |>
  unnest(cols = .pred) |>
  ggplot(aes(x = .eval_time, y = .pred_survival, col = id)) +
  geom_line() +
  theme_bw() +
  facet_wrap(~modelo)
```

```{r echo = FALSE, eval = TRUE, fig.width=7}
models <- list(formula = mod1, tidymodels = mod2)

new_data <- sim_data$data |> distinct(x)

pred_sob <- map(models, ~ predict(.x, new_data,
                                  type = "survival",
                                  eval_time = seq(120)
))

bind_rows(pred_sob, .id = "modelo") |>
  group_by(modelo) |>
  mutate(id = new_data$x) |>
  ungroup() |>
  unnest(cols = .pred) |>
  ggplot(aes(x = .eval_time, y = .pred_survival, col = id)) +
  geom_line() +
  theme_bw() +
  facet_wrap(~modelo)
```