Step 07: Temperature Scaling

##############################################################
######## Project Name : SATSURE Credit Risk Product
######## File Usage : This script creates a temperature scaling factor at mandal level and year level and writes to a csv
######## Date : November 20, 2018
######## Author : Actify Data Labs
##############################################################

# How to run the script
#Rscript temperature_scaling.R <crop_type> <district>

### Passing Arguments
args <- commandArgs(TRUE)
crop_type <- tolower(args[1])
district <- tools::toTitleCase(args[2])

library(magrittr)
library(dplyr)
library(glue)

#crop_type <- “maize”
#district <- “Vizianagaram”

# Parameters
data_dir <- glue::glue(“/home/ubuntu/results/{district}/weather_data”)
years <- as.character(2013:2017)
names(years) <- paste0(“X”, years)

if(tolower(crop_type) == “maize”){
min_temp = 15; max_temp = 33
}else if(tolower(crop_type) == “ragi”){
min_temp = 20; max_temp= 35

}else{
stop(“Please enter valid crop!!!”)
}

(file_list <- list.files(data_dir, pattern = “csv”, full.names = TRUE))
(mandal_names <- list.files(data_dir, pattern = “csv”) %>% gsub(pattern = “.csv”, replacement = “”, x = ., fixed = TRUE) %>% gsub(pattern = ” “, replacement = “”, x = ., fixed = TRUE))

names(file_list) <- mandal_names
# Main code —————————————————————

mandal_wise_scale_list <- lapply(file_list, function(file){

temperature_df <- read.csv(file)
temperature_df <- temperature_df %>% select(Date, Tmin, Tmax, Tavg) %>% mutate(Date = as.Date(Date))
# temperature_df$Date <- as.Date(temperature_df$Date)

yearwise_scale_list <- lapply(years, function(year){
(start_date <- as.Date(glue::glue(“{as.numeric(year)}-10-01”)))
(end_date <- as.Date(glue::glue(“{as.numeric(year)+1}-04-30”)))

df <- temperature_df %>% filter(Date >= start_date, Date <= end_date)

bad_days <- df %>% filter(Tmin < min_temp, Tmax > max_temp) %>% nrow
all_days <- nrow(df)
scaling_factor <- 1 + (bad_days/all_days)

return(scaling_factor)
})
return(yearwise_scale_list)
})

scaled_df <- do.call(rbind, mandal_wise_scale_list) %>% as.data.frame() %>% tibble::rownames_to_column(df = ., var = “Mandal”)

data.table::fwrite(x = scaled_df,
file = glue::glue(“/home/ubuntu/results/{district}_{crop_type}_temperature_scaling_factors.csv”),
append = FALSE,
sep = “,”,
row.names = FALSE,
col.names = TRUE)