Chapter 16 NDVI

library(MODISTools)

# MODIS data sit on a sinusoidal grid, which is skewed away from the equator,
# so we measure the area covered by our cameras (plus 1 km) on that grid
modis_crs <- "+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +R=6371007.181 +units=m +no_defs"
cams_sinu <- st_bbox(st_buffer(st_transform(locs_sf, modis_crs), 1000))

# The centre of that area, converted back to latitude and longitude
aoi_centre <- st_sfc(st_point(c(mean(cams_sinu[c("xmin", "xmax")]),
                                mean(cams_sinu[c("ymin", "ymax")]))), crs = modis_crs) %>%
  st_transform(4326) %>%
  st_coordinates()

# The distance from the centre to the edges, in km. The service sizes requests
# using a nominal 250 m pixel (true size 231.7 m), so we scale up to compensate
km_lr <- ceiling((cams_sinu["xmax"] - cams_sinu["xmin"]) / 2000 * 250 / 231.656)
km_ab <- ceiling((cams_sinu["ymax"] - cams_sinu["ymin"]) / 2000 * 250 / 231.656)
if (km_lr > 100 | km_ab > 100) stop("Cameras cover too large an area for one request")

# MODIS product and band of interest
product <- "MOD13Q1"           # run mt_products() for a list of products available
band <- "250m_16_days_NDVI"    # run mt_bands("MOD13Q1") for a list of bands available

# Specify the time range - we will use a random couple of months
time_range <- c("2022-01-01", "2022-02-28")

# Download the data once, and save a copy to reuse
ndvi_file <- paste0("data/processed_data/", locs$project_id[1], "_MOD13Q1_NDVI.csv")

if (!file.exists(ndvi_file)) {
  ndvi_df <- mt_subset(product = product,
                       band = band,
                       lat = aoi_centre[1, "Y"],
                       lon = aoi_centre[1, "X"],
                       start = time_range[1],
                       end = time_range[2],
                       km_lr = km_lr,
                       km_ab = km_ab,
                       site_name = locs$project_id[1],
                       internal = TRUE,
                       progress = FALSE)
  write.csv(ndvi_df, ndvi_file, row.names = F)
}

ndvi_df <- read.csv(ndvi_file)

# Convert to a raster: one layer per 16-day image, NDVI already scaled to -1 to 1
r <- mt_to_terra(ndvi_df)

# Check every camera falls inside the downloaded area
cams_check <- vect(st_transform(locs_sf, crs(r)))
outside <- !terra::relate(cams_check, as.polygons(r[[1]], extent = TRUE), "intersects")[, 1]
if (any(outside)) stop("Cameras outside the NDVI area: ", paste(locs_sf$placename[outside], collapse = ", "))

# Remove fill values (valid NDVI is -0.2 to 1)
r[r < -0.2] <- NA

# Match the projection of our camera locations, and trim to the cameras plus 1 km
r <- terra::project(r, "EPSG:4326")
r <- terra::crop(r, vect(st_buffer(locs_sf, 1000)))

# Plot the resulting NDVI data
terra::plot(r, col = rev(terrain.colors(20)), 
            range=c(0,1)) # Specify the range of values you want to plot

# Extract the data to camera locations
tmp <- terra::extract(r, vect(locs_sf), ID=F) # Extract - each layer will become its own column
locs_sf$mean_ndvi <- rowMeans(tmp, na.rm=TRUE) # take the mean of each column

#######################################
# Convert it back to a dataframe
locs_sf$geometry <- NULL

locs <- left_join(locs, locs_sf)

# Write the dataset

write.csv(locs, paste0("data/processed_data/", locs$project_id[1],"_camera_locations_and_covariates.csv"), row.names=F)

16.1 Data exploration

16.1.1 Final map

list.of.packages <- c("kableExtra", "tidyr", "leaflet", "dplyr", "viridis", "corrplot", "lubridate", "plotly")

new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)
lapply(list.of.packages, require, character.only = TRUE)

# Final locations plot

locs <- read.csv(paste0("data/processed_data/",pro$project_id[1],"_camera_locations_and_covariates.csv"))

# If you want to color by a category do it here:
category <- "feature_type"
# First lets choose a category to color
locs[,category] <- factor(locs[,category])
col.cat <- turbo(length(levels(locs[,category])))
# Add it to the dataframe
locs$colours <- col.cat[locs[,category]]

m <- leaflet() %>%
  # Add a satellite image layer
  addProviderTiles(providers$Esri.WorldImagery, group="Satellite") %>%  
  addProviderTiles(providers$Esri.WorldTopoMap, group="Base") %>%     
  addCircleMarkers(lng=locs$longitude, lat=locs$latitude,
                   # Color the markers depending on the 'feature type'
                   color=locs$colours,
                   # Add a popup of the deployment code 
                   popup=paste(locs$placename, locs[,category])) %>%
  # Add a legend explaining what is going on
  addLegend("bottomleft", colors = col.cat,  labels = levels(locs[,category]),
    title = category,
    labFormat = labelFormat(prefix = "$"),
    opacity = 1
  ) %>%
  # add a layer control box to toggle between the layers
  addLayersControl(
    baseGroups = c("Satellite", "Base"),
    options = layersControlOptions(collapsed = FALSE)
  )
m

16.1.2 Detection summary

sp_summary <- read.csv(paste0("data/processed_data/",pro$project_id[1],"_species_list.csv"), header=T)
total_obs <- read.csv(paste0("data/processed_data/",pro$project_id[1],"_30min_independent_total_observations.csv"), header=T)

# Convert to long
long_obs <- total_obs %>% 
  pivot_longer(cols=sp_summary$sp,  # The columns we want to create into rows - species
               names_to="sp",       # What we what the number column to be called
               values_to = "count") # Takes the values in the species columns and calls them `count`


# We can them summaries those using dplyr
tmp <- long_obs %>%                   # Take the long observation data frame `long_obs` 
          group_by(sp) %>%            # Group by species
          summarise(count=sum(count)) # Sum all the independent observations

# Add it to the sp_summary dataframe
sp_summary <- left_join(sp_summary, tmp)

## Occupancy
# We use the mutate function to mutate the column
total_binary <-  total_obs %>%    # The total obs dataframe              
                    mutate(across(sp_summary$sp, ~+as.logical(.x)))  # across all of the species columns, make it binary

# Flip the dataframe to longer - as before
long_bin <- total_binary %>% 
  pivot_longer(cols=sp_summary$sp, names_to="sp", values_to = "count") # Takes the species names columns, and makes them unique rows with "sp" as the key 

# We can now sum the presence/absences and divide by the number of survey locations
tmp <- long_bin %>% 
  group_by(sp) %>% 
  summarise(occupancy=sum(count)/nrow(locs)) # divided the sum by the number of sites

# add the results to the sp_summary
sp_summary <- left_join(sp_summary, tmp)


###########################
# Comparison plot
# Lets put the dataframes in a sensible order
sp_summary <- sp_summary[order(sp_summary$count),]

yform <- list(categoryorder = "array",
              categoryarray = sp_summary$sp)

xform <- list(title="Captures")

# Capture rate
fig1 <- plot_ly(x = sp_summary$count, y = sp_summary$common_name, type = 'bar', orientation = 'h') %>% 
 layout(yaxis = yform, xaxis=xform)

yform <- list(categoryorder = "array",
              categoryarray = sp_summary$sp,
              showticklabels=F)
xform <- list(title="Occupancy")


# Occupancy
fig2 <- plot_ly(x = sp_summary$occupancy, y = sp_summary$common_name, type = 'bar', orientation = 'h') %>% 
 layout(yaxis = yform, xaxis=xform)

subplot(nrows=1,fig1, fig2, titleX = T) # We could stack them on top of one another using nrows=2

QUESTION What does this tell you about the behavior of the target species?

16.1.3 Temporal patterns

par(mar=c(5,4,1,1))
# Temporal patterns
mon_obs <- read.csv(paste0("data/processed_data/",pro$project_id[1],"_30min_independent_monthly_observations.csv"), header=T)

# Count up the number of stations and the number of camera nights
mon_summary <- mon_obs %>%                  # Use the monthly observations dataframe
            group_by(date) %>%              # Group by the date
            summarise(locs_active=n(),      # Count the number of active cameras
                      cam_days=sum(days))   # And sum the active days 


# Add in the species specific counts - and join it with the mon_summary dataframe
mon_summary <- mon_obs %>% 
                group_by(date) %>%  
                summarise(across(sp_summary$sp, sum, na.rm=TRUE)) %>% # summarise across all of 
                                                                      # the species columns 
                left_join(x=mon_summary)   # Join with the mon_summary dataframe

# We first need to convert the date column to a date object
mon_summary$date <- ym(mon_summary$date)

# Set up a two panel plot (side by side)
par(mfrow=c(1,2))

plot(mon_summary$date, mon_summary$locs_active,
     type="o", 
     pch=19,
     ylim=c(0, max(mon_summary$locs_active)),
     las=1, 
     ylab="Number of cameras active", xlab="Date")


# Sum all the captures rates for the species columns
mon_summary$all.sp <- rowSums(mon_summary[, sp_summary$sp])

# Plot them
plot(mon_summary$date, mon_summary$all.sp/(mon_summary$cam_days/100),
     type="o",
     pch=19,
     las=1, ylab="Detections per 100 cam days", xlab="Date")

Question What is going on in these plots?

# Species specific plots

par(mfrow=c(2,2))
i <- 1
for(i in 1:length(sp_summary$sp))
{
  plot(mon_summary$date, pull(mon_summary, sp_summary$sp[i])/(mon_summary$cam_days/100),  # The pull command allows you to grab a specific column in a dataframe and turn it into a vector!
     type="o",
     pch=19,
     las=1, ylab="Detections per 100 cam days", xlab="Date",
     main=sp_summary$sp[i])
}

Question Any interesting patterns?

16.1.4 Spatial patterns

# Spatial plots

total_obs <- left_join(total_obs, locs)

# Jaguar
focal_species <- "Panthera.onca"

focal_cr <- pull(total_obs, focal_species)/(total_obs$days/100)

m <- leaflet() %>%
  addProviderTiles(providers$Esri.WorldTopoMap, group="Base") %>%     
  addCircleMarkers(lng=locs$longitude, lat=locs$latitude,
                   # Add a popup of the deployment code 
                   popup=paste(locs$placename),
                   radius=(focal_cr/max(focal_cr)*10)+1, stroke=F,
                   fillOpacity=0.6) 
m

Try other species!

Question Any interesting patterns?

16.1.5 Species co-occurance

# Co-occurances
par(mfrow=c(1,1))

# Pull the data for each of the species from 
tmp <- total_obs[, sp_summary$sp]
M <- cor(tmp)

corrplot(M, method="color", 
         type="upper", 
         order="hclust",
         # addCoef.col = "black", # We suppress the coefs to make a cleaner plot
         tl.col="black", tl.srt=45, #Text label color and rotation
         diag=FALSE
         )

Question Any interesting patterns?

You can now do some data exploration plots.

# Prepare the data
locs <- locs %>% 
            mutate_if(is.character,as.factor) # If a column is a character string, make it a factor

total_obs <- left_join(total_obs, locs)

We have the following species:

sp_summary$sp

And the following categories to explore:

 c("feature_type", "elevation", "mean_ndvi")

Try some boxplots and scatter charts!