---
title: "Notebook 3: Suitability Envelopes for Tree Species Selection"
subtitle: "Combining tree occurrence data and climate layers to inform tree planting decisions"
format:
  html:
    toc: true
    toc-depth: 3
    number-sections: true
    code-fold: true
    code-tools: true
    embed-resources: true
    theme: cosmo
execute:
  echo: true
  warning: false
  message: false
  cache: true
editor:
  markdown:
    wrap: 72
---

*Once completed, feel free to share the results on the K4GGWA WhatsApp
Group or with the ICRAF-Team via email!*

## Overview

The objective of this notebook 3 is to give a simple, practical example
on how R can support in decision making derived from spatial- and
citizen science data. In this notebook we are using tree occurrence data
from GBIF (<https://www.gbif.org>) and BIOCLIM data as predictor
variables (<https://www.worldclim.org/data/bioclim.html>). The aim is to
demonstate how R can support practical decision making for tree planting
choices by building a simple **suitability envelope.** In this example
we use four common tree species relevant for restoration projects in
Senegal.

Note that all data that is used in this example can be pulled directly
in R without using other websites or manual downloads. Also note that
this is a VERY simplified version on how to map tree species suitability
and ecologically not good enough for informed decision making. Steps on
how to improve this notebook to make the suitability mapping
ecologically more accurate can be found below. However, this notebooks
objective is to give a first idea on how publicly available data can be
used to create simple workflows on tree species suitability which can
support decision making.

**Input:** GBIF tree occurrence data (& If available: LDSF/Regreening
App), BIOCLIM variables

**Outputs:** `species_envelope_table.csv` (can be used for QGIS
visualisations) & suitability maps per species

[**The concept of tree habitat suitability mapping**]{.underline}

Instead of relying on literature values for what a species can tolerate
(which is important but also very time consuming), we derive the
tolerance range **empirically**: we look at where the species has
actually been recorded (collected through citizen science apps such as
iNaturalist, Regreening App etc. -\> collected in GBIF), and read off
the range of climate conditions derived at those points. We will use
BIOCLIM variables (temperature, rainfall) only but note that other
predictor data (soil, tree cover, landuse) but also the STAC
(SpatioTemporal Asset Catalog), that has been introduced during
groupwork, can be useful here. The range of these variables becomes the
species' *suitability envelope*, which we then project back across the
whole country to see where else those conditions are met and the species
can potentially exist (SIMPLIFIED!). This can help for an informed
decision making on selecting the right tree species for certain areas.

[**How can it influence decision making**]{.underline}

In an operational setting, this workflow would sit alongside a
ground-truthing workflow: a decision maker can use the suitability map
to shortlist candidate species for a given site/area, then validate the
shortlist against local knowledge, soil sampling, and farmer/community
priorities (fodder, market value, native status) before committing to a
planting decision. So it is important to note that map narrows the
search space and supplements information but does not replace local
knowledge.

### Learning objectives

By the end of this notebook, you will be able to:

- download species occurrence records directly from GBIF using `rgbif`
  pull global climate (BIOCLIM) data via `geodata`

- extract environmental values at occurrence points with
  `terra::extract()`

- build an empirical suitability envelope table per species

- reclassify rasters into suitable/unsuitable masks and visualize them

- understand the possibilities and limitations such a method has

- being able to extend this workflow with more accurate refinements:

  - *combine occurrence records from multiple sources (GBIF + your own
    field data (Regreening App/LDSF)) into one clean table* which have a
    random sampling strategy

  - pull global data via a STAC catalogue

  - add more diverse predictor variables

### Species used in this notebook

| common tree species in Senegal | Usage |
|--------------------------|----------------------------------------------|
| *Faidherbia albida* | N-fixing parkland tree, reverse phenology, widely retained in croplands |
| *Senegalia senegal* (syn. *Acacia senegal*) | Gum arabic production, dryland restoration |
| *Eucalyptus camaldulensis* | Common fast-growing planted (non-native) species |
| *Tamarindus indica* | Provides dense shade, creates high-quality organic matter, and yields edible, nutrient-dense pods used in local cuisine and beverages |

Note that this is a subjective species selection. Any other species can
be used throughout the notebook.

## Setup

```{r}
#| label: setup
#| cache: false

# Packages used in this notebook
# install.packages(c("rgbif", "geodata", "rstac", "terra", "tidyterra",   "dplyr", "ggplot2", "here", "rnaturalearth"))

library(rgbif)
library(geodata)
library(rstac)
library(terra)
library(tidyterra)
library(dplyr)
library(ggplot2)
library(here)
library(rnaturalearth)

# Reuse the same project folder structure from Notebooks 1-2 (senegal_workshop_2026 -> notebooks, results, data)
```

------------------------------------------------------------------------

## Step 1: Define the species list

Note:

- You can swap with any other species of your interest by replacing or
  adding the species names.

- It is important to use the exact spelling as in GBIF (GBIF canonical
  name). If you are uncertain you can check the name within the GBIF
  database (<https://www.gbif.org>).

```{r}
#| label: species-list

species_list <- c(
  "Faidherbia albida",
  "Senegalia senegal",       #  synonym for Acacia senegal
  "Tamarindus indica",     
  "Eucalyptus camaldulensis")
```

------------------------------------------------------------------------

## Step 2: Download occurrence data from GBIF

We will be using the package `rgbif`, which lets us query GBIF directly
through R. We restrict to Senegal (`country = "SN"`), require
coordinates. The function `occ_data()` (r`gbif`) sends the actual
request to GBIF's servers.

```{r}
#| label: gbif-download
# building own  helper function to download and tidy one species at a time
# helps to not do the same thing for all 4 species (loop) --> species_name is the function's parameter which can be seen a placeholder that represents just one species at a time

get_gbif_occurrences <- function(species_name, country_code = "SN") {
  trees <- occ_data( 
    scientificName = species_name, # species_list
    country        = country_code, # SN
    hasCoordinate  = TRUE) # without coordnates the data is not useful for this prupose 
  
  if (is.null(trees$data) || nrow(trees$data) == 0) { # include if(is.null) in case one species has 0 records to return NULL -> loop would fail
    warning(paste("No GBIF records found", species_name))
    return(NULL)}

  trees$data %>%
    transmute( # transmute() is like mutate() but drops every column you don't explicitly list
      species = species_name,
      lon     = decimalLongitude,
      lat     = decimalLatitude,
      source  = "GBIF",
      coordinateUncertaintyInMeters
    ) %>%
    #Dropping rows missing coordinates and rows where the GPS uncertainty is known and larger than 100m 
    filter(
      !is.na(lon), !is.na(lat),
      is.na(coordinateUncertaintyInMeters) | coordinateUncertaintyInMeters <= 100
    ) %>%
    select(-coordinateUncertaintyInMeters)} # desecting this column again, was just a helper 


# new object with all the occurence points inside 
gbif_occurrences <- purrr::map_dfr(species_list, get_gbif_occurrences)
# map_dfr() calls get_gbif_occurrences() once per entry in species_list
# then combine all into one df 

# saving a csv with this data 
write.csv(
  gbif_occurrences,
  here("data", "occurrences", "gbif_occurrences_raw.csv"),
  row.names = FALSE)

head(gbif_occurrences)
```

Now, when inspecting the downloaded data it is important to check, how
many occurrences records are actually available per spp. (n?)?

- If one species has too few occurrences (such as Eucalyptus
  camadulensis in this case) this species should not be used during the
  following workflow since too few occurrences do not represent a
  representative set on where a species can occur alone.
- *Note that in this notebook we continue with all species to showcase
  in the end result that using too few species records does not result
  in a good and ecologically reliable output.*

[Note the **limitations** when using data from GBIF (additional
limitations below):]{.underline}

- A species with few records from GBIF does not say anything about their
  real spread.

- Records cluster along easily accessible areas (roads, towns, research
  stations, protected areas)

  - Citizen-science apps (iNaturalist, etc.) skew toward
    smartphone/internet access and urban or peri-urban users. Rural and
    remote communities or areas which are difficult to access are
    structurally underrepresented in the data.

- Planted vs. wild records aren't distinguished

- Taxonomic misidentification risk

In short: GBIF occurrence data tells you where the species *was found
and reported*, which is a mix of ecological suitability, human sampling
effort, and accessibility and not a direct measure of ecological
suitability alone. Therefore using data from a random sampling design
(such as LDSF) is much more defensible.

------------------------------------------------------------------------

## Step 3a: Add your own data: Regreening App/LDSF/ other field data

If available, you can load existing **LDSF** data or tree occurence data
collected through the **Regreening App** here and bring them into the
same three-column structure (`species`, `lon`, `lat`, `source`) so they
can be combined with the GBIF data.

This code chunk is just a demonstration how loading your own
(Regreening/ LDSF) data could look like.

```{r}
### LDSF ####
# Load data in R: Replace with the path to your own LDSF/field dataset
# ldsf_raw <- read.csv("your path")

# Adjust column names below to match your actual file
# ldsf_occurrences <- ldsf_raw %>% transmute(
#    species = species_clean,     
 #   lon     = longitude,         
  #  lat     = latitude,          
   # source  = "LDSF"
#  ) %>%
 # filter(species %in% species_list) # this filters only the species you have selected above!

# glimpse(ldsf_occurrences)
```

```{r}
### Regreening App Data ### 
# download data from DRS as shown during the workshop 

# Load data in R: Replace with the path to your own Regreening dataset
# regreening_raw <- read.csv("your path")

# Adjust column names below to match your actual file
# regreenbing_occurrences <- regreening_raw %>% transmute(
#    species = species_clean,     
#   lon     = longitude,         
#  lat     = latitude,          
# source  = "LDSF"
#  ) %>%
# filter(species %in% species_list) # this filters only the species you have selected above!

# glimpse(regreening_occurrences)
```

------------------------------------------------------------------------

## Step 3b: Combine all occurrence sources

If you have several data sources, you can upload them as well in a csv
format. Make sure the columns are named and spelled exactly the same way
(the csv columns - you could also rename them in R using the function
"mutate"). Then combine all 4 species occurrences of all sources into
one object and merge the rows.

```{r}
# #| label: combine-occurrences
# 
# all_occurrences <- bind_rows(gbif_occurrences, ldsf_occurrences, regreening_occurences) %>%
#   filter(!is.na(lon), !is.na(lat))
# 
# write.csv(
#   all_occurrences,
#   here("data", "occurrences", "all_occurrences_combined.csv"),
#   row.names = FALSE
# )
# 
# all_occurrences %>%
#   count(species, source)
```

Note that if these steps are executed, the object names in the following
chunks have to be adapted.

------------------------------------------------------------------------

## Step 4: Map occurrence points

A quick visual check before moving to extraction - do the points fall
inside Senegal only? Also, it is important to see the number of
occurrence points for each species since this influences a lot how to
continue working with the data, which species has to be dropped and
which to be interpreted more carefully:

```{r}
senegal_outline <- ne_countries(scale = "medium", country = "Senegal", returnclass = "sf")

# Add occurrence counts to each species label
occ_with_counts <- gbif_occurrences %>%   # or all_occurrences
  add_count(species, name = "n_occ") %>%
  mutate(species_label = paste0(species, " (n=", n_occ, ")"))

ggplot() +
  geom_sf(data = senegal_outline, fill = "grey95", color = "grey40") +
  geom_point(
    data = occ_with_counts,
    aes(x = lon, y = lat, color = species_label),
    alpha = 0.7, size = 1.5
  ) +
  coord_sf(xlim = c(-17.6, -11.3), ylim = c(12.2, 16.7)) +
  labs(title = "GBIF Occurrence records by species", color = "Species") +
  theme_minimal()
```

As you can see here, Eucalyptus camaldulensis has only 2 recorded
occurrences within Senegal. Therefore this species should not be used
for suitability predictions since input data is too scarce. In this case
we will keep it only to visualize in the end that the output is
ecologically not realistic.

------------------------------------------------------------------------

## Step 5: Environmental layers

Now that we have occurrence points for our 4 species, we need
environmental data to describe the conditions at each of those points.
This is the raw material the suitability envelope is built from. In this
notebook we only use BIOCLIM but other variables can be used (see
options below).

### 5a. Bioclim variables via `geodata`

`geodata` downloads WorldClim bioclim layers directly into R. The
resolution of BIOCLIM is 1km.

- Note on the sub-selection of the 19 original bioclim variables:
  - WorldClim provides 19 "bioclim" variables in total, each capturing a
    different aspect of temperature or rainfall (annual means,
    seasonality, extremes of the wettest/driest/warmest/coldest periods,
    etc.). Using all 19 at once creates a problem for our simple
    threshold method: many of these variables are strongly correlated
    with each other (e.g. BIO1, BIO5, BIO6, BIO10, BIO11 are all
    different flavors of "temperature"), so stacking all 19 as
    independent hard constraints multiplies out far too many exclusions.
  - BIO1 (annual mean temperature) and BIO12 (annual precipitation) as
    the two most fundamental climate axes, plus BIO4 (temperature
    seasonality) and BIO15 (precipitation seasonality) to capture
    variability were chosen.

Source: Hijmans, R.J., S.E. Cameron, J.L. Parra, P.G. Jones and A.
Jarvis, 2005. Very High Resolution Interpolated Climate Surfaces for
Global Land Areas. International Journal of Climatology 25: 1965-1978.
doi:10.1002/joc.1276.

```{r}
#| label: bioclim-download
#library(geodata)

bioclim_all <- worldclim_country(
  country = "Senegal",
  var     = "bio",
  res     = 0.5,
  path    = here("data", "environment"))

# Keeping a small, interpretable subset:
# BIO1  = annual mean temperature
# BIO12 = annual precipitation
# BIO4  = temperature seasonality
# BIO15 = precipitation seasonality

bioclim_subset <- bioclim_all[[c("wc2.1_30s_bio_1", "wc2.1_30s_bio_12",  "wc2.1_30s_bio_4", "wc2.1_30s_bio_15")]]

names(bioclim_subset) <- c("bio1_temp_mean", "bio12_precip_annual", "bio4_temp_season", "bio15_precip_season")
```

**A note on more advanced alternatives and BIOCLIM limitations:**

Rather than manually picking a small subset, you could reduce all 19
variables into a smaller number of *statistically independent* axes
using **PCA (Principal Component Analysis)** (finds the main directions
of variation across the correlated variables and combines them) or
**ENFA (Ecological Niche Factor Analysis)**, which designed specifically
for ecological data. Both are more statistically rigorous, but they come
at a cost for a workshop setting: once you're working in "PC1/PC2"
space, the result is no longer directly interpretable as "this site
needs X mm of rain" and a decision-maker can no longer read the output
without translating it back. Given this notebook's goal is a
*transparent, explainable* first step for practitioners, we manually
chose ecologically meaningful variables for simplification purposes.
Whether this is worthwhile depends on how much occurrence data you have
per species since PCA/ENFA on very few points (like our Eucalyptus
example) won't improve results.

Bioclim variables are often used since they are free, globally
consistent, easy to access directly in R and capture the broad climatic
drivers that matter most for a first-pass suitability assessment for the
species. However they have a couple of limitations which should be
considered such as a broad resolution of 1km, which can be enough for
large scale assessments but for small scale pülanting decisions a
smaller resolution is needed since it masks local variation in soil,
vegetation cover or microclimate. The variables themselves are long-term
averages (not real-time conditions) and are interpolated from a sparse
network of weather stations. Averaging also smooths out the extreme
events that often determine survival more than the long-term mean does.
And since bioclim captures climate only, it says nothing about soil,
land use, grazing pressure, or other non-climatic/socio-economic factors
that can just as easily determine whether a tree actually establishes at
a site. Also it does not reflect how climate may shift over a 10–20 year
restoration horizon.

### 5b. Additional data via STAC

As mentioned above, trees do not only grow depending on climate and
rainfall conditions but also depend on soil conditions (organic carbon,
pH, texture) and many other factors. It is important to take as many of
them into account as possible. One example can be to add a different
layers using **STAC (SpatioTemporal Asset Catalog)**, which is a
standardized way to search and access cloud-hosted geospatial datasets
by location and date (as briefly introduced during the workshop),
without downloading anything manually. It works conceptually like the
`geodata` call above, but for a different data catalog and a different
variable type.

```{r}
# STAC   

# xxx_stac (SpatRaster), e.g. layers "soc", "phh2o"
# xxx_stac <- rast(...)

```

The end result should be a `terra` `SpatRaster` stack called `xxx_stac`,
cropped to Senegal, with layers such as soil organic carbon (SOC) and pH
from the stack.

### 5c. Additional predictor variables

If time and data availability allow, this is the place to bring in
further predictors — tree cover, land use, distance to roads/rivers, or
other accessible predictor variables derived from satellite imagery.
Often these have to be downloaded separately (via Google Earth Engine).
Otherwise, this whole section can simply be skipped.

```{r}
# rwemember to Align resolution/extent before stacking

# stacking all variables togetehr 
# env_stack <- c(bioclim_subset, soil_stac)
```

Two important technical steps before combining any layers, regardless of
source:

- **Resolution and extent alignment:** Different data sources have
  different resolutions. `resample()` forces one raster onto the same
  grid as another, which is required before you can combine (stack)
  them.

- **Stacking:** Once aligned, `c()` combines multiple `SpatRaster`
  objects into one multi-layer object, so every layer can be extracted
  together at each occurrence point in one call, and reclassified
  together into the final suitability mask.

------------------------------------------------------------------------

## Step 6: Extract environmental values at occurrence points

Extracting the predictor variables at each species occurrence point.
Remember to change the object names of the occurrences and the predictor
variables if needed.

```{r}
#| label: extract-values
occ_vect <- vect(gbif_occurrences, geom = c("lon", "lat"), crs = "EPSG:4326")
# all_occurances if you add other data sources 

env_values <- terra::extract(bioclim_subset, occ_vect, ID = FALSE) # or env_stac
 
occurrence_env <- bind_cols(gbif_occurrences, env_values)
# all_occurances if you add other data sources 

head(occurrence_env)
```

------------------------------------------------------------------------

## Step 7: Build the empirical suitability envelope

For each species and each variable, take the 5th-95th percentile range
across all its occurrence points, rather than the raw min/max (which is
sensitive to outliers or GPS errors). This will then be considered as
the species suitable habitat envelope. A pixel which falls inside this
envelope will later be considered as suitable and any other pixel as
unsuitable.

```{r}
#| label: envelope-table
#| eval: false
# checking which names were used 
names(env_values)

# envelope 
envelope_table <- occurrence_env %>%
  group_by(species) %>%
  summarise(
    across(
      c(bio1_temp_mean, bio12_precip_annual, bio4_temp_season, bio15_precip_season),
      list(p05 = ~ quantile(.x, 0.10, na.rm = TRUE),
           p95 = ~ quantile(.x, 0.90, na.rm = TRUE)),
      .names = "{.col}_{.fn}"),
    n_records = n())

write.csv(
  envelope_table,
  here("results", "species_envelope_table_gbif_bioclim.csv"),
  row.names = FALSE)

envelope_table
# for each bioclim value its split into 5th and 95th percentile = envelope. 
```

How to interprete: Each pair (\_p05, \_p95) is one variable's range (5th
and 95th percentile).

## Step 8: Reclassify rasters into suitability masks

For each species, we will now mark a pixel as suitable (1) only if it
falls within *every* variable's envelope range and unsuitable (0)
otherwise.

**Note:** the threshold method here is intentionally simple. A more
sophisticated alternative would generate (pseudo-)absence points and use
them to train a Random Forest (RF) or other machine learning models,
which learns not just where the species *was* found, but what actually
distinguishes those points from where it wasn't. This can improve
precision over a simple threshold. However, doing this with
citizen-science data (like GBIF) is risky since occurrence records are
sampling-biased (see limitations), a randomly placed "absence" point can
easily land in a spot that's actually ecologically just as suitable as a
presence point but was just not recorded. Training a model on such
inaccurate absence data teaches the wrong pattern. With data coming from
a randomized sampling design (such as LDSF), absence points can be
generetad by using the plots where the species was not found which then
makes more complex ML approaches possible. This very much improves
prediction accuracy and ecologically soundness.

```{r}
#| label: suitability-masks
 
build_suitability_mask <- function(species_row, stack) {
  bio1_ok  <- stack$bio1_temp_mean      >= species_row$bio1_temp_mean_p05      & stack$bio1_temp_mean      <= species_row$bio1_temp_mean_p95
  bio4_ok  <- stack$bio4_temp_season    >= species_row$bio4_temp_season_p05    & stack$bio4_temp_season    <= species_row$bio4_temp_season_p95
  bio12_ok <- stack$bio12_precip_annual >= species_row$bio12_precip_annual_p05 & stack$bio12_precip_annual <= species_row$bio12_precip_annual_p95
  bio15_ok <- stack$bio15_precip_season >= species_row$bio15_precip_season_p05 & stack$bio15_precip_season <= species_row$bio15_precip_season_p95

  bio1_ok * bio4_ok * bio12_ok * bio15_ok}

suitability_maps <- envelope_table %>%
  group_split(species) %>%
  purrr::map(~ build_suitability_mask(.x, bioclim_subset)) %>%
  purrr::set_names(envelope_table$species)
```

------------------------------------------------------------------------

## Step 9: Visualize suitability maps

### 9a. Per-species suitability

```{r}
#| label: plot-suitability-species

# for putting several ggplot into one graphical output 
library(patchwork)

suitability_stack <- rast(suitability_maps)
names(suitability_stack) <- names(suitability_maps)

sen_bbox <- sf::st_bbox(senegal_outline)

# Numeric version — masked, used for all arithmetic
suitability_masked_num <- terra::mask(suitability_stack, terra::vect(senegal_outline))

species_colors <- c(
  "Eucalyptus camaldulensis" = "#1b9e77",
  "Faidherbia albida"        = "#d95f02",
  "Senegalia senegal"        = "#7570b3",
  "Tamarindus indica"        = "#e7298a"
)

plots <- purrr::map(names(suitability_masked_num), function(nm) {

  r <- suitability_masked_num[[nm]]

  # factor conversion done per single layer -- i always encountered a multi-layer levels() bug so this solves it
  r_fct <- as.factor(r)
  levels(r_fct) <- list(data.frame(id = c(0, 1), suitability = c("Unsuitable", "Suitable")))

  ggplot() +
    geom_spatraster(data = r_fct, aes(fill = suitability)) +
    geom_sf(data = senegal_outline, fill = NA, color = "black", linewidth = 0.3) +
    scale_fill_manual(
      values = c("Unsuitable" = "grey90", "Suitable" = species_colors[[nm]]),
      na.value = "transparent", name = NULL
    ) +
    coord_sf(xlim = sen_bbox[c("xmin","xmax")], ylim = sen_bbox[c("ymin","ymax")], expand = FALSE) +
    labs(title = nm) +
    theme_minimal() +
    theme(legend.position = "none", plot.title = element_text(size = 10, face = "bold"))
})

wrap_plots(plots, ncol = 2)

```

### 9b. Number of suitable species per pixel

Pixel count (% suitable area in Senegal per species):

```{r}
#| label: pixel-counts

purrr::map_dbl(suitability_maps, ~ terra::global(.x, "sum", na.rm = TRUE)[[1]] / terra::ncell(.x) * 100)
```

### 9c: Combined suitability per area

```{r}
suitability_stack <- rast(suitability_maps)
names(suitability_stack) <- names(suitability_maps)

sen_bbox <- sf::st_bbox(senegal_outline)

#numeric
suitability_masked_num <- terra::mask(suitability_stack, terra::vect(senegal_outline))
#factor
suitability_masked_fct <- terra::mask(suitability_stack, terra::vect(senegal_outline))

# Build one category table PER LAYER (4 identical copies, one per species)
cat_table <- data.frame(id = c(0, 1), suitability = c("Unsuitable", "Suitable"))
levels(suitability_masked) <- rep(list(cat_table), terra::nlyr(suitability_masked))

ggplot() +
  geom_spatraster(data = species_count) +
  geom_sf(data = senegal_outline, fill = NA, color = "black", linewidth = 0.4) +
  scale_fill_gradientn(colors = c("grey95", "#c7e9c0", "#74c476", "#238b45", "#00441b"),
                        breaks = 0:4, na.value = "transparent", name = "N suitable\nspecies") +
  coord_sf(xlim = sen_bbox[c("xmin","xmax")], ylim = sen_bbox[c("ymin","ymax")], expand = FALSE) +
  labs(title = "Number of ecologically suitable species per pixel") +
  theme_minimal()

```

## Step 10: Interpretation and discussion

As noted in the overview, this map is a starting shortlist. The next
step would be validating candidate species on the ground and weighing
them against community priorities (fodder, market value, native status)
before committing.

[**Critical reflections & limitations:**]{.underline}

- does the map generally make sense on the broad scale?

- How many points per species were available? Does the Eucalyptus result
  seem realistic? If not, why?

- Large unsuitable areas: Really unsuitable or just very little data in
  these areas?

- Remember: this was a VERY broad suitability mapping -\> ecologically
  not really supported but to get an idea what a simple analysis can do!

- Many more predictor variables needed (here only 2 climatic -\> but
  non-climatic and socio-economic infleunce important in species spread)

- The 5th–95th percentile threshold itself is arbitrary. Why not
  10th–90th, or raw min/max?

  - Different cut-offs would shrink or grow every species' suitable area
    — what does the "right" threshold even mean (...).

- GBIF records often cluster near roads, towns, and accessible areas
  which are not necessarily where the species is most suited, but where
  people (and citizen-science app users specifically) go.

  - Better to use a well designed sampling design such as LDSF-data.

- All variables treated as equally important and independent -\> but
  maybe some are more important than others... There are methods to
  check the most important ones only (ENFA; PCA). - No validation data
  to check how well this actually performed.

- Resolution with 1km is very broad for small scale analysis (county
  level) but good enough for a cuntry level.

- No pseudo-absence/background comparison: this method only looks at
  where the species *was* found, but never checks whether the same
  conditions occur widely elsewhere *without* the species present.

[**Next steps - possible improvements to do:**]{.underline}

- **Option 1:** Add other predictor variables (Soil layer) download from
  soilgrids africa and store in your data folder import soil dataset

- **Option 2:** Add STAC rasters as predictors or to overlay and check
  for e.g. LULC, TreeCover, SOC Can you identify any interesting
  patterns?

- **Option 3:** use different species with more occurrance records in
  gbif

[**Critical questions:**]{.underline}

1\. Which species has the widest / narrowest empirical envelope? Does
that match how widespread or specialized it is known to be?

2\. Where does the empirical envelope (from occurrence data) disagree
with literature-based tolerance ranges (e.g. from the Agroforestree
Database)? What might explain a gap -- limited occurrence records,
sampling bias, or the species' full range extending beyond Senegal?

3.  If two species show overlapping suitable zones, how would you decide
    between them for a given site? What information would you need
    beyond this map?

[**Further literature to dive deeper into the topic**]{.underline}

- <https://www.annualreviews.org/content/journals/10.1146/annurev.ecolsys.110308.120159>

- <https://jcoliver.github.io/learn-r/011-species-distribution-models.html>

- <https://www.sciencedirect.com/science/article/pii/S1470160X22009165>

- <https://besjournals.onlinelibrary.wiley.com/doi/10.1111/2041-210X.14466>

- <https://github.com/datatas/Accessing_Mapping_GBIFdata>
