---
title: "Combining Regreening App polygon data with land health data"
subtitle: "Explore environmental conditions and landscape change across restoration areas"
format:
  typst:
    toc: true
    toc-depth: 2
    code-fold: false
execute:
  warning: false
  message: false
---

# About this notebook

In the previous practical, you worked with **Regreening App** monitoring data to download project data from the **Data Reporting System (DRS),** explore restoration georeferenced data, and turn recorded WKT geometries into polygons.

In this practical we build on those skills, by combining restoration polygons with raster data accessed through the GGW STAC catalogue. This lets us explore data by relating the type of restoration activity that took place and how that interacts with environmental and climate variables, including over time.

This practical covers:

1.  preparing your Regreening App polygons for spatial analysis
2.  connecting to STAC catalogue and finding the relevant raster dataset
3.  extracting raster values within your restoration polygons
4.  comparing environmental conditions across different restoration activity types
5.  combining several spatial indicators
6.  how to extend these analyses to change-analysis with different raster time intervals
7.  how to use analysis and findings to inform ongoing management decisions

::: callout-note
This notebook assumes you have completed the previous Regreening App practical, [**Downloading and working with Regreening App data**](https://k4ggwa.thegrit.earth/content/state_of_land/tutorials/_downloads/N1_Intro_RA_data.qmd), or are comfortable importing a CSV and creating an `sf` object from the geometry field.
:::

::: callout-note
If you are not yet familiar with different types of spatial data formats, or you want to brush up on your knowledge, it is a good idea to explore [**Module 3.1 - Finding and accessing spatial evidence**](https://k4ggwa.thegrit.earth/content/state_of_land/tutorials/m3-1-accessdata.html) on the K4GGWA Platform Evidence Hub.
:::

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

## Connecting field-collected restoration data to landscape evidence

The Regreening App tells us about restoration activities carried out on the ground, like what kind of restoration activity is taking place, the species in question, the types of management practised and other qualitative, ancillary data.

This data is useful for organising projects, reporting and monitoring, and informing ongoing adaptive management decisions. When we combine project level data with landscape-level environmental and climate data, our decision-making levels-up!

We can start to ask and answer questions like:

-   What is the soil organic carbon in my restoration intervention areas at baseline? Endline?
-   How severe is erosion?
-   What is the existing tree or vegetation cover?
-   Are my restoration sites located in areas with particular climate trends?
-   How is vegetation changing over time?

This notebook guides learners on how to combine project georeferenced data with various kinds of raster datasets to do just that!

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

## 1. Download your project data

Open the [Regreening App Data Reporting System (DRS)](https://radrs.icraf.org/permission/dashboard).

::: callout-note
If you are not yet familiar with the DRS Platform, [see this tutorial video explaining how to navigate and access your project.](https://www.youtube.com/watch?v=q6_24YmqGrU)
:::

As a **Project Manager (PM)**:

1.  Open the DRS and project manager dashboard
2.  Select the project you want to analyse
3.  Download the project data as a csv file
4.  Save the csv somewhere easy to find (a project folder)

The exported file contains all the information recorded in the app about the restoration plot, including trees species, management practices, uses, location and polygon geometries. The kinds of data available depend on the app module that was used (Tree Planting; FMNR; Nursery; Rangeland).

::: callout-warning
Remember, best practice is to **set up a project folder** where you store your `.qmd` notebook, data, and outputs. That way, you can easily find all of our project documents and data in one place, and we can set our R session working directory to this folder (**Session \> Set Working Directory \> Choose Directory**). See the example below.
:::

``` text
my_restoration_project/ 
│ 
├── data/ 
├── outputs/ 
```

**Note:** If you have not yet created a project on the DRS, but you want to explore this notebook with an example dataset, you can [download an example dataset here](https://drive.google.com/drive/folders/1zagSkg53XSGFttooknQrQJt5ahSTj7hW?usp=sharing). The example dataset is called `ra_plots_example.csv`. Save this file in your data folder that you created above.

#### Note on the example dataset

The example dataset is from a real FMNR restoration project in northern Ethiopia that has been anonymised. The names of the data collectors and farmers have been removed, and the georeferenced plots have had their geometry modified for privacy. Therefore, the polygons appear as hexagons (H3 grid), not the original geometry - your dataset will however show the real geometry of your plots/polygons.

The code in this notebook generally uses variable names that refer to data captured using the FMNR module. Change these according to your own data.

## 2. Set up R

We will use six main packages for this practical.

```{r}
#| eval: FALSE
# If you have not yet installed some of these, run install.packages() first
library(tidyverse)
library(sf)
library(terra)
library(rstac)
library(leaflet)
library(janitor)
```

-   `sf` handles vector spatial data such as polygons.
-   `terra` handles raster data and spatial operations.
-   `rstac` lets us search STAC catalogues from R.
-   `tidyverse` is used for data manipulation and visualisation.
-   `leaflet` lets us create interactive maps.
-   `janitor` helps us quickly clean our data names.

## 3. Load your Regreening App data

Use the CSV downloaded from the Regreening App DRS and load it into the R environment.

Replace `"ra_plots_example.csv"` with the name of your downloaded project csv file, if using your own file.

Replace `"project_name"` with the name of your project.

```{r}
project_name <- read.csv("data/ra_plots_example.csv")

glimpse(project_name)
```

```{r}
project_name <- project_name |>
clean_names() # clean_names() is a function from the janitor package. We can use the it to easily clean/standardize our column names. In this case, it will replace white space between variable names with underscore and standardise capitalisation. "Plot Name" becomes "plot_name".
```

```{r}
# Let's filter out missing geometries
project_name <- project_name |>
  filter(!is.na(plot_geometry))
```

Convert the WKT geometry to an `sf` object:

```{r}
# Using the st_as_sf function from the sf package, we transform our wkt coordinates in the "plot_geometry" column into spatial features, that R can recognise and map

plots_sf <- st_as_sf(project_name, wkt = "plot_geometry", crs = 4326)

plots_sf
```

Check the coordinate reference system and geometry:

```{r}
st_crs(plots_sf)

sum(!st_is_valid(plots_sf))
```

For this practical, the important thing is that your restoration polygons have a valid spatial location. You can quickly check them on a map:

```{r}
plots_sf |>
leaflet() |>
  addProviderTiles("OpenStreetMap.Mapnik") |>
  setView(
    lng = 39.2,
    lat = 13.6,
    zoom = 10) |>
  addPolygons(
    weight = 2,
    fillOpacity = 0.3
  )
```

## 4. What is a STAC?

A STAC, or *SpatioTemporal Asset Catalogue*, is a standard way of organising and describing spatial datasets. It is typically structured like this:

``` text
Catalogue
   │
   ├── Collection
   │      │
   │      ├── Item
   │      │     ├── Asset
   │      │     └── metadata
   │      │
   │      └── Item
   │
   └── Collection
```

Generally speaking:

-   a **collection** groups related datasets;
-   an **item** represents a particular dataset or observation;
-   an **asset** is the actual data file (in this case, a raster);
-   metadata tells us what the data represent, and other useful specs for correctly handling it.

One of the main advantages of accessing spatial data this way, is that we do not need to manually download a large raster file. Instead files are typically stored in cloud-native formats, such that we can tell R (through the `rstac` package) to find and retrieve the raster image tiles for our exact area of interest, making our analysis more efficient and quick.

The main thing to know about STAC is that it is essentially an indexing system for spatial data catalogues through which many different spatial data providers are making their products easily discoverable.

**In this notebook we will use the GGW STAC (published by the SPACIAL Lab at Landscape Alliance)**. [You can learn more about the methods behind our data products here.](https://k4ggwa.thegrit.earth/content/ecosystem/ecosystem.html)

There are many dozens of STAC catalogues available from many different data providers. It should be noted that data access through a STAC API is just one modality of accessing spatial data. You can use any kind of raster files in this analysis, regardless of how it was accessed.

::: callout-note
Read more about STACs and other ways of accessing spatial data in [Module 3.1 of the K4GGWA Platform Evidence Hub](https://k4ggwa.thegrit.earth/content/state_of_land/tutorials/m3-1-accessdata.html).
:::

## 5. Connect to the GGW STAC

The GGW STAC catalogue is available using the following STAC URL name:

```{r}
stac_source <- stac("https://stacapi100.thegrit.earth/")

stac_source
```

We can use `rstac` functions `collections()` and `get_request()` to check what collections are available:

```{r}
collections <- stac_source |>
  collections() |>
  get_request()

collections
```

## 6. Find a raster for your restoration area

We can use the extent of our restoration polygons as the area of interest. To do this, we use a function called `st_bbox()` from the `sf` package to delimit the bounding box of our Regreening App polygon data.

```{r}
project_bbox <- st_bbox(plots_sf)

bbox <- c(
  project_bbox["xmin"],
  project_bbox["ymin"],
  project_bbox["xmax"],
  project_bbox["ymax"]
)

bbox
```

Now search for a dataset. In this notebook, we will use a couple of predictive rasters from this catalogue - *soil organic carbon (SOC)* and *tree cover.* You don't need to use these datasets specifically, you can browse and choose any datasets according to your needs.

```{r}
# Using STAC query functions - stac_search() and get_request() - we are telling R to find all files within the specified collection that have coverage in our region of interest (our bounding box). Try changing the number in 'limit' to see more or less files. 

items <- stac_search(
  q = stac_source,
  collections = "ggw", # Try changing the collection name to explore other available data
  bbox = bbox,
  limit = 20
) |>
  get_request()

items
```

The search returns STAC **items** that match our request. We can ask R to print the asset titles, for a more intuitive inspection of the data:

```{r}
for (i in items$features) {
  print(i$assets$layer$title)
}
```

We can also inspect what assets are contained inside an individual item:

```{r}
names(items$features[[1]]$assets)
```

You may see one or more asset names. An asset contains a link to the actual data file:

```{r}
items$features[[1]]$assets
```

The exact asset names available depend on the collection. In a different STAC catalogue or collection, you may see different names and different datasets.

# 7. Access the raster as a Cloud Optimised GeoTIFF

For a COG, we can give `terra` the remote URL rather than downloading the entire raster first.

For the soil organic carbon example:

```{r}
soc_url <- "https://stacapi100.thegrit.earth/eodata/cogeo/ggw/Soil_Organic_Carbon_2023_GGW_500m.tif"
```

Open it and run a quick check:

```{r}
soc <- rast(paste0("/vsicurl/", soc_url))

soc
```

We can inspect some basic information:

```{r}
list(
  crs = crs(soc),
  resolution = res(soc),
  extent = ext(soc),
  layers = nlyr(soc)
)
```

::: callout-warning
**It is good practice to always check a dataset's metadata** including the variable and units, spatial resolution, spatial extent, number of bands and date before we start using it. That way we know exactly what kind of data we're working with.
:::

# 8. Check that the raster covers your restoration sites

It is good practice to check that your raster and polygons actually overlap.

First convert the polygons to a `terra` spatial vector:

```{r}
plots_vect <- vect(plots_sf)
```

Project the polygons to the raster's CRS:

```{r}
plots_vect <- project(plots_vect,soc)
```

Check the coordinate reference systems:

```{r}
crs(plots_vect)

crs(soc)
```

Now compare the extents:

```{r}
ext(plots_vect)

ext(soc)
```

Your restoration polygons should fall within the area covered by the raster.

# 9. Extract raster values inside each restoration polygon

This is the key step in this practical - computing the values of environmental variables in your area of interest or intervention zones.

We can use `extract()` to summarise raster values within each polygon. For example, to calculate the mean soil organic carbon:

```{r}
soc_stats <- extract(soc, plots_vect, fun = mean, na.rm = TRUE)

head(soc_stats, 30)
```

The result should contain one value for each polygon. Because Regreening App polygons are generally small intervention areas, often less than one hectare, we should bare in mind that when combining with a raster of 500m resolution, several plots may fall inside the same raster pixel. This means, several plots may have the same value, when extracting raster values.

We can attach it back to our `sf` dataset:

```{r}
# First, we tell R to create a new column 'SOC_mean' in our plots_sf dataset, using the soc_stats values we just calculated, and assign it to a new variable called 'plots_with_soc'.

plots_soc <- plots_sf |>
  mutate(
    soc_mean = soc_stats[, 2] #*0.01
  )

# Next, we want to do a quick check that the plot names and SOC values line up
plots_soc |>
  st_drop_geometry() |>
  select(
    plot_name,
    soc_mean
  ) |>
  head()
```

Check the values in the SOC column. Are they sensible? Often, when working with raster data, a scale-factor must be applied to the values stored. If our values seem too high, or we otherwise suspect they have been transformed for data-storage, we should check the metadata again.

In this case, using our example dataset, SOC values appear much too high. We can therefore apply a scale-factor of 0.01. **Uncomment the scale-factor next to the soc_mean line in the code cell above to do this.**

You have now created a new dataset that combines georeferenced data from the field, with land health raster datasets! This is a very simple example, but we can build on our analyses from here with more raster layers and more complex analysis methods.

# 10. Distribution of SOC across our restoration site

Now that we have a spatial dataset with our mean SOC values, we can plot a quick histogram to check the distribution of SOC values across our restoration site:

```{r}
plots_soc |>
  st_drop_geometry() |>
  ggplot(aes(x = soc_mean)) +
  geom_histogram(bins = 20) +
  labs(
    title = "2023 Average SOC Across Restoration Site ",
    x = "Mean soil organic carbon (g C/kg)",
    y = "Number of restoration plots"
  )
```

We may also want to quickly map (using `leaflet`!) this out to easily visualise SOC across our landscape.

```{r}
# First let's crop the full raster to the extent of our polygons, with a bit of extra buffer
soc_crop <- crop(soc, extend(ext(plots_vect), 0.2))

# If you didn't scale the soc raster before, you can do that here by uncommenting the line below
# soc_crop <- soc_crop * 0.01 

# Create the colour ramp
soc_range <- range(global(soc_crop, c("min", "max"), na.rm = TRUE),na.rm = TRUE)

soc_pal <- colorNumeric(
  palette = hcl.colors(100, "YlOrBr"),
  domain = soc_range,
  na.color = "transparent"
)

# Create the map
leaflet() |>
  addProviderTiles(providers$Esri.WorldImagery) |>
  addRasterImage(
    soc_crop,
    colors = soc_pal,
    opacity = 0.95
  ) |>
  addPolygons(
    data = plots_sf,
    fill = FALSE,
    color = "#222222",
    weight = 1,
  ) |>
  addLegend(
    position = "bottomright",
    pal = soc_pal,
    values = soc_range,
    title = "SOC (g C/kg)"
  ) |>
  setView(lng = 39.2, lat = 13.6, zoom = 10)
```

### Reflections

> Are our restoration activities taking place under relatively similar environmental conditions, or across a diverse range of conditions?

This is an important MEL question. A small number of monitoring sites may not represent the full range of landscapes where restoration is being implemented. By aggregating up all of our intervention areas, and calculating the mean value of a variable of interest, we can establish the landscape-scale conditions of our site, our project baseline, and track this variable over time - hoping it changes, due to our interventions.

# 11. Comparing whether different management practices affect environmental variables

The Regreening App contains information about how restoration is being implemented.

For example, we might want to compare plots **with and without crops**.

```{r}
plots_soc |>
  st_drop_geometry() |>
  ggplot(aes(x = plot_has_crops, y = soc_mean)) +
  geom_boxplot() +
  labs(
    title = "SOC, crops vs. no crops",
    x = "Plot has crops",
    y = "Mean soil organic carbon"
  )
```

### Reflections

> Do environmental variables like SOC (or erosion, tree-cover, etc) vary under different management practices? What does that inform us about how we might adapt our interventions?

This exercise helps us interpret our program intervention results and perform a more robust evaluation design. In some cases, with more advanced statistical analysis, we may be able to establish causal inference and impact pathways.

This gives us strong evidence that our restoration activities are working, exactly how they are working and perhaps interacting with confounding variables, and a solid basis for demonstrating impact, attracting additional finances, and scaling out activities.

You can try the same analysis with another restoraion variable such as:

-   no fencing vs fencing;
-   management practice;
-   restoration method;
-   region.

# 12. Combining two land health variables: soil organic carbon and forest cover

Certain land health variables, like SOC, can be strong proxies for things like soil fertility, soil structural properties and infiltration, and vegetation cover - all ecosystem functions we are trying to recover and enhance through our interventions.

Others, like tree cover or grassland cover can indicate water availability, fire prevalence or ecosystem types or transitions. So far we have looked at just one environmental indicator: **soil organic carbon (SOC)**. Looking at indicators in isolation can be useful but may not give us the whole picture, sometimes even misleading us.

It is often useful to combine and compare multiple variables across our landscape, to understand different interactions and responses for different ecological functions.

Let's incorporate another indicator - tree cover - into our analysis to see if we can observe any interesting trends or interactions between them.

The GGW STAC contains both datasets:

``` text
GGW_TreeCover_LC8_2021-01-01_2023-12-31_500m.tif
Soil_Organic_Carbon_2023_GGW_500m.tif
```

Both are 2023 products at 500 m resolution, so they can be used together to describe different aspects of the landscape context around restoration locations.

## 12.1 Access the tree-cover raster

We can access the tree-cover COG in exactly the same way as the SOC raster:

```{r}
tc_url <- "https://stacapi100.thegrit.earth/eodata/cogeo/ggw/GGW_TreeCover_LC8_2021-01-01_2023-12-31_500m.tif"

tree_cover <- rast(paste0("/vsicurl/", tc_url))

tree_cover
```

Check its basic properties:

```{r}
list(
  crs = crs(tree_cover),
  resolution = res(tree_cover),
  extent = ext(tree_cover),
  layers = nlyr(tree_cover)
)
```

We can project our restoration polygons to the tree-cover raster:

```{r}
plots_vect_tc <- project(vect(plots_sf),tree_cover)
```

Now extract the mean tree-cover value within each restoration polygon. Before doing so, think about what kinds of values you might expect to see from your landscape. Is it a densely treed area? Are there forest fragments? What forest-cover values might you expect for your landscape?

```{r}
tc_stats <- extract(tree_cover, plots_vect_tc, fun = mean, na.rm = TRUE)

head(tc_stats)
```

Add it to our restoration dataset:

```{r}
plots_soc_tc <- plots_soc |>
  mutate(
    tc_mean = tc_stats[, 2]
  )
```

We now have a dataset containing your Regreening App polygons, with soil health and land health indicators for each site.

## 12.2 Explore the relationship between the two indicators

Do restoration locations with higher forest cover also tend to have higher soil organic carbon?

```{r}
plots_soc_tc |>
  st_drop_geometry() |>
  ggplot(aes(x = tc_mean, y = soc_mean)) +
  geom_point() +
  geom_smooth()+
  labs(
    title = "Soil organic carbon and tree cover across restoration plots",
    x = "Mean tree cover (%)",
    y = "Mean soil organic carbon (g/kg)"
  ) +
  theme_minimal()
```

### Reflections

> Do the two indicators appear to vary together? Are restoration locations spread across a wide range of landscape conditions? Are there locations with relatively low cover but relatively high SOC, or vice versa?

There does not need to be a strong relationship for this analysis to be useful. The point instead is to start thinking about restoration landscapes as having multiple dimensions rather than being described by one indicator.

## 12.3 Use the two indicators to identify different landscape contexts

We can also divide the observations into broad groups based on the two environmental indicators.

For example, calculate the median of each variable:

```{r}
soc_median <- median(plots_soc_tc$soc_mean,na.rm = TRUE)

tc_median <- median(plots_soc_tc$tc_mean,na.rm = TRUE)
```

Then create simple landscape groups:

```{r}
# We tell R some conditional statements using the 'case_when' function, and instruct R on how to name the new column and outputs where we will save these new classifications, per the conditions set

plots_soc_tc <- plots_soc_tc |>
  mutate(
    landscape_obs = case_when(
      soc_mean >= soc_median &
        tc_mean >= tc_median ~
        "Higher SOC/higher treecover",

      soc_mean >= soc_median &
        tc_mean < tc_median ~
        "Higher SOC/lower treecover",

      soc_mean < soc_median &
        tc_mean >= tc_median ~
        "Lower SOC/higher treecover",

      TRUE ~
        "Lower SOC/lower treecover"
    )
  )
```

See how many restoration plots fall into each group:

```{r}
plots_soc_tc |>
  st_drop_geometry() |>
  count(landscape_obs, sort = TRUE)

View(plots_soc_tc)
```

::: callout-note
The median split here is a simple learning exercise, not necessarily a recommended program monitoring classification system. For real MEL work, thresholds should be based on context-dependent ecological meaning and specific program objectives.
:::

If you are working across several different landscape contexts or your landscape has variable conditions, it can be extremely informative to know how different restoration indicators are performing and interacting - for a more dynamic understanding of these ecosystems, informing adaptive management decisions.

# 13. Monitoring indicator change over time

The GGW STAC products used in this practical are primarily single-period datasets. We saw this when we explored each rasters' metadata.

This is useful for understanding baseline landscape trends and patterns and assessing where might be prioritised for intervention. It can also help us inform decisions around what type of restoration might be needed (erosion control? riverine stabilisation? more trees?).

What these can't help us do, is monitor and track the performance of our interventions over time, and to quantify that change (i.e., baseline \> intervention \> endline). For that, we need a time-series of the same raster indicator. Currently, the GGW STAC catalogue does not have these time-series raster layers - these will become available in coming months.

As more time-indexed raster products become available, the same workflow can be extended to investigate **landscape change through time**.

For example, if we have a vegetation indicator (like the tree-cover raster we used in this practical) over several years, we can extract the same environmental indicator for the same restoration locations at multiple dates, and track each restoration plot over time.

``` text
              2015       2020       2025
Plot A        0.31       0.39       0.44
Plot B        0.52       0.51       0.55
Plot C        0.28       0.25       0.21
```

This helps us track our progress and ask questions like:

-   Are restoration areas showing increasing or decreasing vegetation indicators?

-   Which project areas are changing most?

-   Which areas show little change?

-   Do areas with different restoration approaches show different trajectories?

-   Are some areas showing unexpected declines that warrant investigation?

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

## Well-done!

You have successfully worked through a simple notebook that combines cloud-based raster datasets with field-collected vector data, to extract and analyse landscape conditions at restoration sites.

Having practiced and learned the basics of combining these two types of data - thinking about how they can help us better understand our landscapes, target our interventions, and track and quantify environmental conditions - we can start to build on these skills and perform ever-more interesting analyses and visual outputs to support and communicate our decisions.

If you haven't yet explored the [Create a Report notebook](https://k4ggwa.thegrit.earth/content/state_of_land/tutorials/_downloads/Create_report.qmd) in the Evidence Hub's Practicals Gallery - check it out! You can turn your analysis and write-up into a quick, clean and presentable report in minutes.
