--- params: ref: "word-styles-reference-var1.docx" output_file: CI_report.docx report_date: "2024-04-18" data_dir: "Sony" mail_day: "Wednesday" output: # html_document: # toc: yes # df_print: paged word_document: reference_docx: !expr file.path("word-styles-reference-var1.docx") toc: yes editor_options: chunk_output_type: console --- ```{r setup, include=FALSE} #set de filename van de output # knitr::opts_chunk$set(echo = TRUE) # output_file <- params$output_file report_date <- params$report_date mail_day <- params$mail_day # # # # Activeer de renv omgeving # renv::activate() # renv::deactivate() # Optioneel: Herstel de omgeving als dat nodig is # Je kunt dit commentaar geven als je het normaal niet wilt uitvoeren # renv::restore() ``` ```{r libraries, message=FALSE, warning=FALSE, include=FALSE} knitr::opts_chunk$set(warning = FALSE, message = FALSE) library(here) library(sf) library(tidyverse) library(tmap) library(lubridate) library(exactextractr) library(zoo) library(raster) library(terra) library(rsample) library(caret) library(randomForest) library(CAST) # Define the log file path log_file <- here("laravel_app/storage/app/rmd_log.txt") # Create a logging function log_message <- function(message) { cat(message, "\n", file = log_file, append = TRUE) } ``` ```{r directories, message=FALSE, warning=FALSE, include=FALSE} project_dir <- params$data_dir # laravel_storage_dir <- here("laravel_app/storage/app/",params$data_dir) laravel_storage_dir <- here("laravel_app/storage/app",project_dir) data_dir <- here(laravel_storage_dir, "Data") # message('DATA_DIR',data_dir) extracted_CI_dir <- here(data_dir, "extracted_ci") daily_CI_vals_dir <- here(extracted_CI_dir, "daily_vals") cumulative_CI_vals_dir <- here(extracted_CI_dir, "cumulative_vals") harvest_dir <- here(data_dir, "HarvestData") weekly_CI_mosaic <- here(laravel_storage_dir, "weekly_mosaic") source(here("r_app", "parameters_project.R")) # s2_dir <- "C:/Users/timon/Resilience BV/4002 CMD App - General/4002 CMD Team/4002 TechnicalData/04 WP2 technical/python/chemba_S2/" ``` ```{r week, message=FALSE, warning=FALSE, include=FALSE} Sys.setlocale("LC_TIME", "C") today <- as.character(report_date) mail_day_as_character <- as.character(mail_day) report_date_as_week_day <- weekdays(ymd(today)) days_of_week <- c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") #als de index of report_date_as_week_day groter dan de index van de mail_day dan moet de week + 1 week <- week(today) log_message(paste("week", week, "today", today)) today_minus_1 <- as.character(ymd(today) - 7) today_minus_2 <- as.character(ymd(today) - 14) today_minus_3 <- as.character(ymd(today) - 21) log_message(paste("report_date_as_week_day", report_date_as_week_day)) log_message(paste("which(days_of_week == report_date_as_week_day)", which(days_of_week == report_date_as_week_day))) log_message(paste("mail_day_as_character", mail_day_as_character)) log_message(paste(" which(days_of_week == mail_day_as_character)", which(days_of_week == mail_day_as_character))) if (which(days_of_week == report_date_as_week_day) > which(days_of_week == mail_day_as_character)){ log_message("adjusting weeks because of mail day") week <- week(today) + 1 today_minus_1 <- as.character(ymd(today)) today_minus_2 <- as.character(ymd(today) - 7) today_minus_3 <- as.character(ymd(today) - 14) } # week <- week(today) # week <- 25 # today = "2024-06-21" #today = as.character(Sys.Date()) #week = lubridate::week(Sys.time()) ## week = 26 #title_var <- paste0("CI dashboard week ", week, " - all pivots dashboard using 3x3 meter resolution") subtitle_var <- paste("Report generated on", Sys.Date()) week_minus_1 <- week -1 # sprintf("%02d", week(today_minus_1)) week_minus_2 <- week -2 # sprintf("%02d", week(today_minus_2)) week_minus_3 <- week -3 # sprintf("%02d", week(today_minus_3)) week <- sprintf("%02d", week) year = year(today) year_1 = year(today_minus_1) year_2 = year(today_minus_2) year_3 = year(today_minus_3) ``` `r subtitle_var` \pagebreak # Explanation of the maps This PDF-dashboard shows the status of your fields on a weekly basis. We will show this in different ways: 1) The first way is with a general overview of field heterogeneity using ‘variation’ – a higher number indicates more differences between plants in the same field. 2) The second map shows a normal image of the latest week in colour, of the demo fields. 3) Then come the maps per field, which show the status for three weeks ago, two weeks ago, last week, and this week, as well as a percentage difference map between last week and this week. The percentage difference maps shows the relative difference in growth over the last week, with positive numbers showing growth, and negative numbers showing decline. 4) Below the maps are graphs that show how each pivot quadrant is doing, measured through the chlorophyll index. ```{r data, message=TRUE, warning=TRUE, include=FALSE} # get latest CI index # remove_pivots <- c("1.1", "1.12", "1.8", "1.9", "1.11", "1.14") CI_quadrant <- readRDS(here(cumulative_CI_vals_dir,"All_pivots_Cumulative_CI_quadrant_year_v2.rds"))# %>% # rename(pivot_quadrant = field) path_to_week_current = here(weekly_CI_mosaic, paste0("week_",week, "_", year, ".tif")) path_to_week_minus_1 = here(weekly_CI_mosaic, paste0("week_",week_minus_1, "_", year_1, ".tif")) path_to_week_minus_2 = here(weekly_CI_mosaic, paste0("week_",week_minus_2, "_", year_2, ".tif")) path_to_week_minus_3 = here(weekly_CI_mosaic, paste0("week_",week_minus_3, "_", year_3, ".tif")) log_message("required mosaic paths") log_message(paste("path to week current",path_to_week_current)) log_message(paste("path to week minus 1",path_to_week_minus_1)) log_message(paste("path to week minus 2",path_to_week_minus_2)) log_message(paste("path to week minus 3",path_to_week_minus_3)) CI <- brick(path_to_week_current) %>% subset("CI") CI_m1 <- brick(path_to_week_minus_1) %>% subset("CI") CI_m2 <- brick(path_to_week_minus_2) %>% subset("CI") CI_m3 <- brick(path_to_week_minus_3) %>% subset("CI") # last_week_dif_raster <- ((CI - CI_m1) / CI_m1) * 100 last_week_dif_raster_abs <- (CI - CI_m1) ``` ```{r data_129, message=TRUE, warning=TRUE, include=FALSE} three_week_dif_raster_abs <- (CI - CI_m3) ``` ```{r data_132, message=TRUE, warning=TRUE, include=FALSE} # AllPivots0 <-st_read(here(data_dir_project, "pivot.geojson")) # AllPivots0$pivot <- factor(AllPivots0$pivot, levels = c("1.1", "1.2", "1.3", "1.4", "1.6", "1.7", "1.8", "1.9", "1.10", "1.11", "1.12", "1.13", "1.14" , "1.16" , "1.17" , "1.18" ,"2.1", "2.2", "2.3" , "2.4", "2.5", "3.1", "3.2", "3.3", "4.1", "4.2", "4.3", "4.4", "4.5", "4.6", "5.1" ,"5.2", "5.3", "5.4", "6.1", "6.2", "DL1.1", "DL1.3")) AllPivots0 <- field_boundaries_sf # joined_spans <-st_read(here(data_dir_project, "span.geojson")) %>% st_transform(crs(AllPivots0)) # pivots_dates <- readRDS(here(harvest_dir, "harvest_data_new")) # pivots_dates$pivot <- factor(pivots_dates$pivot, levels = c("1.1", "1.2", "1.3", "1.4", "1.6", "1.7", "1.8", "1.9", "1.10", "1.11", "1.12", "1.13", "1.14" , "1.16" , "1.17" , "1.18" ,"2.1", "2.2", "2.3" , "2.4", "2.5", "3.1", "3.2", "3.3", "4.1", "4.2", "4.3", "4.4", "4.5", "4.6", "5.1" ,"5.2", "5.3", "5.4", "6.1", "6.2", "DL1.1", "DL1.3")) #AllPivots <- merge(AllPivots0, harvesting_data, by = c("field", "sub_field")) #%>% #rename(field = pivot, sub_field = pivot_quadrant) #%>% select(-pivot.y) #head(AllPivots) #AllPivots_merged <- AllPivots %>% #dplyr::select(field, sub_field, sub_area) %>% unique() %>% # group_by(field) %>% summarise(sub_area = first(sub_area)) #AllPivots_merged <- st_transform(AllPivots_merged, crs = proj4string(CI)) #pivot_names <- unique(CI_quadrant$field) ``` ```{r eval=FALSE, include=FALSE} pivot_stats_q <- cbind(AllPivots0, round(exact_extract(CI, AllPivots0, c("coefficient_of_variation", "mean"), default_value = -9999),2)) %>% st_drop_geometry() %>% as_tibble() hetero_pivots0 <- merge(AllPivots, pivot_stats_q %>% dplyr::select(-hectares, -radius, -pivot), by = "pivot_quadrant") hetero_pivots <- hetero_pivots0 %>% #dplyr::filter(variable %in% "CV") %>% mutate(class = case_when(coefficient_of_variation <= 0.001 ~ "Missing data", coefficient_of_variation >= 0.002 & coefficient_of_variation < 0.1 ~ "Homogeneous", coefficient_of_variation >= 0.1 & coefficient_of_variation < 0.2~ "Somewhat Homogeneous", coefficient_of_variation >= 0.2 & coefficient_of_variation < 0.4 ~ "Somewhat Heterogeneous", coefficient_of_variation >= 0.4 ~ "Heterogeneous")) %>% mutate(class = as.factor(class)) # hetero_pivots %>% filter(pivot == "1.3") hetero_pivots$class <- factor(hetero_pivots$class, levels = c("Missing data", "Homogeneous","Somewhat Homogeneous", "Somewhat Heterogeneous", "Heterogeneous" )) # hetero_pivots %>% select(pivot_quadrant, class, Age, coefficient_of_variation , mean) %>% view() # hetero_pivots %>% filter(class == "Somewhat Heterogeneous" ) %>% select(pivot_quadrant, class, Age, coefficient_of_variation , mean) Mypal <- c('#dcdcdc', '#008000','#8db600','#FFC300','#F22222') hetero_plot <- function(data){ # map <- tm_shape(data) + tm_polygons(col = "class", palette=Mypal) + tm_text("pivot_quadrant", size = 1/2) + tm_layout(main.title=paste0("Homogeneity of pivot quadrants, week ", week, " 2022"),main.title.position = "center")+ tm_compass(position = c("center", "top")) + tm_scale_bar(position = c("center", "top")) # print(map, width = 20, units = "cm") } ``` \newpage ```{r eval=FALSE, fig.height=7, fig.width=10, message=FALSE, warning=FALSE, include=FALSE} hetero_plot(hetero_pivots) ``` ```{r function, message=FALSE, warning=FALSE, include=FALSE} subchunkify <- function(g, fig_height=7, fig_width=5) { g_deparsed <- paste0(deparse( function() {g} ), collapse = '') sub_chunk <- paste0(" `","``{r sub_chunk_", floor(runif(1) * 10000), ", fig.height=", fig_height, ", fig.width=", fig_width, ", echo=FALSE}", "\n(", g_deparsed , ")()", "\n`","`` ") cat(knitr::knit(text = knitr::knit_expand(text = sub_chunk), quiet = TRUE)) } create_CI_map <- function(pivot_raster, pivot_shape, pivot_spans, show_legend = F, legend_is_portrait = F, week, age){ tm_shape(pivot_raster, unit = "m")+ tm_raster(breaks = c(0,0.5,1,2,3,4,5,6,7,Inf), palette = "RdYlGn",legend.is.portrait = legend_is_portrait ,midpoint = NA) + tm_layout(main.title = paste0("\nMax CI week ", week,"\n", age, " weeks old"), main.title.size = 0.7, legend.show = show_legend) # + # tm_shape(pivot_shape) + # tm_borders(lwd = 3) + tm_text("sub_field", size = 1/2) + # tm_shape(pivot_spans) + tm_borders(lwd = 0.5, alpha=0.5) } create_CI_diff_map <- function(pivot_raster, pivot_shape, pivot_spans, show_legend = F, legend_is_portrait = F, week_1, week_2, age){ tm_shape(pivot_raster, unit = "m")+ tm_raster(breaks = c(-3,-2,-1,0,1,2, 3), palette = "RdYlGn",legend.is.portrait = legend_is_portrait ,midpoint = 0, title = "CI difference") + tm_layout(main.title = paste0("CI change week ", week_1, "- week ",week_2, "\n", age," weeks old"), main.title.size = 0.7, legend.show = show_legend) # + # tm_shape(pivot_shape) + # tm_borders(lwd = 3) + tm_text("sub_field", size = 1/2) + # tm_shape(pivot_spans) + tm_borders(lwd = 0.5, alpha=0.5) } ci_plot <- function(pivotName){ # pivotName = "1.1" pivotShape <- AllPivots0 %>% terra::subset(field %in% pivotName) %>% st_transform(crs(CI)) age <- harvesting_data %>% dplyr::filter(field %in% pivotName) %>% dplyr::select(age) %>% unique() AllPivots2 <- AllPivots0 %>% dplyr::filter(field %in% pivotName) singlePivot <- CI %>% crop(., pivotShape) %>% mask(., pivotShape) singlePivot_m1 <- CI_m1 %>% crop(., pivotShape) %>% mask(., pivotShape) singlePivot_m2 <- CI_m2 %>% crop(., pivotShape) %>% mask(., pivotShape) # singlePivot_m3 <- CI_m3 %>% crop(., pivotShape) %>% mask(., pivotShape) abs_CI_last_week <- last_week_dif_raster_abs %>% crop(., pivotShape) %>% mask(., pivotShape) abs_CI_three_week <- three_week_dif_raster_abs %>% crop(., pivotShape) %>% mask(., pivotShape) planting_date <- harvesting_data %>% dplyr::filter(field %in% pivotName) %>% ungroup() %>% dplyr::select(season_start) %>% unique() joined_spans2 <- AllPivots0 %>% st_transform(crs(pivotShape)) %>% dplyr::filter(field %in% pivotName) #%>% unique() %>% st_crop(., pivotShape) CImap_m2 <- create_CI_map(singlePivot_m2, AllPivots2, joined_spans2, show_legend= T, legend_is_portrait = T, week = week_minus_2, age = age -2) CImap_m1 <- create_CI_map(singlePivot_m1, AllPivots2, joined_spans2, show_legend= F, legend_is_portrait = F, week = week_minus_1, age = age -1) CImap <- create_CI_map(singlePivot, AllPivots2, joined_spans2, show_legend= F, legend_is_portrait = F, week = week, age = age ) CI_max_abs_last_week <- create_CI_diff_map(abs_CI_last_week,AllPivots2, joined_spans2, show_legend = T, legend_is_portrait = T, week_1 = week, week_2 = week_minus_1, age = age) CI_max_abs_three_week <- create_CI_diff_map(abs_CI_three_week, AllPivots2, joined_spans2, show_legend = T, legend_is_portrait = T, week_1 = week, week_2 = week_minus_3, age = age) tst <- tmap_arrange(CImap_m2, CImap_m1, CImap,CI_max_abs_last_week, CI_max_abs_three_week, nrow = 1) cat(paste("## Field", pivotName, "-", age, "weeks after planting/harvest", "\n")) # cat("\n") # cat('