---
title: "Model comparison and reproducible regression checks"
output: rmarkdown::html_vignette
bibliography: ../inst/references.bib
vignette: >
  %\VignetteIndexEntry{Model comparison and reproducible regression checks}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
set.seed(42)
library(clmplus)
library(ChainLadder)
```

# Updated replication workflow

The replication code has been updated because the `apc` package used by the
original implementation has been removed from CRAN. The revised code no longer
depends on `apc` and uses the current `clmplus` implementation instead. These
changes are intended to preserve the numerical results of the original analysis
while ensuring that the replication workflow can be run using packages that are
currently available.

The strings `"a"`, `"ac"`, `"ap"`, and `"apc"` below are model identifiers,
not package dependencies.

# Deterministic comparison

```{r fits}
data("AutoBI", package = "ChainLadder")
triangle <- ChainLadder::incr2cum(AutoBI$AutoBIPaid)
prepared <- AggregateDataPP(triangle)
model_ids <- c("a", "ac", "ap", "apc")
fits <- setNames(lapply(model_ids, function(id) {
  clmplus(prepared, hazard.model = id, verbose = FALSE)
}), model_ids)
predictions <- lapply(fits, predict)
```

The age-only fit reproduces chain ladder.

```{r chain-ladder-comparison}
mack <- ChainLadder::MackChainLadder(triangle)
age_prediction <- predictions[["a"]]
stopifnot(isTRUE(all.equal(
  unname(age_prediction$full_triangle),
  unname(mack$FullTriangle),
  tolerance = 1e-10
)))
data.frame(
  accident_period = seq_along(age_prediction$reserve) - 1L,
  reserve = unname(age_prediction$reserve),
  ultimate = unname(age_prediction$ultimate_cost)
)
sum(age_prediction$reserve)
```

Partial forecasting fills only the requested future calendar diagonals.

```{r partial-forecast}
one_year <- predict(fits[["apc"]], forecasting_horizon = 1)
dim(one_year$full_triangle)
dim(one_year$apc_output$lower_triangle_apc)
```

```{r plots, fig.width=7, fig.height=4}
plot(fits[["apc"]])
plot(predictions[["apc"]])
```
