On a few hundred sites every accumulation rule runs in a fraction of a second. On thousands of sites the run time and memory depend on three choices: the backend that answers nearest-neighbour queries, whether a distance matrix is precomputed, and the number of threads. This article measures each choice on simulated surveys of 2,000 to 20,000 sites and ends with settings for large runs. Installation is in Get started; the rules themselves are described in Choosing an accumulation order.
Check which backend
spacc()picks.Time the backends at increasing site counts.
Decide whether a precomputed distance matrix helps.
Set the number of threads.
Simulated surveys
The timings use surveys of n sites at random positions
in a 100 by 100 square, with 200 species each present at a site with
probability 0.05. Run time depends on the number of sites, seeds and
threads, and hardly on the species pattern, so random presences are
enough here.
sim_survey <- function(n, n_species = 200) {
set.seed(n)
list(coords = data.frame(x = runif(n, 0, 100), y = runif(n, 0, 100)),
species = matrix(rbinom(n * n_species, 1, 0.05), n, n_species))
}
timed <- function(expr) unname(system.time(expr)["elapsed"])The run times below were measured on the machine that built this page, an Intel Core i9-14900K with 32 threads and 64 GB of memory, running Windows and R 4.6.1. On another machine the absolute times change; the ratios between backends are the part to read.
Which backend spacc() picks
The rules nn_walk and kncn repeatedly ask
which unvisited site is nearest to a point. With
backend = "auto", the default, spacc() answers
these queries by a scan over all unvisited sites (the exact backend) for
up to 500 sites and from an index above 500. For nn_walk
the index is a ball tree, which works for Euclidean and haversine
distances alike; each visited site is removed from it, so a query only
meets sites that are still unvisited. For kncn the query
point is the centroid, which moves little from one step to the next. The
index keeps each unvisited site’s distance from an earlier centroid, and
a site’s distance is computed again only when the centroid has since
moved far enough for that site to be the nearest. The
backend element of the result records the choice; the index
is labelled kdtree, the value of the backend
argument that selects it.
small <- sim_survey(400)
large <- sim_survey(2000)
c(n400 = spacc(small$species, small$coords, method = "nn_walk",
n_seeds = 10, progress = FALSE)$backend,
n2000 = spacc(large$species, large$coords, method = "nn_walk",
n_seeds = 10, progress = FALSE)$backend)
#> n400 n2000
#> "exact" "kdtree"The rule knn sorts the sites by distance from each focal
point and needs neither a matrix nor a tree; its backend reads
fixed_focus. gaussian and cone
compute the distances they need from the coordinates, and
random and collector use none.
Both backends follow the same rule and break ties between sites at exactly equal distance the same way, by the lower site index, so with the same seed they return identical orders:
same_orders <- function(method) {
e <- spacc(large$species, large$coords, method = method,
backend = "exact", n_seeds = 20, seed = 1, progress = FALSE)
k <- spacc(large$species, large$coords, method = method,
backend = "kdtree", n_seeds = 20, seed = 1, progress = FALSE)
identical(e$orders, k$orders)
}
c(nn_walk = same_orders("nn_walk"), kncn = same_orders("kncn"))
#> nn_walk kncn
#> TRUE TRUERun times by backend
The chunk below times 50 seeds of each rule and backend at 2,000 and 5,000 sites, using all threads.
grid <- expand.grid(method = c("knn", "kncn", "nn_walk"),
backend = c("exact", "kdtree"), n = c(2000, 5000),
stringsAsFactors = FALSE)
grid <- grid[!(grid$method == "knn" & grid$backend == "kdtree"), ]
grid$seconds <- NA_real_
for (i in seq_len(nrow(grid))) {
d <- sim_survey(grid$n[i])
grid$seconds[i] <- timed(spacc(d$species, d$coords,
method = grid$method[i], backend = grid$backend[i],
n_seeds = 50, progress = FALSE))
}| Method | Backend | 2,000 sites (s) | 5,000 sites (s) |
|---|---|---|---|
| knn | fixed focus | 0.01 | 0.03 |
| kncn | exact | 0.03 | 0.14 |
| nn_walk | exact | 0.05 | 0.38 |
| kncn | kdtree | 0.02 | 0.04 |
| nn_walk | kdtree | 0.01 | 0.03 |
For nn_walk the tree is the faster backend, and the gap
grows with the number of sites, because the exact backend scans a full
row of the matrix at every step. For kncn the exact backend
computes the distance from the centroid to every unvisited site at every
step, without a matrix, and the index is ahead at both sizes.
knn is as fast as the fastest walk at both sizes.
At 20,000 sites the exact backend of nn_walk needs a
matrix of 20,000 by 20,000 values, 3.2 GB, so it is left out here. The
other paths:
big <- sim_survey(20000)
c(knn = timed(spacc(big$species, big$coords, method = "knn",
n_seeds = 50, progress = FALSE)),
kncn_exact = timed(spacc(big$species, big$coords, method = "kncn",
backend = "exact", n_seeds = 50,
progress = FALSE)),
kncn_tree = timed(spacc(big$species, big$coords, method = "kncn",
backend = "kdtree", n_seeds = 50,
progress = FALSE)),
nn_walk_tree = timed(spacc(big$species, big$coords, method = "nn_walk",
backend = "kdtree", n_seeds = 50,
progress = FALSE)))
#> knn kncn_exact kncn_tree nn_walk_tree
#> 0.04 2.45 0.11 0.09At this size the scan of the exact backend shows for
kncn as well, and the index, which auto picks,
is the faster of the two.
Under haversine distance a tree query evaluates great-circle
distances, while the exact backend of nn_walk reads them
from its matrix. The chunk below runs both backends on one thread:
lonlat_survey <- function(n) {
d <- sim_survey(n)
d$coords <- data.frame(x = d$coords$x * 0.4 - 10, y = d$coords$y * 0.35 + 35)
d
}
hav <- expand.grid(backend = c("exact", "kdtree"), n = c(1000, 4000),
stringsAsFactors = FALSE)
hav$seconds <- mapply(function(backend, n) {
d <- lonlat_survey(n)
timed(spacc(d$species, d$coords, method = "nn_walk",
distance = "haversine", backend = backend, n_seeds = 50,
n_cores = 1, progress = FALSE))
}, hav$backend, hav$n)
hav
#> backend n seconds
#> 1 exact 1000 0.11
#> 2 kdtree 1000 0.04
#> 3 exact 4000 2.14
#> 4 kdtree 4000 0.20The tree is the faster backend at both sizes, and the gap grows with the number of sites.
Precomputing distances
distances() computes the matrix once and returns a
spacc_dist object that every accumulation function accepts
in place of coordinates. Its size grows with the square of the number of
sites: 8 bytes per pair.
d5 <- sim_survey(5000)
build_time <- timed(dm <- distances(d5$coords))
c(seconds = build_time, megabytes = round(object.size(dm) / 1e6))
#> seconds megabytes
#> 0.12 200.00Every ordering rule then takes its distances from the matrix. A
supplied matrix always takes the exact backend, so for
nn_walk above a few thousand sites it is slower than the
tree the coordinates would get:
c(matrix = timed(spacc(d5$species, dm, method = "nn_walk", n_seeds = 50,
progress = FALSE)),
coords_tree = timed(spacc(d5$species, d5$coords, method = "nn_walk",
n_seeds = 50, progress = FALSE)))
#> matrix coords_tree
#> 0.21 0.02What precomputing saves is the matrix build, which the exact backend
of nn_walk otherwise repeats at every call; at 5,000 sites
that build is the time printed above. gaussian scans all
unvisited sites at every step, computing their distances from the
current site from the coordinates or reading them from a supplied
matrix:
d2 <- sim_survey(2000)
dm2 <- distances(d2$coords)
c(coords = timed(spacc(d2$species, d2$coords, method = "gaussian",
n_seeds = 50, progress = FALSE)),
matrix = timed(spacc(d2$species, dm2, method = "gaussian",
n_seeds = 50, progress = FALSE)))
#> coords matrix
#> 0.11 0.16The two times are close: at 2,000 sites the matrix build is a small
part of a gaussian run. A precomputed matrix is also the
way to bring in distances that are not Euclidean or haversine, through
the fun argument of distances() or from an
sf layer in longitude and latitude, which gives geodesic
distances in metres. A matrix only holds distances between sites, which
changes three rules, as described in Preparing
site-by-species data: knn takes sites as focal points,
kncn works from sums of squared distances, and
cone reads directions from the stored coordinates.
Threads
The seeds run independently, so they are spread over threads.
n_cores is the number of threads: the seeds are cut into
that many blocks of equal size and each block runs on its own thread.
n_cores = 1 (or parallel = FALSE) runs them
one after another. The default is detectCores() - 1.
th <- c(1, 4, 16)
secs <- sapply(th, function(t) {
timed(spacc(d5$species, d5$coords, method = "nn_walk",
backend = "exact", n_seeds = 64, n_cores = t,
progress = FALSE))
})
setNames(round(secs, 2), paste(th, "threads"))
#> 1 threads 4 threads 16 threads
#> 1.94 0.84 0.46The run time falls with the number of threads, though by less than
the thread count. On a shared machine, set n_cores below
the default before a large run so that other jobs keep their cores.
Settings for large surveys
For surveys of thousands of sites, measured on the machine above:
-
knn(fixed focus) needs no matrix and was as fast as the fastest walk at every size, under a tenth of a second for 50 seeds on 20,000 sites. -
nn_walkkeepsbackend = "auto", which picks the tree above 500 sites; do not pass aspacc_distobject for it on large surveys. -
kncnkeepsbackend = "auto"as well; neither of its backends builds a matrix. -
gaussianneeds no matrix and runs in parallel over seeds; its run time grows with the square of the number of sites. The time at 2,000 sites is in Precomputing distances. - Each seed is an independent order, so the run time grows in
proportion to
n_seeds; the seed count needed for a stable band is discussed in How spatial accumulation works.