
# ------------------------------------------------------------------------------------
# website for climate data

# https://www.worldclim.org/data/worldclim21.html
# Fick, S.E. and R.J. Hijmans, 2017. WorldClim 2: new 1km spatial resolution climate surfaces for global land areas. International Journal of Climatology 37 (12): 4302-4315.


# --------------------------------------------------------------------------------
# setup

# install and load packages
require(pacman)
pacman::p_load(tidyverse, purrr, rgeos, sp, maps, maptools, RCurl, rgdal, 
               raster, mapproj, MODISTools, rts, gdalUtils, DescTools)

# global options
options(scipen = 20)

# set character encoding to UTF-8
Sys.setlocale(category = "LC_ALL", locale = "en_US.UTF-8")

# path to working directory
base_path <- "~/Dropbox/Research/hunter-gatherer-diets"

# data directory
output_dir <- file.path(base_path, "data")
if (dir.exists(output_dir)){
  print("Directory already exists!")
} else {
  dir.create(output_dir)
}


# ------------------------------------------------------------------------------------
# read diet data

dat <- read_csv(file.path(base_path, "data", "raw_diet_data.csv"))

# create average latitude value and convert diet percentages to proportions
dat %>%
  mutate(across(starts_with(c("hg","plant", "animal", "honey", "protein", 
                              "lipid", "fiber", "sugar", "carb")), function(x) x/100),
         latitude_avg = (latitude_min + latitude_max) / 2) %>% 
  rename(reliability=total_reliability) ->
  dat

glimpse(dat)


# ------------------------------------------------------------------------------------
# extract Bio1: annual mean temperature

# change path to location of GeoTiff file
bio1 <- raster(file.path("/Volumes/Extreme",  "wc2.1_30s_bio_1.tif"))

# create spatialPoints object
dat_sp <- with(dat, SpatialPoints(cbind(longitude, latitude_avg), proj4string = CRS(proj4string(bio1))))

# get cell values with buffer (in meters)
temp_mean_15km <- extract(x=bio1, y=dat_sp, method="simple", buffer=15000, fun=mean, na.rm=TRUE)

# collect temp data in a tibble
tibble(study=dat$study,
       temp_mean_15km=temp_mean_15km) ->
temp_avg


# --------------------------------------------------------------------------------
# merge and save diet and bio data

dat_temp <- merge(dat, temp_avg, by="study", all=TRUE)

write_csv(dat_temp, file=file.path(base_path, "data", "raw_diet_temp_data.csv"))


