Title: | Utility tools for Species Distribution Modelling |
---|---|
Description: | What the package does (one paragraph). |
Authors: | Gerry Ryan [aut, cre] , David Duncan [ctb], Nick Tierney [ctb] |
Maintainer: | Gerry Ryan <[email protected]> |
License: | MIT + file LICENSE |
Version: | 0.0.0.9000 |
Built: | 2024-11-18 03:09:04 UTC |
Source: | https://github.com/idem-lab/sdmtools |
Adapted from seegSDM. Reposition observations to a location within mask if within a specified distance. Useful for when coastal observations drop off jagged mask and similar
assign_nearest_land(dat_object, mask_object, max_distance, verbose = TRUE)
assign_nearest_land(dat_object, mask_object, max_distance, verbose = TRUE)
dat_object |
data.frame |
mask_object |
'SpatRaster' |
max_distance |
map units if raster is projected |
verbose |
provide verbose output. Default is TRUE |
modified data object minus observations not within specified maximum distance of mask
Create an example mask within a given raster
example_mask(raster, pc_threshold = NULL)
example_mask(raster, pc_threshold = NULL)
raster |
generated from example_raster for example |
pc_threshold |
A threshold percentile to divide mask / non mask elements |
A spatRaster
example_mask(example_raster(), pc_threshold=0.5)
example_mask(example_raster(), pc_threshold=0.5)
Create example raster for use in examples
example_raster(seed = NULL, layername = NULL)
example_raster(seed = NULL, layername = NULL)
seed |
A seed to pass to |
layername |
|
A SpatRaster
.
example_raster() example_raster( seed = 3.142, layername = "jabberwock_density" )
example_raster() example_raster( seed = 3.142, layername = "jabberwock_density" )
Create an example vector
example_vector(seed = NULL)
example_vector(seed = NULL)
seed |
A seed to pass to |
A SpatVector
example_vector()
example_vector()
Extracts data from raster covariate layers for modelling.
extract_covariates( covariates, presences = NULL, absences = NULL, presences_and_absences = NULL )
extract_covariates( covariates, presences = NULL, absences = NULL, presences_and_absences = NULL )
covariates |
|
presences |
|
absences |
|
presences_and_absences |
|
extract_covariates
will run correctly with either presences
only,
presences
and absences
, or presences_and_absences
only. (If all three
are included it will ignore the last one).
A tibble
containing values variables presence
and each of the
covariate layers at each location.
Gerry Ryan
library(terra) cov1 <- example_raster( seed = -44, layername = "cov1" ) cov2 <- example_raster( seed = 15.3, layername = "cov2" ) covs <- c(cov1, cov2) presences <- example_vector(seed = 68) %>% as.data.frame(geom = "xy") absences <- example_vector(seed = 9.6) %>% as.data.frame(geom = "xy") extract_covariates( covariates = covs, presences = presences, absences = absences )
library(terra) cov1 <- example_raster( seed = -44, layername = "cov1" ) cov2 <- example_raster( seed = 15.3, layername = "cov2" ) covs <- c(cov1, cov2) presences <- example_vector(seed = 68) %>% as.data.frame(geom = "xy") absences <- example_vector(seed = 9.6) %>% as.data.frame(geom = "xy") extract_covariates( covariates = covs, presences = presences, absences = absences )
A table of showing the United Nations Regional groups of Member States and World Health Organisation regions of nation states and all states with Officially Assigned ISO3166 Alpha-3 country codes.
global_regions
global_regions
global_regions
A tibble with 249 rows and 6 columns:Country name. Given name conflicts between the two data sources, names identified in country
are defined as countrycode::countrycode(global_regions$iso3, origin = "iso3c", destination = "country.name")
Alpha-2 & Alpha-3 ISO3166 country codes
World Health Organisation region
United Nations Regional group of Member States
Continent
Includes all Officially Assigned ISO3166 Alpha-3 country codes.
Not all 'countries' include a continent.
Special cases of UN regional groupings
Israel
In May 2000, Israel became a full member of the Group of Western European and other States on a temporary basis (subject to renewal), thereby enabling it to put forward candidates for election to various bodies of the General Assembly. In 2004, Israel obtained a permanent renewal to its membership.
Kiribati
As of 2010, Kiribati (geographically in Oceania) is not a member of any regional group, despite other Oceania nations belonging to the Group of Asia-Pacific States.
Türkiye
Türkiye participates fully in both the Group of Western European and other States and the Group of Asia-Pacific States, but for electoral purposes is considered a member of the Group of Western European and other States only.
While Türkiye is listed in both groupings in the original dataset; here we remove the duplication and list it only where it is a voting member, i.e., Western European and other States
United States of America
The United States of America is not a member of any regional group, but attends meetings of the Group of Western European and other States as an observer and is considered to be a member of that group for electoral purposes.
Table combined from un-regions.csv
, and who-regions.csv
, housed in
package data-raw directory.
un-regions.csv
manually created from tables on "Regional groups of Member
States"
https://www.un.org/dgacm/en/content/regional-groups
2024-02-02
who-regions.csv
was downloaded from
https://ourworldindata.org/grapher/who-regions
2024-02-02
World Health Organization – processed by Our World in Data & World Health Organization.
continent
defined by countrycode::codelist$continent
, (largely?) by
World Bank.
Imports all rasters of a given extension type from a specified directory using terra::rast
.
Based on seegSDM::importRasters
.
import_rasts(path, ext = ".grd", as_list = FALSE)
import_rasts(path, ext = ".grd", as_list = FALSE)
path |
Directory path containing rasters |
ext |
Extension type |
as_list |
|
A SpatRaster
if as_list = FALSE
, or list of SpatRaster
objects.
## Not run: rasters <- import_rasts("/data/grids/covariates") ## End(Not run)
## Not run: rasters <- import_rasts("/data/grids/covariates") ## End(Not run)
Checks whether longitude and latitude coincide with non-missing pixels of a raster. The function takes two arguments: points, a dataframe containing columns named longitude' and 'latitude', and mask is a raster. Returns a dataframe of longitude and latitude only those rows with points falling on non-missing pixels. If all points fall on missing pixels, the function throws an error.
inside_mask(points, mask)
inside_mask(points, mask)
points |
dataframe containing columns named 'longitude' and 'latitude' |
mask |
a raster |
dataframe of longitude and latitude only those rows with points falling on non-missing pixels. If all points fall on missing pixels, the function throws an error.
Makes a SpatRaster
or SpatVector
mask layer of Africa, based on shapefiles for African nations from the malaraAtlas
package.
make_africa_mask( filename = NULL, type = c("raster", "vector"), res = c("high", "low"), countries = NULL )
make_africa_mask( filename = NULL, type = c("raster", "vector"), res = c("high", "low"), countries = NULL )
filename |
Character of file path and name if mask is to be written to disc. |
type |
Character |
res |
Character |
countries |
Character of ISO3 country names. If |
Raster layers creates with extent of terra::ext(-18.0000019073486, 52.0416647593181, -34.9999987284343, 37.5416679382324)
SpatRaster
or SpatVector
in WGS 84 (EPSG:4326).
## Not run: # Create an object in workspace africa_mask_v <- make_africa_mask(type = "vector") # Save to disk make_africa_mask(filename = "africa_mask.tif", type = "raster") # or do both at once africa_mask_r <- make_africa_mask("africa_mask.tif") ## End(Not run)
## Not run: # Create an object in workspace africa_mask_v <- make_africa_mask(type = "vector") # Save to disk make_africa_mask(filename = "africa_mask.tif", type = "raster") # or do both at once africa_mask_r <- make_africa_mask("africa_mask.tif") ## End(Not run)
multispeciesPP
Make presence-only list for multispeciesPP
make_mpp_list(x, id)
make_mpp_list(x, id)
x |
A |
id |
The name of the identity column in |
The package multispeciesPP
requires a very annoying named list
format for presence-only data. This function takes a table of covariate /
bias values and an ID column (i.e. species), and returns a named list where
each element is the values corresponding to that identity only. Ugh.
A named list or data frames.
## Not run: make_mpp_list(presence_only_data, species) ## End(Not run)
## Not run: make_mpp_list(presence_only_data, species) ## End(Not run)
Masks all NA
cells across all layers, such that returned layers
have matching NA
cells.
mask_all(rasts, filename = NULL, overwrite = FALSE)
mask_all(rasts, filename = NULL, overwrite = FALSE)
rasts |
|
filename |
|
overwrite |
|
Uses a ton of RAM and will break for larger rasters.
SpatRaster
# Create some SpatRaster layers with non-matching NA cells library(terra) library(sdmtools) r <- c( example_raster(seed = 1), example_raster(seed = 2), example_raster(seed = 3) ) rvals <- terra::values(r) nas <- c(1:10, 105:120, 215:240) rvals[nas] <- NA r[] <- rvals # check if it pleases you to do so # plot(r) # mask out non-overlapping `NA` values in all layers s <- mask_all(r) s # plot(s)
# Create some SpatRaster layers with non-matching NA cells library(terra) library(sdmtools) r <- c( example_raster(seed = 1), example_raster(seed = 2), example_raster(seed = 3) ) rvals <- terra::values(r) nas <- c(1:10, 105:120, 215:240) rvals[nas] <- NA r[] <- rvals # check if it pleases you to do so # plot(r) # mask out non-overlapping `NA` values in all layers s <- mask_all(r) s # plot(s)
Creates a mask where a cell in any layer of r
that is NA
will be returned
as NA
.
mask_from_all(r)
mask_from_all(r)
r |
|
Similar in intention to mask_all
, but (a) will work on larger rasters
because it only holds the values of a single layer in memory at a time, and
(b) returns a mask layer, rather than masking each layer in r
.
Can be very slow
SpatRaster
with values NA
or 1.
r <- example_raster(seed = 10) s <- example_raster(seed = 11) r[10:20] <- NA s[5:15] <- NA q <- mask_from_all(c(r,s)) library("terra") plot(c(r,s,q))
r <- example_raster(seed = 10) s <- example_raster(seed = 11) r[10:20] <- NA s[5:15] <- NA q <- mask_from_all(c(r,s)) library("terra") plot(c(r,s,q))
Title
maskpointsdf(df, msk)
maskpointsdf(df, msk)
df |
data.frame |
msk |
mask |
tibble of two columsn, lon and lat
Crop, resample, and mask x
against ref
, and optionally
replace any missing values.
match_ref(x, ref, missing_val = NULL, filename = NULL, overwrite = TRUE)
match_ref(x, ref, missing_val = NULL, filename = NULL, overwrite = TRUE)
x |
|
ref |
|
missing_val |
If |
filename |
If not |
overwrite |
|
SpatRaster
of nlyrs(x)
trimmed to extent and resolution of ref
.
#placeholder example
#placeholder example
Adapted from seegSDM Identify closest neighbouring cell that does not return NA on raster mask
nearest_land(points, raster, max_distance)
nearest_land(points, raster, max_distance)
points |
anything |
raster |
raster |
max_distance |
the map units if raster is projected |
matrix of XY coordinates of nearest cell on mask, or NAs
long_tibble
constructor functionlong_tibble
constructor function
new_long_tibble(x)
new_long_tibble(x)
x |
A |
long_tibble
.
multispeciesPP
Make spatial predictions from multispeciesPP::predict.multispeciesPP
by passing in data as terra::SpatRaster
layers and returning a SpatRaster
.
predict_mpp_rast( model, data, sp, type = c("response", "link"), filename = NULL, overwrite = FALSE )
predict_mpp_rast( model, data, sp, type = c("response", "link"), filename = NULL, overwrite = FALSE )
model |
A |
data |
|
sp |
|
type |
|
filename |
|
overwrite |
|
SpatRaster
multispeciesPP
for all speciesCalls sdmtools::predict_mpp_rast
over all species in model
predict_mpp_rast_all( model, data, type = c("response", "link"), filename = NULL, overwrite = FALSE )
predict_mpp_rast_all( model, data, type = c("response", "link"), filename = NULL, overwrite = FALSE )
model |
A |
data |
|
type |
|
filename |
|
overwrite |
|
SpatRaster
Produces raster prediction from SDM based on model and covariate layers.
predict_sdm( model, covariates, type = NULL, layer_name = "predicted_distribution" )
predict_sdm( model, covariates, type = NULL, layer_name = "predicted_distribution" )
model |
A model object. |
covariates |
|
type |
Scale of prediction (response, model, etc.). |
layer_name |
Name for predicted layer. |
SpatRaster
prediction from model
## Not run: m <- glm(z ~ cov1, cov2, data = sdm_data) prediction <- predict_sdm(m, covs) ## End(Not run)
## Not run: m <- glm(z ~ cov1, cov2, data = sdm_data) prediction <- predict_sdm(m, covs) ## End(Not run)
long_tibble
Prints data tables stored in sdmtools
for their entire length*, but maintains other nice print features
of tbl_df
, i.e., tibbles.
## S3 method for class 'long_tibble' print(x, ...)
## S3 method for class 'long_tibble' print(x, ...)
x |
An object of class |
... |
extra arguments for printing |
*"entire length" — well really, up to 999 lines, which none currently are.
print(raster_to_terra)
print(raster_to_terra)
raster
to terra
equivalence tableA table of equivalent functions (or near equivalent) from the
raster
and terra
packages.
raster_to_terra
raster_to_terra
global_regions
A tibble with 42 rows and 3 columns:function name in raster
function name in terra
Annotations about differences in arguments or usage, etc.
Some argument names may differ.
Initially produced by Gerry Ryan and supplemented with "New method names" section in https://cran.r-project.org/web/packages/terra/terra.pdf, annotations added by IDEM members
Simple convenience function to plot points over a raster. Useful for quick data checks.
rastpointplot(r, v, pch = 16, cex = 0.5)
rastpointplot(r, v, pch = 16, cex = 0.5)
r |
|
v |
|
pch |
|
cex |
|
graphical plot
r <- example_raster() v <- example_vector() rastpointplot(r,v)
r <- example_raster() v <- example_vector() rastpointplot(r,v)
Single line wrapper to save plot as png
save_plot( p, filename, width = 2400, height, units = c("px", "cm", "mm"), res = 300 )
save_plot( p, filename, width = 2400, height, units = c("px", "cm", "mm"), res = 300 )
p |
A plot object |
filename |
|
width |
In |
height |
In |
units |
Units of |
res |
resolution, default 300px |
nothing. Writes a plot to filename
## Not run: lovely_plot <- plot(1:10) # why use three lines png("lovely_plot.png") lovely_plot dev.off() #when you could use one save_plot(p = lovely_plot, "lovely_plot.png") ## End(Not run)
## Not run: lovely_plot <- plot(1:10) # why use three lines png("lovely_plot.png") lovely_plot dev.off() #when you could use one save_plot(p = lovely_plot, "lovely_plot.png") ## End(Not run)
Convenience function for setting SpatRaster
layer names, enables setting in
piped workflows.
set_layer_names(x, layernames)
set_layer_names(x, layernames)
x |
|
layernames |
|
SpatRaster
example_raster() |> set_layer_names("Charlie Watts")
example_raster() |> set_layer_names("Charlie Watts")
Convenience function for setting SpatRaster
levels names to enable setting in
piped workflows.
set_levels(x, levs)
set_levels(x, levs)
x |
|
levs |
|
SpatRaster
## Not run: categorical_raster |> set_levels( levs = tribble( ~value, ~category, 30, "URBAN CENTRE", 23, "DENSE URBAN CLUSTER", 22, "SEMI-DENSE URBAN CLUSTER", 21, "SUBURBAN OR PERI-URBAN", 13, "RURAL CLUSTER", 12, "LOW DENSITY RURAL", 11, "VERY LOW DENSITY RURAL", 10, "WATER" ) ) %>% as.data.frame() ## End(Not run)
## Not run: categorical_raster |> set_levels( levs = tribble( ~value, ~category, 30, "URBAN CENTRE", 23, "DENSE URBAN CLUSTER", 22, "SEMI-DENSE URBAN CLUSTER", 21, "SUBURBAN OR PERI-URBAN", 13, "RURAL CLUSTER", 12, "LOW DENSITY RURAL", 11, "VERY LOW DENSITY RURAL", 10, "WATER" ) ) %>% as.data.frame() ## End(Not run)
Sources all scripts in a specified directory and optionally prints paths.
source_R(path = "R", print.names = TRUE)
source_R(path = "R", print.names = TRUE)
path |
Path of directory; default is |
print.names |
Print path and name of sourced scripts. Default |
Scripts are sourced to local environment. NULL
returned.
## Not run: source_R("/Users/frankenstein/project/R") ## End(Not run)
## Not run: source_R("/Users/frankenstein/project/R") ## End(Not run)
Split rasters
split_rast(x, grain = 4, write_temp = FALSE)
split_rast(x, grain = 4, write_temp = FALSE)
x |
A |
grain |
Grain of splitting. |
write_temp |
write to a tempfile. Default is FALSE |
Splits a SpatRaster
up into a grain^2
list of approximately equal
geographic sized rasters covering the extent of x
A list of SpatRaster
s of length grain^2
.
# Split a raster into four library(terra) r <- example_raster() s <- split_rast(r, grain = 2) s # plot with original ps <- lapply( s, FUN = extend, y = r ) |> rast() c(r, ps) |> plot()
# Split a raster into four library(terra) r <- example_raster() s <- split_rast(r, grain = 2) s # plot with original ps <- lapply( s, FUN = extend, y = r ) |> rast() c(r, ps) |> plot()
Defunct.
DO NOT USE THIS FUNCTION; use terra::scale
instead
standardise_rast(x)
standardise_rast(x)
x |
A |
A SpatRaster
objects with mean of zero and standard deviation of one.
## Not run: r <- example_raster() standardise_rast(r) ## End(Not run)
## Not run: r <- example_raster() standardise_rast(r) ## End(Not run)
Standardises all layers in a SpatRaster
to a scale of 0-1,
by dividing by the maximum value in each layer. Only operates by layer
std_rast(x, reverse, filename = NULL, overwrite = TRUE)
std_rast(x, reverse, filename = NULL, overwrite = TRUE)
x |
|
reverse |
|
filename |
Optional |
overwrite |
|
Will break for non-numeric rasters
A SpatRaster
with range 0-1
example_raster(seed = 3010) |> std_rast(reverse = TRUE)
example_raster(seed = 3010) |> std_rast(reverse = TRUE)
Returns a temporary file with a *.tif
extenstion
temptif()
temptif()
character
temptif()
temptif()
spatRaster
When a new terra::SpatRaster
is created it is stored in
memory. Writing it to disc and reading the object back from file requires two
steps: terra::writeRaster
then reading and re-assigning via terra::rast
.
writereadrast
wraps these into a single step.
writereadrast(x, filename, overwrite = TRUE, layernames = NULL)
writereadrast(x, filename, overwrite = TRUE, layernames = NULL)
x |
A |
filename |
A |
overwrite |
|
layernames |
|
A terra::SpatRaster
object reading from disc at filename
.
## Not run: # create raster then assign r <- sdmtools::example_raster() # usual workflow in two slow tedious boring steps terra::writeRaster(r, "LowerSpringvale.tif") s <- terra::rast("LowerSpringvale.tif") Better workflow in one fast enjoyable lithesome step with `sdmtools` r <- writereadrast(r, "tootgarook.tif") # or roll into single step with pipe q <- sdmtools::example_raster() |> writereadrast("frankstonfreeway.tif") ## End(Not run)
## Not run: # create raster then assign r <- sdmtools::example_raster() # usual workflow in two slow tedious boring steps terra::writeRaster(r, "LowerSpringvale.tif") s <- terra::rast("LowerSpringvale.tif") Better workflow in one fast enjoyable lithesome step with `sdmtools` r <- writereadrast(r, "tootgarook.tif") # or roll into single step with pipe q <- sdmtools::example_raster() |> writereadrast("frankstonfreeway.tif") ## End(Not run)