---
title: "Landscape connectivity indicators for Tasmania"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Landscape connectivity indicators for Tasmania}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

This vignette calculates four connectivity indicators for Tasmania from the
bundled rasters. The indicators and the multi-resolution method are described
in [Valavi et al. (2026)](https://doi.org/10.32942/X2S68V).

| Indicator | R call | Interpretation |
| --- | --- | --- |
| Connectedness | `connectedness(..., option = 1)` | Connectivity to condition-weighted habitat in the surrounding landscape |
| Connected habitat (a.k.a. connectivity-adjusted condition) | `connectedness(..., option = 3)` | Square root of connectedness multiplied by local habitat condition |
| Protected Area Connectedness Index (PARC-connectedness) | `connectedness(..., pa_file = ...)` | Connectedness evaluated at protected cells, optionally restricted to protected destinations |
| Bioclimatic Ecosystem Resilience Index (BERI) | `beri(...)` | Capacity to retain biodiversity under climate change, from connected habitat that stays compositionally similar across climate scenarios |

All indicator results stay in memory as georeferenced `terra::SpatRaster` objects
and are plotted directly. No indicator output files or data downloads are needed.

## 1. Read the bundled data

The example rasters are installed with the package; `system.file()` returns
their paths.

```{r inputs}
library(connectivity)
library(terra)

condition_file <- system.file("extdata", "site_condition.tif", package = "connectivity")
pa_file <- system.file("extdata", "pa_proportion.tif", package = "connectivity")
climate_dir <- system.file("extdata", "transgrids", package = "connectivity")

condition <- rast(condition_file)
pa <- rast(pa_file)
condition

global(condition, c("min", "max"), na.rm = TRUE)
global(pa, c("min", "max", "mean"), na.rm = TRUE)
```

The rasters cover Tasmania, Australia on a common grid: 588 columns by 516 rows,
EPSG:4326, at 30 arc-second resolution (approximately 1 km). Habitat condition
and protected-area proportions range from zero to one; missing cells are `NA`.
Auxiliary rasters must share the condition raster's CRS, resolution and pixel
grid and cover the analysis window. They are not resampled automatically.

```{r input-maps, fig.width=9, fig.height=4, fig.cap="Bundled habitat condition and protected-area proportions."}
plot(
    c(condition, pa),
    main = c("Habitat condition", "Protected fraction"),
    col = hcl.colors(100, "viridis"),
    range = c(0, 1)
)
```

## 2. Choose resolution levels

Aggregation levels are generated from the base raster during each calculation.
Use `resolution_info()` before calculating the
indicators to preview candidate grid dimensions, cell counts, resolutions and
approximate search reach. It accepts a raster filename or a `SpatRaster` and
reads only grid metadata.

The default candidates are powers of two from 1 to 512. Set `outer_window` to
the value intended for the indicator calculations. Here, `min_dimension = 16`
flags candidates with fewer than 16 cells in either dimension for review.

```{r resolution-planning}
resolution_plan <- resolution_info(
    condition,
    levels = 2^(0:9),
    outer_window = 7,
    min_dimension = 16
)
```

The helper prints the summary and invisibly returns the numeric planning table
saved here as `resolution_plan`. Dimensions round up at each aggregation level.
Search reach is `outer_window * level * max(res(condition))` in native coordinate
units, with an additional kilometre estimate. For geographic rasters, that
estimate uses the raster's centre latitude. This planning span differs from the
dispersal bandwidths specified by `lambdas` in kilometres.

For this grid, level 32 leaves 19 columns and 17 rows; level 64 leaves only
10 columns and 9 rows and receives a small-grid flag. Levels through 32 retain
at least 16 cells in each dimension, so the examples use
`levels = c(2, 4, 8, 16, 32)`. Level 1 is always included by the engine.
The flags guide review and do not prevent a calculation or select levels
automatically. All calls below use two worker threads; `n_threads = NULL` uses
all available cores.

## 3. Connectedness

`option = 1` returns raw connectedness, describing how well each cell is linked
to condition-weighted habitat in its surrounding landscape.

```{r connectedness}
conns <- connectedness(
    condition_file = condition,
    lambdas = c(2, 20, 50),
    max_cost = 2,
    window_size = 5,
    outer_window = 7,
    levels = c(2, 4, 8, 16, 32),
    option = 1,
    window_mode = "circular",
    n_threads = 2
)

plot(
    conns,
    main = "Connectedness",
    col = hcl.colors(100, "fall", rev = TRUE),
    range = c(0, 0.8)
)
```

## 4. Connected habitat

`option = 3` (the default) calculates Connected Habitat (a.k.a.
connectivity-adjusted condition), `sqrt(connectedness * condition)`, so local
habitat condition also affects the score. `option = 2` would return the product
without the square root.

```{r connected-habitat}
connhabitat <- connectedness(
    condition_file = condition,
    lambdas = c(2, 20, 50),
    max_cost = 2,
    window_size = 5,
    outer_window = 7,
    levels = c(2, 4, 8, 16, 32),
    option = 3,
    window_mode = "circular",
    n_threads = 2
)

plot(
    connhabitat,
    main = "Connected habitat",
    col = hcl.colors(100, "fall", rev = TRUE),
    range = c(0, 0.8)
)
```

## 5. PARC-connectedness

Supplying `pa_file` calculates the Protected Area Connectedness Index
(PARC-connectedness). The condition used
for habitat and traversal is the maximum of habitat condition and protected
fraction, and only cells with a positive protected fraction receive scores.
With `pa_to_pa = FALSE`, destinations may include the surrounding unprotected
landscape. Set `pa_to_pa = TRUE` to restrict destinations to protected cells,
weighted by protected fraction at coarser levels. PARC returns raw
connectedness regardless of `option`.

```{r parc}
parc <- connectedness(
    condition_file = condition,
    pa_file = pa,
    pa_to_pa = FALSE,
    lambdas = c(2, 20, 50),
    max_cost = 2,
    window_size = 5,
    outer_window = 7,
    levels = c(2, 4, 8, 16, 32),
    window_mode = "circular",
    n_threads = 2
)

plot(
    parc,
    main = "PARC-connectedness",
    col = hcl.colors(100, "viridis"),
    range = c(0, 1)
)
```

## 6. BERI

The Bioclimatic Ecosystem Resilience Index (BERI) combines habitat
connectedness with compositional similarity under climate scenarios, derived
from generalised dissimilarity modelling (GDM). Each climate file contains 19 bands in matching order. `1990.tif`
is the current baseline; the six other files are future scenarios. Scenario
identifiers below are the original filenames.

```{r climate-inputs}
current_file <- file.path(climate_dir, "1990.tif")
scenario_names <- c(
    "ACC50_85", "GFD50_85", "IPS50_26",
    "IPS50_45", "IPS50_60", "IPS50_85"
)

future_files <- file.path(climate_dir, paste0(scenario_names, ".tif"))
basename(future_files)

current_climate <- rast(current_file)
nlyr(current_climate)

compareGeom(condition, current_climate, lyrs = FALSE)
```

The climate grids share the condition grid, so the resolution plan above also
applies to them. Pass the current baseline first and future scenarios in the
order shown. The result is one BERI raster combining these scenarios, without
the Connected Habitat condition multiplication or square-root transformation.
Omitting `future_files` calculates the current-climate index only.

```{r beri}
beri_map <- beri(
    condition_file = condition,
    current_file = current_file,
    future_files = future_files,
    lambdas = c(2, 20, 50),
    max_cost = 2,
    window_size = 5,
    outer_window = 7,
    levels = c(2, 4, 8, 16, 32),
    window_mode = "circular",
    n_threads = 2
)

plot(
    beri_map,
    main = "BERI",
    col = hcl.colors(100, "RdYlGn"),
    range = c(0, 0.8)
)
```

## 7. Compare all indicators

The five panels show the input habitat condition and four indicator results,
cropped to the Tasmanian mainland for display. Calculations above use the
complete bundled landscape. Display ranges are zero to one for the first four
panels and zero to 0.8 for BERI.

```{r comparison, fig.width=10, fig.height=7, fig.cap="Habitat condition and the four connectivity indicators on the Tasmanian mainland."}
mainland <- ext(144.4, 148.6, -43.7, -40.6)
maps <- list(condition, conns, connhabitat, parc, beri_map)
titles <- c(
    "(a) Habitat condition",
    "(b) Connectedness",
    "(c) Connected habitat",
    "(d) PARC-connectedness",
    "(e) BERI"
)

condcol <- hcl.colors(100, "fall", rev = TRUE)
palettes <- list(
    condcol, condcol, condcol,
    hcl.colors(100, "viridis"), hcl.colors(100, "RdYlGn")
)

old_par <- par(mfrow = c(2, 3), mar = c(3, 3, 3, 4))
for (i in seq_along(maps)) {
    plot(
        terra::crop(maps[[i]], mainland),
        main = titles[i],
        col = palettes[[i]],
        range = c(0, if (i == 5) 0.8 else 1)
    )
}
plot.new()
par(old_par)
```

## 8. Large rasters in tiles

Each call holds its analysis window in memory. For rasters too large for one
call, `make_tiles()` splits the grid into rectangular tiles whose internal edges
fall on multiples of `align_to` pixels; use the largest aggregation level.
Pass each tile as `polygon_mask` with the default open border, so each tile
reads its surrounding landscape. With `balanced = TRUE`, tile edges balance the
number of cells with data instead of tile sizes.

The example below only demonstrates that tiling does not change the result: it
calculates Connected Habitat in four tiles, merges them in memory and compares
the mosaic with the untiled result from section 4.

```{r tiles}
tiles <- make_tiles(condition, nrows = 2, ncols = 2, align_to = 32)
tiles

tile_maps <- lapply(seq_len(nrow(tiles)), function(i) {
    return(connectedness(
        condition_file = condition,
        polygon_mask = tiles[i],
        lambdas = c(2, 20, 50),
        max_cost = 2,
        window_size = 5,
        outer_window = 7,
        levels = c(2, 4, 8, 16, 32),
        option = 3,
        window_mode = "circular",
        n_threads = 2
    ))
})
mosaic <- merge(sprc(tile_maps))

# The merged tiles reproduce the whole-raster calculation.
all.equal(values(mosaic), values(connhabitat))
```

In practice, tiles are used when the whole raster is too large to process at
once, so keeping every tile result in memory defeats the purpose. Write each
tile to a file instead, for example from separate jobs using `make_tile()`,
then combine the files with `terra::merge()` or read them as one virtual
raster with `terra::vrt()`:

```{r tile-files, eval=FALSE}
tile_files <- sprintf("connected_habitat_tile_%02d.tif", tiles$id)
for (i in seq_len(nrow(tiles))) {
    connectedness(condition_file, polygon_mask = tiles[i], filename = tile_files[i])
}

habitat <- vrt(tile_files)
# Or write one merged file:
habitat <- merge(sprc(tile_files), filename = "connected_habitat.tif")
```

## Data sources and licence

The nine GeoTIFFs are distributed under **CC BY-NC-SA 4.0**, separately from the package's
MIT-licensed code. The installed data README records the grid, layer metadata,
attribution and licence:

```{r data-documentation, eval=FALSE}
file.show(system.file("extdata", "README.md", package = "connectivity"))
```

Ware, C., Valavi, R., Vickers, M., Giljohann, K. M., Mokany, K., Purvis, A.,
Walkden, P., De Palma, A., Duffin, C., Contu, S., Harwood, T., Hoskins, A.,
and Ferrier, S. (2026).
*Global biodiversity indicator data for BHI, BERI, PARC-representativeness,
PARC-connectedness and ecosystem condition (2000–2024).* Version 4.
CSIRO Data Collection. <https://doi.org/10.25919/3aka-y730>.

Valavi, R., Mokany, K., Ware, C., Vickers, M., Giljohann, K. M., and Ferrier,
S. (2026). *A scalable multi-resolution framework for connectivity-based
biodiversity indicators.* EcoEvoRxiv. <https://doi.org/10.32942/X2S68V>.
