---
title: "Vulnerability surfaces"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Vulnerability surfaces}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 7,
  fig.height = 5
)
```

# Vulnerability surfaces

```{r}
library(demovuln)
```

```{r}
A <- matrix(
  c(0.0, 0.4,
    2.0, 0.7),
  nrow = 2,
  byrow = FALSE
)

model <- matrix_population_model(
  A,
  adult_stages = 2,
  juvenile_stages = 1
)
```

```{r}
grid <- perturbation_grid(
  magnitudes = seq(0, 1, length.out = 11),
  durations = 0:3,
  periods = c(1, 2, 3, 5, 10)
)

out <- run_grid(
  model,
  target = "adult_survival",
  grid = grid,
  t_max = 50,
  recovery_steps = 10
)

out$vulnerability
head(out$table)
```

```{r}
tab <- subset(out$table, duration == 1 & feasible)

mat <- tapply(
  tab$population_reduction,
  list(tab$magnitude, tab$period),
  mean
)

image(
  x = as.numeric(rownames(mat)),
  y = as.numeric(colnames(mat)),
  z = mat,
  xlab = "Magnitude",
  ylab = "Period",
  main = "Population reduction"
)

contour(
  x = as.numeric(rownames(mat)),
  y = as.numeric(colnames(mat)),
  z = mat,
  add = TRUE
)
```
