Cleaning and matching the occurrence records, delimiting the calibration area (M) and cutting the predictor rasters to it.
1. Point filtering
filter_occurrences() removes records unsuitable for
niche modelling with a fixed, ordered list of transparent rules. It is
designed especially for GBIF downloads, but works on
any table with coordinates: tests whose columns are missing are skipped.
Nothing is removed silently. Each record keeps the
first test it failed in the reason column
and is kept only if it passes every active test, so every decision can
be checked.
| Group | Tests (in order) | Needs |
|---|---|---|
| Names |
name_unmatched (not resolved, or only above the genus),
name_synonym_conflict (resolves to an accepted name other
than the target; hybrid names), rank_conflict (only the
genus, or an infraspecific taxon out of scope) |
the columns of match_names(),
target_taxon
|
| Records and metadata |
invalid_coordinates, duplicate,
grid_cell_centre (atlas cell centres recognised from the
uncertainty), gbif_issue, basis_of_record,
establishment_means, coord_uncertainty,
coarse_decimals, garden_text,
settlement_text, locality_is_country,
too_old, manual_exclude,
excluded_dataset
|
GBIF columns |
| Gridded datasets |
grid_uncertainty_block, lattice_dataset,
stacked_dataset (atlas or grid data recognised per
dataset) |
datasetKey |
| CoordinateCleaner |
country_mismatch, coordinatecleaner
(centroids, institutions, zeros, GBIF HQ, urban areas) |
the CoordinateCleaner package |
| Layers |
outside_range, at_sea /
on_water, no_climate_data,
built_up, cropland, ghs_dense,
ghs_building_nearby
|
range polygon, shoreline, climate, land-cover rasters |
| Isolation and climate |
isolated_climate_outlier,
small_isolated_cluster, climate_limit,
climate_soft_limit (beyond a soft limit, kept only with a
climatic refuge nearby, e.g. a valley below cold mountains) |
climate raster, thresholds |
You choose the tests and thresholds. Two presets
give sensible defaults: "strict" for presence records used
in modelling, and "lenient" for delimiting the accessible
area (M). Climate thresholds depend on the species, so they are off
until you set them.
library(preENM)
occ <- read_gbif("0020328-260928105237408.zip") # your GBIF download
settings <- filter_settings(
"strict",
max_coord_unc_m = 1000,
climate_limit = 22, climate_soft_limit = 16, # deg C, warmest quarter
refuge_limit = 11, refuge_radius_km = 10, # e.g. an arctic-alpine plant
target_taxon = "Dryas octopetala", # accepted name
drop_tests = "too_old") # switch tests off/on
layers <- filter_layers(
range = "range_polygon.shp", # optional, any CRS
land = download_shoreline("data/coast"), # GSHHG, downloaded once
climate = "CHELSA_bio10_1981-2010_V.2.1.tif",
built = download_landcover("built", "data"), # ESA WorldCover ~1 km
cropland = download_landcover("cropland", "data"))
occ <- match_names(occ, kingdom = "Plantae") # names against GBIF
res <- filter_occurrences(occ, settings, layers,
exclude_ids = c("1701093660"), # gbifID lists
keep_ids = c("2571281411"))
res # records removed per test
filter_report(res, by = "countryCode") # which tests remove records where
filter_sensitivity(res, "climate", c(16, 18, 20, 22, 24)) # choose thresholds
record_fate(res, c("2571281411", "1701093660"))
write_filter_results(res, "results", "species_strict") # CSV files
clean <- kept(res)Only tests whose data you supply are run; the others are listed as
skipped. Optional helpers download the layers:
download_shoreline(), download_landcover() and
aggregate_ghs() (GHS-BUILT-S settlement layers). See
?filter_occurrences and ?filter_settings for
every test and threshold.
Is the name right? Records arrive under synonyms,
outdated names, misspellings, genus-only, aggregate and hybrid names.
Cleaning pipelines differ most in how they treat them, and none found
misidentified specimens without expert knowledge (Fuehrding-Potschkat et
al. 2022, Ecology and Evolution 12, e9168); records that could
not be confidently assigned to the accepted taxon are best excluded and
the losses documented (Lipinski 2026, Conservation 6, 40).
match_names() resolves each distinct name once against a
backbone and adds the matched and accepted name, the accepted species,
rank, status, match type (exact, fuzzy, higher rank, none), confidence
and flags for synonyms, hybrids, aggregates, higher-rank and fuzzy
matches:
-
backbone = "gbif"(default; rgbif),"checklistbank"(a ChecklistBank dataset, by default the Catalogue of Life) or a Darwin Core taxon table such as the World Flora Online backbone, matched locally without internet; - results are cached for the session and, with
cache_file, across sessions, so a large download is looked up only once; - for GBIF downloads the verbatim name is matched by default, so you see what GBIF’s own interpretation did.
The three name tests then come first in
filter_occurrences(). Which infraspecific taxa belong to
the unit you model is yours to declare, not a fixed rule: in polyploid
complexes cytotypes are often recorded under an aggregate or a species
name.
settings <- filter_settings(
"strict",
target_taxon = "Aus bus", # accepted name(s)
infraspecific_include = c("Aus bus subsp. bus", # in scope
"Aus bus subsp. cus"),
infraspecific_exclude = "Aus bus subsp. dus", # always out
aggregates_in_scope = TRUE, # "Aus bus agg." kept
accept_fuzzy = FALSE) # misspelled: removedDifferent data, different tests. For records of
several kinds (see data_type in
merge_occurrences()), give
filter_occurrences() a list of settings named by data type,
e.g. list(presence_only = filter_settings("strict"), presence_absence = filter_settings("lenient", drop_tests = "coarse_decimals"));
see section
16.
Relation to CoordinateCleaner. Its standard tests
are called, not re-implemented, so please also cite Zizka et al. (2019),
Methods in Ecology and Evolution 10: 744-751. The other tests
are specific to preENM: atlas grid detection, gridded
datasets, coordinate decimals, text clues, shoreline distance,
settlement, range, climate and isolation.
2. Accessible area (M)
delimit_m() draws the area the species could have
reached (the M of the BAM diagram), where background points are drawn
and to which the predictors are clipped. Instead of choosing buffer
radii by hand, one number is derived from the records: the
linking distance L. The thinned records are joined by
single-linkage clustering (their minimum spanning tree). Gaps within a
continuous range are sampling gaps; gaps between separate parts of the
range are much longer. L is the last link before the largest jump in the
sorted links (searched between 100 and 600 km by default). Everything
else follows from L: buffers of L/2 join every chain of records linked
at L into one patch.
L is a spatial connectivity threshold derived from the records, not a
dispersal distance. It depends on how densely the range was recorded as
well as on the species, and the largest gap between records need not be
a barrier to dispersal (nor every barrier the largest gap). The default
search range of 100 to 600 km suits continental ranges; for narrow
endemics, island species or very mobile animals set
link_search to the scale of the range, and check that L is
stable under other thin_km and link_search
values. If too few links fall within link_search to find a
jump, delimit_m() stops and lists the longest links instead
of choosing a value; with link_fallback = "upper" it takes
the upper end of the range, marked as a fallback in every printout. The
methods below are alternative hypotheses about accessibility, best
compared side by side with m_scenarios().
A long link may be a sampling gap (nobody looked) or a real gap
(people looked and did not find the species), and the records alone
cannot tell them apart: in simulations, sparse records joined
populations that were truly separate in up to 40% of runs
(validation/). Give effort, a raster of
recording effort such as the records of a target group per cell
(gbif_effort_rasters()), and every long link is tested: the
number of records expected in the gap along it is the effort there times
the records per unit of effort around the records. If several were
expected and none was recorded (Poisson probability of none below
effort_alpha, 0.05), the gap is taken as real, a derived L
is lowered below it and no corridor crosses it; a gap nobody recorded
stays a possible sampling gap. The records per unit of effort are
counted around each link, so parts of the range recorded at different
rates are each judged by their own. In the simulations, a recorded gap
between populations that sparse records had joined in 40% of runs kept
them apart in every run, and a gap nobody recorded changed nothing. A
gap of unsuitable habitat is real for the records but may still be
crossed by dispersal: leave such links untested with
effort_min_km, set somewhat above the distance between
records across the gap (records lie farther apart than its edges).
eff <- gbif_effort_rasters(target_table, extent = ext) # or any effort raster
m <- delimit_m(pres, effort = eff$n_records)
m # says whether L was lowered, and from whatlinking_stability() shows how much L depends on these
choices: it recomputes L at every combination of thinning grain and
search range, and on subsamples that drop a fifth of the records at
random or mostly from densely recorded areas (as if the range were
recorded less intensively there). An L that moves by more than a quarter
rests on the recording pattern as much as on the range, and alternative
M then deserve as much weight.
| Method | What it draws |
|---|---|
"delaunay" (default) |
Delaunay triangles with all edges up to L, plus L/2 buffers, closed
by L/2, holes filled. Follows concave outlines; e.g. the M of alpine
plant Dryas octopetala in Europe (L = 340 km). The closing also
joins clusters whose records are up to about 2L apart, including area
that may have been accessible though the records do not show it;
closing_mode = "strict" closes each cluster on its own, so
the patches of M are the clusters linked at L. |
"cluster_hull" |
convex (or concave, hull_ratio < 1) hull of each
cluster linked at L: fills hollows inside a cluster automatically |
"convex_hull" |
one convex hull around all records: the most generous M |
"buffer" |
buffers of fixed radius (buffer_km), e.g. as a
reference |
"regions" |
the biogeographic units that hold records (Barve et al. 2011):
ecoregions, biomes or, for freshwater taxa, river basins
(e.g. HydroBASINS) given as regions, those with at least
region_min records, optionally cut to buffers of
region_buffer_km around the records.
download_regions() fetches RESOLVE ecoregions (the update
of the WWF ecoregions), biomes and realms, the botanical countries and
other levels of the TDWG scheme for plants, and HydroBASINS |
"simulation" |
dispersal simulated from the records over the landscape
(env), with a niche ellipsoid, a dispersal kernel and
optional barriers (Machado-Stredel et al. 2021, Frontiers of
Biogeography 13, e48814; m_simulate()): it models
accessibility explicitly, but its result depends on the niche, kernel
and barrier assumptions |
"adaptive" |
spatially adaptive buffers for unevenly surveyed areas (Barbosa
2026, Biodiversity Informatics 20): each cluster linked at L
buffered by the mean distance between its records, isolated records by a
small circle (adaptive_min_km), so unsurveyed land is not
pulled into M; generous for one large, well-surveyed cluster |
eco <- download_regions("ecoregions", path = "data", extent = c(-10, 40, 35, 72))
m_eco <- delimit_m(pres, method = "regions", regions = eco, region_min = 3)
bc <- download_regions("wgsrpd3", path = "data") # botanical countriesFor several species, lineages or cytotypes, build one M per group
(call delimit_m() on each subset): individual accessible
areas improved stacked models (Cooper & Soberon 2018, Global
Ecology and Biogeography 27, 156-165), and niche comparisons should
give each group its own M (niche_overlap() with a list of
areas; Qiao et al. 2017, Scientific Reports 7, 1213).
Room for expert judgement. The automatic M can leave out areas the species could have crossed, e.g. a hollow between two mountain chains. You can then:
- add polygons drawn in a GIS (
add); - add sites known from the literature with a radius
(
add_sites); - join isolated parts by corridors along the spanning tree, up to a
second linking distance L2 (
corridors = TRUE); - choose a hull method that fills hollows;
- set L by hand (
link_km), remove areas (exclude), clip to a studyextent, or trim the sea (land).
The report states how much area the expert additions contribute, so it can be reported as expert-based.
env <- terra::rast(list.files("layers", "\\.tif$", full.names = TRUE))
occ <- merge_occurrences(GBIF = clean, Neotoma = fossils) # e.g. modern + fossil
occ$time <- ifelse(occ$source == "Neotoma", "fossil", "modern")
lk <- linking_distance(occ, group = "time") # diagnostics: is L sensible?
lk
plot_linking(lk) # the jump at L
st <- linking_stability(occ, group = "time") # L across grains, ranges, subsamples
plot_linking_stability(st)
m <- delimit_m(occ, group = "time",
extent = c(-26, 74, 38, 82), # lon/lat box
add = "additional_areas.gpkg", # expert polygons
add_sites = data.frame(name = c("Jan Mayen", "Bjornoya"),
lon = c(-8.3, 19.0), lat = c(71.0, 74.4),
buffer_km = 60))
m # L, settings and areas
plot_m_area(m) # preview: automatic M + expert additions
m_report(m, raster = env) # areas (incl. land area), records inside
m_class_shares(m, "CHELSA_kg0_1981-2010_V.2.1.tif",
labels = koppen_geiger_labels(), fact = 3) # climate types
# sensitivity: several methods side by side, compared with the default
sc <- m_scenarios(occ, group = "time", extent = c(-26, 74, 38, 82))
sc$comparison # area, records inside, overlap, Jaccard
plot_m_area(sc)
write_m_area(m, "M_area", "species_M") # GeoPackage, CSV reports, PNG maps
env_m <- crop_to_m(env, m) # predictors clipped to M


The example above uses simulated records with a hollow between two arms of the range. The default Delaunay M leaves the hollow out; an expert polygon or a cluster hull includes it.
Compare several M by default. The calibration area
was the most influential choice in simulations of model accuracy,
explaining half of its variance, more than regularisation, collinearity
treatment and spatial thinning together (Luna et al. 2024,
Biodiversity Informatics 18, 43-55). Treat
m_scenarios() as part of choosing M, not as an optional
check, and report how much the candidates differ.
M by simulated dispersal. m_simulate()
(or delimit_m(method = "simulation", env = env)) follows
Machado-Stredel et al. (2021): a niche ellipsoid on the first principal
components of the layers decides where dispersers can establish; from
random halves of the records, dispersers move over n_events
steps with a normal kernel (kernel_sd cells), and the cells
reached most often, without the 5% least accessed, form M. Cells without
values and barrier polygons cannot be crossed, so M stops
at a barrier wider than the kernel allows; the cells of all records are
always added. The grid is aggregated on disk when it is very large.
With past (the same layers for a glacial climate,
e.g. the Last Glacial Maximum), the simulation runs through a glacial
cycle, as in their “changing framework”: a transition to glacial
conditions, a glacial period, a transition back and a current period (5,
10, 5 and 10 thousand years by default, periods), in
scenarios of 1 ka, each a weighted mean of the two climates projected
with the present PCA. Populations go extinct where a new scenario is
unsuitable; cells that had values only in the past (shelves exposed at
low sea level) can carry dispersal while the glacial climate dominates,
so land bridges are crossed. M is the accessed cells with values
today.
ms <- m_simulate(occ, env_region, barrier = "mountain_ranges.gpkg",
kernel_sd = 2, n_events = 30)
ms_lgm <- m_simulate(occ, env_region, past = env_lgm, # glacial cycle
kernel_sd = 2, n_events = 5)
ms; plot(ms)
sc <- m_scenarios(occ, scenarios = list(
delaunay = list(),
simulated = list(method = "simulation", env = env_region,
simulation = list(kernel_sd = 2, n_events = 30))))Minimal background area. m_minimal()
grows circles around the centre of the records in steps of records
included, then beyond the farthest one, as in MinBAR (Rotllan-Puig &
Traveset 2021, Ecological Modelling 439, 109353), but asks a
model-free question: from which extent on does the available environment
stop changing? Consecutive extents count as stable when their
environments cannot be told apart (largest Kolmogorov-Smirnov distance
over the layers below its 5% critical value) for two steps. The stable
extent is a lower bound to compare with the other delimitations; a
continental gradient may never stabilise, and the printout then says
so.
Is the environment of M offered evenly? Uneven
availability of climates inside the calibration area biases the
estimated niche (Jimenez & Soberon 2022, Ecological
Modelling 464, 109823). m_availability() (or
m_report(m, env = env)) is the continuous analogue of
m_class_shares(): for each predictor it cuts the records’
range into bins, compares the share of M’s cells in each with an even
spread, and flags variables with a large thinly represented part, gaps,
or low evenness. Read their response curves with care, or consider a
background stratified in environmental space.
av <- m_availability(env, occ, m = m)
av # flagged predictors, in plain words
plot_m_availability(av)
3. Cutting raster files to M
crop_rasters() cuts whole folders of rasters (e.g. the
layers of every period or scenario) to M or any polygon and writes them
to a new folder. GDAL does the work file to file, so memory use stays
low. Finished files are skipped when the run is repeated, and a failing
file does not stop the others.
res <- crop_rasters(c("climate/bio", "climate/orog"), # folders of rasters
m, # or "species_M.gpkg"
out_dir = "climate/M_area",
variables = c("bio01", "bio04", "bio05", "bio06", "bio10",
"bio12", "bio17", "scd", "dem"))
table(res$status)Values are copied exactly. CHELSA stores integers
with a scale and offset in the file metadata (e.g. temperature x 10 in
Kelvin). Cropping by reading the values into R and writing them back in
the original integer type, e.g.
terra::crop(r, v, mask = TRUE, filename = ..., datatype = datatype(r)),
can round the values and drop the scale and offset. In our test it gave
errors of up to 0.95 deg C. crop_rasters() keeps the raw
values, the data type, the scale/offset and NoData, on exactly the input
grid (nothing is resampled). For a single raster in memory,
crop_to_m() is enough.
