---
title: "Introduction to BayGMST"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to BayGMST}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 4.5
)
has_cmdstan <- requireNamespace("instantiate", quietly = TRUE) &&
  instantiate::stan_cmdstan_exists()
```

This vignette walks through the full BayGMST workflow end to end, using small
example datasets bundled with the package (trimmed subsets of the data used
in Bagwell et al., in prep.; see `system.file("extdata", package =
"BayGMST")`). It replaces the `config.yml`-driven scripts the package was
originally built from -- see `NEWS.md` and
`system.file("legacy-scripts", package = "BayGMST")`.

```{r setup}
library(BayGMST)
```

## 1. Load example data

```{r load-data}
proxy_matrix <- read.csv(
  system.file("extdata", "example_proxy_matrix.csv", package = "BayGMST")
)
forcing_raw <- read.csv(
  system.file("extdata", "example_forcing.csv", package = "BayGMST")
)
instrumental_raw <- read.csv(
  system.file("extdata", "example_instrumental_temperature.csv", package = "BayGMST")
)
# read.csv() mangles "Time"/"Anomaly (deg C)" headers via make.names(); give
# them stable names instead of relying on the mangled spelling.
colnames(instrumental_raw)[1:2] <- c("Time", "Anomaly")

years <- forcing_raw$year
head(proxy_matrix)
```

## 2. Reduce the proxy network to a single representative series

```{r reduce-proxies}
calib_years <- instrumental_raw$Time

rp <- reduce_proxies(
  proxy_matrix = proxy_matrix[, -1],
  years        = proxy_matrix$year,
  temp_calib   = instrumental_raw$Anomaly,
  calib_years  = calib_years,
  method       = "PCR",
  # `chunk` must be large enough that every segment (including the last,
  # shortest one) still fully contains the calibration window (1850-2000,
  # 151 years). This toy example only has 301 years total, so we use a
  # single segment (chunk >= length(years)) rather than the package
  # default of 250, which would create a too-short trailing segment here.
  chunk        = nrow(proxy_matrix)
)
rp
```

`rp` can be passed to `fit_baygmst()` directly (it is aligned to the model's
year grid by calendar year, via `as_baygmst_proxy()`); the raw series lives
in `rp$composite$RP1` if you need it. You do not have to use
`reduce_proxies()` at all -- any reduced or composited proxy series works
here; see "Using composites from other packages" below.

## 3. Transform the radiative forcings

```{r transform-forcings}
forcing <- transform_forcings(
  G = forcing_raw$CO2,
  V = forcing_raw$volcanic,
  S = forcing_raw$solar
)
```

## 4. Align everything onto the common year grid and fit the model

The proxy series is aligned automatically (by calendar year) when you pass
the `reduce_proxies()` output itself; the instrumental series still needs
aligning onto `years` by hand, with `NA` marking the pre-instrumental years
the model will reconstruct:

```{r align}
instrumental_T <- instrumental_raw$Anomaly[match(years, instrumental_raw$Time)]
```

Fitting requires a working CmdStan installation (via \pkg{cmdstanr} /
\pkg{instantiate}); see `vignette("cmdstanr", package = "cmdstanr")` if you
don't have one yet. The chunk below is skipped if none is found.

```{r fit, eval = has_cmdstan}
fit <- fit_baygmst(
  proxy          = rp,
  instrumental_T = instrumental_T,
  forcing_G      = forcing$G,
  forcing_V      = forcing$V,
  forcing_S      = forcing$S,
  years          = years,
  chains         = 2,
  parallel_chains = 2,
  iter_warmup    = 300,
  iter_sampling  = 1000,
  seed           = 1
)
summary(fit)
```

## 5. Visualize the reconstruction

`plot()` on a fitted model draws the summary figure used in the PReSto
manuscript: the reconstruction on top and the posterior densities of the
model parameters below (this needs the 'patchwork' package).

```{r plot-fit, eval = has_cmdstan && requireNamespace("patchwork", quietly = TRUE), fig.height = 6}
plot(fit)
```

The panels are also available individually:

```{r plot-reconstruction, eval = has_cmdstan}
plot_reconstruction(fit)
```

```{r plot-trace, eval = has_cmdstan}
plot_trace(fit)
```

```{r plot-posteriors, eval = has_cmdstan}
plot_posterior_densities(fit)
```

## 6. Cross-validate

```{r cv, eval = has_cmdstan}
cv <- cv_baygmst(
  proxy          = rp,
  instrumental_T = instrumental_T,
  forcing_G      = forcing$G,
  forcing_V      = forcing$V,
  forcing_S      = forcing$S,
  years          = years,
  nfold          = 3,
  chains         = 2,
  parallel_chains = 2,
  iter_warmup    = 300,
  iter_sampling  = 1000,
  seed           = 1
)
cv
plot_cv(cv)
```

## 7. Using composites from other packages

`reduce_proxies()` is one way to produce the model's proxy input, but not
the only one. `fit_baygmst()`'s proxy equation estimates its own intercept
and slope against temperature, so any reduced or composited proxy series on
a reasonable scale works -- a standardized (z-score) composite or a
temperature-anomaly-scale series is appropriate; a raw-unit series with
large numerical magnitude should be standardized first.

`as_baygmst_proxy()` normalizes the common shapes such a series arrives in.
In particular, it accepts composite objects of the shape produced by
compositing packages in the LiPD ecosystem (such as the in-development
[compositeR](https://github.com/nickmckay/compositeR) package, whose
`compositeEnsembles2()` is the intended primary pathway for building
BayGMST inputs from paleoclimate data): a list carrying `$ages` (in years
BP, i.e. before 1950 CE) and `$composite` (rows = time steps, columns =
ensemble members). Here is a synthetic stand-in:

```{r byo-composite}
set.seed(1)
composite_ens <- list(
  ages      = seq(250, -50, by = -1),               # 1700-2000 CE, in yr BP
  composite = matrix(rnorm(301 * 50, sd = 0.2), 301, 50) +
    seq(-0.2, 0.4, length.out = 301)                # 50 ensemble members
)

proxy_input <- as_baygmst_proxy(composite_ens)
proxy_input
```

Ages are converted to calendar years and the ensemble is collapsed to its
median series (compositing uncertainty is therefore not yet propagated into
the posterior; the object records `n_ensemble` so this can become an
ensemble-aware pathway in a future release). The result can be passed
straight to `fit_baygmst(proxy = proxy_input, ...)`, which aligns it to
`years` by calendar year and errors informatively if any requested year is
not covered. Bare numeric vectors, `data.frame`s with year and value
columns, and time-by-ensemble matrices work the same way -- see
`?as_baygmst_proxy`.

## Known limitations

See `NEWS.md` for the modeling decisions and known limitations of this
release (for example, `reduce_proxies(method = "SIR")` is experimental).
The data in this vignette are synthetic, so its reconstructions should not
be over-interpreted.
