Step 02: Create Mandal Level Raster Bricks

##############################################################
######## Project Name : SATSURE Credit Risk Product
######## File Usage : This script create mandal wise raster bricks
######## Date : November 20, 2018
######## Author : Actify Data Labs
##############################################################

# How to run the script
# Rscript create_mandal_level_raster_bricks.R <veg_index> <district> <no_of_cores>

rm(list = ls())
args <- commandArgs(TRUE)

source(“~/codes/credit_risk_product/utils.R”)
source(“~/codes/credit_risk_product/settings.R”)

# Importing necessary libraries

import_libraries()

# # for testing purposes only ———————————————-
# veg_index <- “ndvi” %>% toupper
# crop_type <- “maize”
# year = “2013”
# # – ———————————————————————–

####### Parameters
(veg_index <- toupper(args[1]))
(district <- tools::toTitleCase(args[2]))
(shp_dir <- glue::glue(“~/{district}/SHP/mandal_shapefiles”))
(data_dir <- glue::glue(“~/{district}”))
(no_of_cores <- as.integer(args[3]))
###################

## Get maximum cores of the machine
(max_cores <- parallel::detectCores(all.tests = FALSE, logical = TRUE))

## Use max cores if specified no of cores is more than max cores
if (no_of_cores > max_cores){
print(glue(“Specified no of cores ({no_of_cores}) is less than maximum cores of the machine ({max_cores}). So, using maximum cores avaiable.”))
no_of_cores <- max_cores
}

future::plan(future::multiprocess, workers = no_of_cores)

# Getting vector layer names and shapefiles
(vector_layer_names <- read_shape_files(dir = shp_dir, file_pattern = “geojson$|shp$”))
(mandal_names <- vector_layer_names$mandal_names)
(mandal_filenames <- vector_layer_names$file_names)

# Making a list of mandal shapefiles
mandal_shapefiles <- future.apply::future_lapply(mandal_filenames, rgdal::readOGR)
(names(mandal_shapefiles) <- lapply(mandal_names, function(name){
mandal_name <- name %>% strsplit(x = ., split = “\\.”) %>% unlist %>% dplyr::first(x = .)
return(mandal_name)
}) %>% unlist)

names(years) <- years
# main_process ———————————————————–

#year <- “2017”

tictoc::tic()
lapply(years, function(year){

print(glue::glue(“We are in the year {year} now!”))

# Reading raster file names
(raster_file_list <- list.files(glue::glue(“{data_dir}/{year}/{veg_index}”), full.names = TRUE, pattern = “clipped”))

# Creating a list of raster objects
(raster_list <- lapply(raster_file_list, raster::raster))

tictoc::tic()
# running the loop for every mandal
future.apply::future_lapply(mandal_shapefiles, function(mandal_shapefile){

print(glue::glue(“Running analysis for mandal {mandal_shapefile$Mandal}”))

#mandal_shapefile <- mandal_shapefiles[1]
mandal_shapefile <- sp::spTransform(mandal_shapefile, CRS(proj4string(raster_list[[1]])))

tictoc::tic()
mandal_raster_list <- lapply(raster_list, function(raster_file){
mandal_raster <- crop(raster_file, mandal_shapefile) %>% mask(x = ., mask = mandal_shapefile)

if(values(mandal_raster) %>% is.na %>% all){
return(NULL)
}else{

return(mandal_raster)
}

}) # loop for mandal_raster_list ends here
tictoc::toc()
# Removing null elements from mandal_raster_list
mandal_raster_list <- Filter(Negate(is.null), mandal_raster_list)

# Making brick
print(glue::glue(“Making raster brick for {mandal_shapefile$Mandal}……”))
raster_brick <- raster::brick(mandal_raster_list)

# Making destination folder filepath
(destination_file_path <- glue::glue(“{data_dir}/{year}/{veg_index}/mandal_level_bricks/”))
if(!dir.exists(destination_file_path)){
dir.create(destination_file_path, recursive = TRUE)
}

# Writing Raster
print(glue::glue(“Writing raster brick for {mandal_shapefile$Mandal}……”))
writeRaster(x = raster_brick,
filename = glue::glue(“{destination_file_path}/{mandal_shapefile$Mandal}_raster_brick.grd”),
format = “raster”,
overwrite = TRUE)

print(glue::glue(“Successfully written brick for mandal {mandal_shapefile$Mandal} for index {veg_index} for the year {year}”))

return(“Success”)

}) # loop for mandal ends here
tictoc::toc()
return(glue::glue(“All bricks successfully written for year {year}”))

}) # loop for year ends here

tictoc::toc()