---
title: "Getting started with spacc"
description: "One path from a site-by-species matrix and site coordinates to a spatial accumulation curve, its comparison with random order, and a first look at each analysis built on it."
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Getting started with spacc}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE, comment = "#>", fig.width = 6.5, fig.height = 4.5,
  dev = "svglite", fig.ext = "svg", dev.args = list(pointsize = 14)
)
has_ggplot <- requireNamespace("ggplot2", quietly = TRUE)
```

spacc builds species accumulation curves in which sites enter the count in
spatial order: starting from a point in the study area, the nearest sites
are added first. This tutorial starts from a table of species records per
site and a table of site coordinates, and ends with a spatial accumulation
curve, its summary and plot, a test against the classical random-order
curve, and one short example of each analysis built on the same orders. It
assumes basic R: matrices, data frames and function calls.

## Installation

Install the released version from CRAN:

```{r install-cran, eval = FALSE}
install.packages("spacc")
```

The development version is on GitHub:

```{r install-dev, eval = FALSE}
# install.packages("pak")
pak::pak("gcol33/spacc")
```

The development version compiles C++ code;
[Installation](https://gillescolling.com/spacc/#installation) shows how to
set up a compiler.

## A first accumulation curve

The examples use a simulated survey: 80 sites scattered over a 100 by 100
square and 40 species. Each species has a centre, and its chance of
occurring at a site falls with the squared distance to that centre, so
every species occupies a patch about 60 units across. Neighbouring sites
therefore share species, which is the situation spatial accumulation is
built for.

```{r simulate}
library(spacc)
set.seed(42)
n_sites <- 80
n_species <- 40
coords <- data.frame(x = runif(n_sites, 0, 100), y = runif(n_sites, 0, 100))
species <- matrix(0L, n_sites, n_species)
for (j in seq_len(n_species)) {
  cx <- runif(1, 20, 80)
  cy <- runif(1, 20, 80)
  p <- exp(-0.001 * ((coords$x - cx)^2 + (coords$y - cy)^2))
  species[, j] <- rbinom(n_sites, 1, p)
}
colnames(species) <- paste0("sp", seq_len(n_species))
```

`spacc()` takes two inputs. `species` is the site-by-species matrix: one
row per site, one column per species, holding 0/1 presence or abundance
counts. `coords` holds the site positions in columns `x` and `y`, one row
per site in the same order as `species`; the two tables are matched by row
position, not by a key. `n_seeds` sets how many curves are drawn, each from
a different starting point.

```{r first-call}
sac <- spacc(species, coords, n_seeds = 30, progress = FALSE)
sac
```

The result is a `spacc` object; the inputs are left unchanged. Its element
`curves` is a matrix with one row per seed and one column per accumulation
step: entry (s, k) is the number of species found in the first k sites
visited from seed s. Abundances count as presences here, since a curve only
asks whether a species is new.

```{r curves}
dim(sac$curves)
sac$curves[1:3, 1:8]
```

Every seed ends at the same value, the 40 species of the whole survey, so
seeds differ only in how fast they get there. `summary()` reduces the seeds
to a mean curve and a band between the 2.5% and 97.5% quantiles of the
seeds at each step. Saturation is the first step at which the mean curve
reaches 90% of its final value (`saturation_threshold` changes the 90%).
The CV at midpoint is the standard deviation across seeds divided by the
mean, halfway along the curve, in percent.

```{r summary}
summary(sac)
```

`plot()` draws the mean curve and the band. A wide band means the species
found in the first sites depend strongly on where the survey starts.
`ci_level` sets the width of the band and `ci = FALSE` leaves it out.

```{r plot-sac, eval = has_ggplot, fig.alt = "Spatial accumulation curve: the mean number of species rises from about ten at one site to forty at eighty sites, with a shaded band that is widest in the first third of the curve."}
plot(sac)
```

`as.data.frame()` returns the same summary as a table, one row per step,
for your own plots or for export.

```{r as-df}
head(as.data.frame(sac), 3)
```

## Comparing with random order

The classical accumulation curve adds sites in random order. The same call
with `method = "random"` draws it, and `c()` combines named curves into one
object that `plot()` overlays.

```{r random}
rnd <- spacc(species, coords, n_seeds = 30, method = "random",
             progress = FALSE)
both <- c(spatial = sac, random = rnd)
```

```{r plot-both, eval = has_ggplot, fig.alt = "Two accumulation curves on the same axes: the random-order curve rises faster than the spatial curve and both reach forty species at eighty sites."}
plot(both)
```

The random curve rises faster because each step mixes sites from different
patches, while the spatial curve keeps adding neighbours that share
species. `compare()` tests the difference in the area under the two mean
curves by permuting seeds between them.

```{r compare}
set.seed(1)
compare(sac, rnd, n_perm = 199)
```

Six other ordering rules and user-supplied orders are compared in
[Choosing an accumulation order](https://gillescolling.com/spacc/articles/accumulation-orders.html);
grouped curves and the tests in `compare()` are covered in
[Comparing curves between groups and regions](https://gillescolling.com/spacc/articles/comparing-curves.html).

## Reading your own data

Field data often sit in one file with a site identifier, coordinates under
other names, and one column per species. The file below is written to a
temporary path so this page runs anywhere; it uses `plot`, `easting` and
`northing` for the identifier and coordinates.

```{r write-csv}
field <- data.frame(plot = sprintf("P%02d", seq_len(n_sites)),
                    easting = coords$x, northing = coords$y, species)
path <- tempfile(fileext = ".csv")
write.csv(field, path, row.names = FALSE)
```

Read the file, keep the species columns as a matrix, and rename the
coordinate columns to `x` and `y`. Because both tables come from the same
rows, their order matches.

```{r read-csv}
dat <- read.csv(path)
sp_cols <- setdiff(names(dat), c("plot", "easting", "northing"))
x <- as.matrix(dat[, sp_cols])
xy <- data.frame(x = dat$easting, y = dat$northing)
spacc(x, xy, n_seeds = 30, progress = FALSE)
```

For another file, change the path in `read.csv()` and the three column
names in `setdiff()` and `data.frame()`. Records in long format (one row
per species and site), longitude and latitude, and `sf` points are covered
in [Preparing site-by-species data](https://gillescolling.com/spacc/articles/data-preparation.html).

## Common errors

The errors below come from the two input tables not fitting together.
Each entry shows the message and the corrected call.

A site table with the identifier still in it is not numeric:

```{r err-numeric, error = TRUE}
spacc(dat[, c("plot", sp_cols)], xy, progress = FALSE)
```

Keep only the species columns, as `x` in
[Reading your own data](#reading-your-own-data) does:

```{r fix-numeric}
spacc(dat[, sp_cols], xy, n_seeds = 30, progress = FALSE)
```

Coordinates under their original names are not found:

```{r err-coords, error = TRUE}
spacc(x, dat[, c("easting", "northing")], progress = FALSE)
```

Rename them to `x` and `y`:

```{r fix-coords}
names(xy)
spacc(x, xy, n_seeds = 30, progress = FALSE)
```

Filtering one table and not the other leaves different row counts:

```{r err-rows, error = TRUE}
keep <- dat$easting < 50
spacc(x[keep, ], xy, progress = FALSE)
```

Apply the same filter to both:

```{r fix-rows}
spacc(x[keep, ], xy[keep, ], n_seeds = 30, progress = FALSE)
```

A filter that drops rows from both tables keeps them paired. Sorting one
table and not the other raises no error, because the row counts still
agree; the species are then attached to the wrong sites.

## Other measures along the same orders

Each function below visits the sites in the same spatial orders as
`spacc()` and counts something other than species. One short call shows
what it returns; the linked article covers it in full. The abundance matrix
`abund` gives each species a Poisson count at every site, since several of
these measures weigh species by their abundance.

```{r abund}
set.seed(7)
abund <- matrix(rpois(n_sites * n_species, lambda = 2), n_sites, n_species)
colnames(abund) <- colnames(species)
```

### Hill numbers

Hill numbers of order q count effective species: q = 0 is richness, q = 1
the exponential of Shannon entropy, q = 2 the inverse Simpson index.

```{r hill, eval = has_ggplot, fig.alt = "Three Hill-number accumulation curves: q = 0 highest, q = 1 in the middle, q = 2 lowest."}
hill <- spaccHill(abund, coords, q = c(0, 1, 2), n_seeds = 20,
                  progress = FALSE)
plot(hill)
```

[Accumulating Hill numbers and partitioning diversity](https://gillescolling.com/spacc/articles/hill-numbers.html)
covers the orders, the alpha, beta and gamma partition, and evenness.

### Beta diversity

`spaccBeta()` measures how different each new site is from the sites
already visited, split into turnover (other species) and nestedness (a
subset of the same species) after Baselga (2010).

```{r beta}
beta <- spaccBeta(species, coords, n_seeds = 20, progress = FALSE)
as.data.frame(beta)[c(1, 5, 20), 1:4]
```

Each row is a step of the walk, comparing the next site with the sites
visited so far.

[Accumulating beta diversity](https://gillescolling.com/spacc/articles/beta-diversity.html) covers the
indices and the Hill-number version.

### Sample coverage

Sample coverage is the estimated share of all individuals in the community
that belong to species already recorded. `spaccCoverage()` tracks it along
the walk, and `interpolateCoverage()` reads the richness reached at chosen
coverage levels.

```{r coverage}
cov <- spaccCoverage(abund, coords, n_seeds = 20, progress = FALSE)
colMeans(interpolateCoverage(cov, target = c(0.90, 0.95)))
```

[Standardising by sample coverage](https://gillescolling.com/spacc/articles/coverage.html) explains the
estimators and when to standardise by coverage.

### Total richness

Nonparametric estimators infer how many species were missed from the
species seen only once or twice. `chao2()` uses incidence: how many species
occur at one site and how many at two.

```{r chao2}
chao2(species)
```

Every species of the simulated survey occurs at ten or more sites, so no
species is seen at only one or two, and the estimate equals the observed
40.

[Estimating total richness](https://gillescolling.com/spacc/articles/richness-estimators.html) compares
the estimator family.

### Extrapolation

`extrapolate()` fits an asymptotic model to the mean curve; its asymptote
is an estimate of the richness a complete survey would record.

```{r extrapolate}
fit <- extrapolate(sac, model = "michaelis-menten")
fit
```

[Extrapolating curves and predicting richness](https://gillescolling.com/spacc/articles/extrapolation.html)
compares the models and their predictions.

### Distance decay

`betaDecay()` relates the dissimilarity of every pair of sites to the
distance between them and fits a decay model.

```{r decay}
betaDecay(species, coords, model = "exponential", progress = FALSE)
```

[Measuring distance decay and zeta diversity](https://gillescolling.com/spacc/articles/turnover.html)
covers distance decay and zeta diversity.

### Per-site maps

`spaccMetrics()` runs one curve from every site and reduces each to a few
numbers, such as the area under the curve, giving one value per site to map.

```{r metrics}
m <- spaccMetrics(species, coords, metrics = c("slope_10", "auc"),
                  progress = FALSE)
head(as.data.frame(m), 3)
```

[Mapping per-site metrics and wavefronts](https://gillescolling.com/spacc/articles/site-maps.html) maps
these values and turns them into `sf` layers.

## Methods shared by the results

Every result object has `print()`, `summary()`, `plot()` and
`as.data.frame()`, so the calls above work the same way on a Hill, beta or
coverage object. `[` keeps a subset of seeds, here the first five.

```{r subset}
sac[1:5]
```

`plot()` returns a ggplot object, so further layers are added with `+`.
`ggplot2::autoplot()` returns the same figure.

```{r autoplot, eval = has_ggplot, fig.alt = "The spatial accumulation curve with a horizontal dashed line at forty species."}
ggplot2::autoplot(sac) +
  ggplot2::geom_hline(yintercept = n_species, linetype = "dashed")
```

## Where next

Building curves:

- [Preparing site-by-species data](https://gillescolling.com/spacc/articles/data-preparation.html): input
  structures, long-format records, `sf` points and malformed input.
- [Choosing an accumulation order](https://gillescolling.com/spacc/articles/accumulation-orders.html): the
  seven ordering rules and user-defined orders on one dataset.
- [Comparing curves between groups and regions](https://gillescolling.com/spacc/articles/comparing-curves.html):
  `compare()`, species groups and per-country curves.
- [Running on many sites](https://gillescolling.com/spacc/articles/large-data.html): backends, precomputed
  distances and threads, with timings.

Diversity:

- [Accumulating Hill numbers and partitioning diversity](https://gillescolling.com/spacc/articles/hill-numbers.html)

- [Accumulating beta diversity](https://gillescolling.com/spacc/articles/beta-diversity.html)

- [Accumulating phylogenetic and functional diversity](https://gillescolling.com/spacc/articles/phylo-functional.html)

Effort and completeness:

- [Rarefying to equal effort](https://gillescolling.com/spacc/articles/rarefaction.html)

- [Standardising by sample coverage](https://gillescolling.com/spacc/articles/coverage.html)

- [Estimating total richness](https://gillescolling.com/spacc/articles/richness-estimators.html)

- [Extrapolating curves and predicting richness](https://gillescolling.com/spacc/articles/extrapolation.html)

Spatial patterns:

- [Measuring distance decay and zeta diversity](https://gillescolling.com/spacc/articles/turnover.html)

- [Testing turnover against null models](https://gillescolling.com/spacc/articles/null-models.html)

- [Relating diversity to area](https://gillescolling.com/spacc/articles/area-relationships.html)

- [Mapping per-site metrics and wavefronts](https://gillescolling.com/spacc/articles/site-maps.html)

- [Partitioning spatial structure](https://gillescolling.com/spacc/articles/spatial-structure.html)

Background:

- [How spatial accumulation works](https://gillescolling.com/spacc/articles/theory.html): the ordering
  rules as formulas, distances and the nearest-neighbour backend.

## References

Baselga, A. (2010). Partitioning the turnover and nestedness components of
beta diversity. *Global Ecology and Biogeography*, 19, 134-143.
