#!/usr/bin/env Rscript
## ---------------------------
##
## Script name: 00_explore.R
##
## Purpose of script: Clean and explore Laos climate data provided by DHIS2
## Author: Daniela Lührsen
## Date Created: 2024-07-17
## Email: daniela.luhrsen@bsc.es
##
## ---------------------------

## load up the packages
packages <- c("ggplot2", "dplyr", "tidyr", "lubridate", "sf")
lapply(packages, require, character.only = TRUE)

## ---------------------------

##############################################################
##### CLEANING ----------------------------------------------
##############################################################
# load data
data <- read.csv("data/laos/climate.csv")

# fix dates
data$year <- substr(data$period, 1, 4)
data$month <- substr(data$period, 5, 6)
data$day <- substr(data$period, 7, 8)
data$date <- as.Date(paste0(data$year, data$month, data$day), format = "%Y%m%d")

# fix variables
# Climate-Temperature max           ZH76qVQl5Mz
# Climate-Temperature min           GUGH0txkkNs
# Climate-Rainfall                  gsiW9SgolNd
# Climate-Temperature avg           VA05qvanuVs
data$variable[data$dataelement == "ZH76qVQl5Mz"] <- "tasmax"
data$variable[data$dataelement == "GUGH0txkkNs"] <- "tasmin"
data$variable[data$dataelement == "gsiW9SgolNd"] <- "prlr"
data$variable[data$dataelement == "VA05qvanuVs"] <- "tas"

# fix orgunit
data$orgunit_id <- substr(data$orgunit, 1, 2)
data$orgunit_name <- substr(data$orgunit, 4, 100)

# select only necessary columns
data <- data[, c("year", "month", "day", "date", "value",
                 "variable", "orgunit_id", "orgunit_name")]

# turn table from long to wide format
data <- data %>%
  pivot_wider(names_from = variable, values_from = value)

# save clean data
write.csv(data, "data/laos/laos_climate_2015-2023.csv", row.names = FALSE)


##############################################################
##### QUALITY ASSESSMENT -------------------------------------
##############################################################

# load data
data <- read.csv("data/laos/laos_climate_2015-2023.csv")

# check summary for each variable
summary(data$tasmax) #2
summary(data$tasmin) #1
summary(data$tas) # 4412
summary(data$prlr) #5


# # check the high max values
data[data$tasmax > 50, ]
data[data$tas > 50, ]
# they are only few values, so replace with NA
data$tasmax[data$tasmax > 50] <- NA
data$tas[data$tas > 50] <- NA


#check high number of NA in tas
na_count <- aggregate(is.na(data$tas), by = list(data$orgunit_name), FUN = sum)
# equally distributed spatially
na_count <- aggregate(is.na(data$tas), by = list(data$date), FUN = sum)
na_count[na_count$x != 0, ]
# no rainfall since may 2023

yearly_tas <- aggregate(data$tas,
                        by=list(orgunit= data$orgunit_name),
                        FUN = mean, na.rm = TRUE)

yearly_prlr <- aggregate(data$prlr,
                        by=list(orgunit= data$orgunit_name),
                        FUN = sum, na.rm = TRUE)
yearly_prlr$x <- yearly_prlr$x / length(unique(data$year))


##############################################################
##### Visualise -------------------------------------
##############################################################

monthly <- aggregate(list(tasmax = data$tasmax,
                          tasmin = data$tasmin,
                          tas = data$tas,
                          prlr = data$prlr),
                     by = list(year = data$year,
                               month = data$month,
                               orgunit_id = data$orgunit_id,
                               orgunit_name = data$orgunit_name),
                     FUN = mean, na.rm = TRUE)
monthly$date <- as.Date(paste0(monthly$year,
                               sprintf("%02d", monthly$month),
                               "01"),
                        format = "%Y%m%d")


#  daily timeseries------------------------------------------------------------

# mean temperature
ggplot(data = monthly, aes(x = date, y = tas)) +
  geom_line() +
  labs(title = "",
       x = "Date",
       y = "Mean temperature") +
  facet_wrap(~ orgunit_name, ncol = 3) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# precipitation
ggplot(data = monthly, aes(x = date, y = prlr)) +
  geom_line() +
  labs(title = "",
       x = "Date",
       y = "Precipitation") +
  facet_wrap(~ orgunit_name, ncol = 3) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

#combined
ggplot(data = monthly, aes(x = date)) +
  geom_col(aes(y = prlr), fill = "blue", alpha = 0.6) +   # Precipitation as blue bars
  geom_line(aes(y = tas/3), color = "red", size = 1) + # Temperature as red line (scaled)
  scale_y_continuous(
    name = "Precipitation",
    sec.axis = sec_axis(~. * 3, name = "Mean Temperature") # Secondary axis for temperature
  ) +
  labs(title = "",
       x = "Date") +
  facet_wrap(~ orgunit_name, ncol = 3) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# month of the year ---------------------------------------------------------

# add month column
monthly <- monthly %>%
  mutate(month = month(date, label = TRUE, abbr = TRUE))

# Calculate the mean tasmax for each month and each orgunit_name
monthly_means <- monthly %>%
  group_by(orgunit_name, month) %>%
  summarise(mean_tasmax = mean(tasmax, na.rm = TRUE),
            mean_tasmin = mean(tasmin, na.rm = TRUE),
            mean_tas = mean(tas, na.rm = TRUE),
            mean_prlr = mean(prlr, na.rm = TRUE)) %>%
  ungroup()

# plot mean temperature
ggplot(data = monthly_means, aes(x = month, y = mean_tas, group = 1)) +
  geom_line() +
  labs(title = "",
       x = "Month",
       y = "Mean temperature") +
  facet_wrap(~ orgunit_name, ncol = 3) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# plot precipitation
ggplot(data = monthly_means, aes(x = month, y = mean_prlr, group = 1)) +
  geom_line() +
  labs(title = "",
       x = "Month",
       y = "Precipitation") +
  facet_wrap(~ orgunit_name, ncol = 3) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# map --------------------------------------------------------------------------

# load shapefile
orgunits_shapefile <- sf::st_read("data/laos/shapefile/gadm41_LAO_1.shp")

# correct the shapefile
orgunits_shapefile$NAME_1[orgunits_shapefile$NAME_1 == "Louang Namtha"] <-  "Louangnamtha"
orgunits_shapefile$NAME_1[orgunits_shapefile$NAME_1 == "Phôngsali"] <- "Phongsali"
orgunits_shapefile$NAME_1[orgunits_shapefile$NAME_1 == "Oudômxai"] <-  "Oudomxai"
orgunits_shapefile$NAME_1[orgunits_shapefile$NAME_1 == "Saravan"] <-  "Salavan"
orgunits_shapefile$NAME_1[orgunits_shapefile$NAME_1 == "Savannakhét"] <-  "Savannakhet"
orgunits_shapefile$NAME_1[orgunits_shapefile$NAME_1 == "Xaignabouri"] <-  "Xainyabouli"
orgunits_shapefile$NAME_1[orgunits_shapefile$NAME_1 == "Xaisômboun"] <-  "Xaisomboun"
orgunits_shapefile$NAME_1[orgunits_shapefile$NAME_1 == "Xékong"] <-  "Xekong"
orgunits_shapefile$NAME_1[orgunits_shapefile$NAME_1 == "Louangphrabang"] <-  "Louangphabang"
orgunits_shapefile$NAME_1[orgunits_shapefile$NAME_1 == "Xiangkhoang"] <-  "Xiangkhouang"
orgunits_shapefile$NAME_1[orgunits_shapefile$NAME_1 == "Vientiane [prefecture]"] <-  "Vientiane Capital"

sf::st_write(orgunits_shapefile, "data/laos/shapefile/gadm41_LAO1_cleaned.shp")

# get mean of temperature and sum of precipitation
summary_stats <- monthly %>%
  group_by(orgunit_id, orgunit_name) %>%
  summarise(
    mean_tasmax = mean(tasmax, na.rm = TRUE),
    mean_tasmin = mean(tasmin, na.rm = TRUE),
    mean_tas = mean(tas, na.rm = TRUE),
    total_prlr = sum(prlr, na.rm = TRUE)
  ) %>%
  ungroup()

# Merge the summary statistics with the shapefile
orgunits_shapefile <- orgunits_shapefile %>%
  left_join(summary_stats, by = c("NAME_1" = "orgunit_name"))

# plot total precipitation
ggplot(orgunits_shapefile) +
  geom_sf(aes(fill = total_prlr)) +
  scale_fill_viridis_c(option = "plasma") +
  labs(title = "Total Precipitation",
       fill = "Total precipitation") +
  theme_minimal()

# Rcombine temperature to plot them all in the same map
temperature_data <- orgunits_shapefile %>%
  select(NAME_1, mean_tasmax, mean_tasmin, mean_tas) %>%
  pivot_longer(cols = starts_with("mean"),
               names_to = "variable",
               values_to = "value") %>%
  mutate(variable = factor(variable,
                           levels = c("mean_tasmin", "mean_tas", "mean_tasmax")))

# plot min, mean, max temperature
ggplot(temperature_data) +
  geom_sf(aes(fill = value)) +
  scale_fill_viridis_c(option = "plasma", name = "Temperature") +
  facet_wrap(~ variable,
             ncol = 3,
             labeller = as_labeller(c(mean_tasmax = "Mean Maximum Temperature",
                                      mean_tasmin = "Mean Minimum Temperature",
                                      mean_tas = "Mean Temperature"))) +
  theme_minimal()

### END
