## ===================================================================== ## Paper1_analysis_and_figures.R ## Targeted-yield fertiliser prescriptions for finger millet on a Rhodustalf: ## statistics, tables, PCA (FactoMineR), GIS map (sf) and all manuscript figures. ## ## Requirements : R >= 4.3 with ggplot2, dplyr, tidyr, sf, patchwork, ggrepel, ## FactoMineR, factoextra, pheatmap, ragg, cowplot, RColorBrewer, ## jsonlite, grid, scales (tested with R 4.3.3, ggplot2 3.4.4, ## sf 1.0-15, FactoMineR 2.9, factoextra 1.0.7, patchwork 1.2.0). ## Input : validation_dataset.csv in the working directory (or set the ## environment variable P1_BASE to the folder that holds it). ## Fonts : figures use "Liberation Sans"; change FAM below if absent. ## Boundaries : Census 2011 district and state layers (DataMeet, CC BY 4.0) ## are downloaded into ./gis on first run. ## Edit : the validation-farm coordinates in the 'pts_ll' block of the ## Fig. 1 section (block-level position until GPS is available). ## Output : ./out/figs (PNG, 300 dpi), ./out/tables (CSV, JSON, RDS), ## ./out/gis/study_sites.gpkg (opens directly in QGIS). ## ===================================================================== ## ###################################################################### ## 00_setup.R ## ###################################################################### ## ===================================================================== ## 00_setup.R - data, parameters, helpers (Paper 1: finger millet STCR) ## R >= 4.3 ; packages: ggplot2, dplyr, tidyr, sf, patchwork, ggrepel, ## FactoMineR, factoextra, pheatmap, ragg, jsonlite ## ===================================================================== suppressPackageStartupMessages({ library(ggplot2); library(dplyr); library(tidyr); library(sf) library(patchwork); library(ggrepel); library(FactoMineR); library(factoextra) library(pheatmap); library(ragg); library(grid); library(scales); library(jsonlite) }) options(stringsAsFactors = FALSE, dplyr.summarise.inform = FALSE) set.seed(20260108) BASE <- Sys.getenv("P1_BASE", getwd()) OUT <- file.path(BASE, "out") for (s in c("figs", "tables", "gis")) dir.create(file.path(OUT, s), recursive = TRUE, showWarnings = FALSE) FAM <- "Liberation Sans" save_fig <- function(p, name, w, h, dpi = 300) { ragg::agg_png(file.path(OUT, "figs", paste0(name, ".png")), width = w, height = h, units = "in", res = dpi, background = "white") print(p); invisible(dev.off()) } rnd <- function(x, d = 0) floor(x * 10^d + 0.5 + 1e-9) / 10^d # round half up fmt <- function(x, d = 0) formatC(rnd(x, d), format = "f", digits = d) ## ---------- validation data ---------- d <- read.csv(file.path(BASE, "validation_dataset.csv"), stringsAsFactors = FALSE) d$Farm <- factor(ifelse(d$Location == "I", "Ayyakannur", "Palayam"), levels = c("Ayyakannur", "Palayam")) trt <- data.frame( Trt = paste0("T", 1:10), short = c("RDF", "RDF+FYM", "NPK-3.0", "NPK-3.5", "NPK-4.0", "IPNS-3.0", "IPNS-3.5", "IPNS-4.0", "FP", "Control"), long = c("Blanket (RDF)", "Blanket + FYM", "STCR-NPK 3.0", "STCR-NPK 3.5", "STCR-NPK 4.0", "STCR-IPNS 3.0", "STCR-IPNS 3.5", "STCR-IPNS 4.0", "Farmers' practice", "Absolute control"), group = c("Blanket (RDF)", "Blanket + FYM", "STCR-NPK", "STCR-NPK", "STCR-NPK", "STCR-IPNS", "STCR-IPNS", "STCR-IPNS", "Farmers' practice", "Absolute control"), target = c(NA, NA, 3.0, 3.5, 4.0, 3.0, 3.5, 4.0, NA, NA), letter = c("h", "de", "g", "d", "b", "f", "c", "a", "i", "j"), # ANOVA letters as reported in the thesis (pooled) stringsAsFactors = FALSE) d <- left_join(d, trt, by = "Trt") d$Trt <- factor(d$Trt, levels = paste0("T", 1:10)) d$short <- factor(d$short, levels = trt$short) GROUPS <- c("STCR-IPNS", "STCR-NPK", "Blanket + FYM", "Blanket (RDF)", "Farmers' practice", "Absolute control") d$group <- factor(d$group, levels = GROUPS) COL <- c("STCR-IPNS" = "#009E73", "STCR-NPK" = "#E69F00", "Blanket + FYM" = "#0072B2", "Blanket (RDF)" = "#56B4E9", "Farmers' practice" = "#CC79A7", "Absolute control" = "#5E5E5E") SHP <- c(Ayyakannur = 21, Palayam = 24) d$ach <- d$Yield_kg_ha / d$Target_kg_ha * 100 d$err <- d$Yield_kg_ha - d$Target_kg_ha d$NR_N <- d$Uptake_N / (d$Yield_kg_ha / 1000) d$NR_P2O5 <- d$Uptake_P * 2.29 / (d$Yield_kg_ha / 1000) d$NR_K2O <- d$Uptake_K * 1.21 / (d$Yield_kg_ha / 1000) ## ---------- basic parameters (Table 3 of the manuscript) ---------- NR <- c(N = 21.1, P2O5 = 7.5, K2O = 26.0) # kg per tonne grain Cs <- c(N = 14.86, P2O5 = 19.19, K2O = 18.95) # % soil Cf <- c(N = 44.16, P2O5 = 32.79, K2O = 59.75) # % fertiliser Cfy <- c(N = 28.47, P2O5 = 11.77, K2O = 33.78) # % FYM CONV <- c(N = 1, P2O5 = 2.29, K2O = 1.21) A_T <- NR / (Cf / 100) # kg per t of target B_S <- Cs / Cf * CONV # per kg soil test value B_O <- Cfy / Cf * CONV # per kg elemental FYM nutrient BLANKET <- c(N = 60, P2O5 = 30, K2O = 30) LO <- 0.5 * BLANKET; HI <- 1.5 * BLANKET fym_elem <- function(t, comp, moist = 0.24) t * 1000 * (1 - moist) * comp / 100 # kg ha-1 of N, P, K dose <- function(T, S, O = c(0, 0, 0)) { raw <- A_T * T - B_S * S - B_O * O list(raw = raw, final = pmin(pmax(raw, LO), HI)) } FYM_REF <- c(0.66, 0.32, 0.54) # % N, P, K (dry basis), calibration FYM FYM_VAL <- c(0.54, 0.25, 0.55) # % N, P, K (dry basis), validation FYM ## ---------- sites ---------- sites <- data.frame( site = c("Thoppupatti", "Ayyakannur", "Palayam"), short = c("T", "A", "P"), phase = c("Phases I-II (calibration)", "Phase III (validation)", "Phase III (validation)"), block = c("Vedasandur", "Guziliamparai", "Guziliamparai"), SN = c(215, 241, 249), SP = c(21.3, 28.5, 29.9), SK = c(219, 294, 290), stringsAsFactors = FALSE) RANGE <- data.frame(var = c("N", "P2O5", "K2O"), lo = c(198, 18.2, 191), hi = c(250, 37.4, 255)) ## ---------- Phase II strip summary (Table 2 of the manuscript) ---------- strip <- data.frame( strip = rep(c("I", "II", "III"), each = 7), var = rep(c("KMnO4-N", "Olsen-P", "NH4OAc-K", "Grain yield", "N uptake", "P uptake", "K uptake"), 3), mean = c(200, 22.1, 197, 2100, 42.2, 6.1, 48.9, 224, 29.7, 226, 2719, 56.6, 8.5, 59.5, 244, 34.3, 249, 2917, 70.7, 13.7, 64.0), min = c(198, 18.2, 191, 1324, 28.5, 3.9, 35.5, 221, 26.5, 223, 1731, 35.1, 5.3, 45.0, 240, 32.0, 245, 1895, 45.8, 6.0, 50.0), max = c(207, 24.5, 200, 2779, 59.0, 8.8, 62.1, 231, 31.9, 233, 3614, 85.0, 13.5, 76.4, 250, 37.4, 255, 3962, 89.5, 18.9, 85.5)) theme_ms <- function(base = 8) { theme_bw(base_size = base, base_family = FAM) %+replace% theme(panel.grid.minor = element_blank(), panel.grid.major = element_line(colour = "grey92", linewidth = 0.25), panel.border = element_rect(colour = "grey35", fill = NA, linewidth = 0.4), strip.background = element_rect(fill = "grey94", colour = "grey35", linewidth = 0.4), strip.text = element_text(size = base, face = "bold", margin = margin(2, 2, 2, 2)), axis.ticks = element_line(linewidth = 0.3, colour = "grey35"), axis.text = element_text(colour = "grey15"), legend.key.size = unit(3.4, "mm"), legend.title = element_text(face = "bold", size = base), legend.text = element_text(size = base - 0.5), plot.tag = element_text(face = "bold", size = base + 2), plot.title = element_text(face = "bold", size = base + 0.5, hjust = 0), plot.margin = margin(3, 8, 3, 3)) } tagit <- function() plot_annotation(tag_levels = "a", tag_prefix = "(", tag_suffix = ")", theme = theme(plot.tag = element_text(face = "bold", size = 10, family = FAM))) ## ---------- 0b. boundary layers (DataMeet India community, CC BY 4.0) ---------- gdir <- file.path(BASE, "gis"); dir.create(gdir, showWarnings = FALSE) base_url <- "https://raw.githubusercontent.com/datameet/maps/master" dl1 <- function(url, dest) if (!file.exists(dest)) try(download.file(url, dest, mode = "wb", quiet = TRUE), silent = TRUE) for (e in c("shp", "dbf", "shx", "prj")) dl1(sprintf("%s/Districts/Census_2011/2011_Dist.%s", base_url, e), file.path(gdir, paste0("2011_Dist.", e))) for (e in c("shp", "dbf", "shx", "prj", "cpg")) dl1(sprintf("%s/States/Admin2.%s", base_url, e), file.path(gdir, paste0("states_Admin2.", e))) ## ###################################################################### ## 01_stats.R ## ###################################################################### ## 01_stats.R - statistics, tables and PCA (writes out/tables/*) J <- list() ## ---------- A. accuracy of prescriptions ---------- s <- d %>% filter(!is.na(Target_kg_ha)) acc <- function(x) data.frame(n = nrow(x), ach_mean = mean(x$ach), ach_min = min(x$ach), ach_max = max(x$ach), bias = mean(x$err), rmse = sqrt(mean(x$err^2)), mape = mean(abs(x$err) / x$Target_kg_ha * 100)) acc_all <- acc(s); acc_ipns <- acc(filter(s, group == "STCR-IPNS")); acc_npk <- acc(filter(s, group == "STCR-NPK")) acc_rows <- bind_rows( cbind(label = "All prescriptions", acc_all), cbind(label = "STCR-IPNS", acc_ipns), cbind(label = "STCR-NPK", acc_npk), s %>% group_by(Trt, short) %>% summarise(n = n(), ach_mean = mean(ach), ach_min = min(ach), ach_max = max(ach), bias = mean(err), rmse = sqrt(mean(err^2)), mape = mean(abs(err) / Target_kg_ha * 100), .groups = "drop") %>% mutate(label = as.character(short)) %>% select(label, n, ach_mean, ach_min, ach_max, bias, rmse, mape)) write.csv(acc_rows, file.path(OUT, "tables", "accuracy.csv"), row.names = FALSE) cat("\n== ACCURACY ==\n"); print(acc_rows %>% mutate(across(where(is.numeric), ~ rnd(.x, 2)))) cat("bias^2 / MSE =", rnd(acc_all$bias^2 / acc_all$rmse^2, 3), "\n") ## by farm cat("Farm-wise achievement (mean):\n"); print(s %>% group_by(Farm) %>% summarise(ach = mean(ach), bias = mean(err), rmse = sqrt(mean(err^2)))) ## regression obs ~ target + IPNS fit <- lm(Yield_kg_ha ~ I(Target_kg_ha/1000) + I(group == "STCR-IPNS"), data = s) cat("\nRegression: "); print(round(coef(fit), 1)); cat("R2 =", rnd(summary(fit)$r.squared, 3), " resid SD =", rnd(summary(fit)$sigma, 0), "\n") fit_ci <- confint(fit); print(round(fit_ci, 1)) J$reg <- list(b0 = unname(coef(fit)[1]), b_t = unname(coef(fit)[2]), b_ipns = unname(coef(fit)[3]), r2 = summary(fit)$r.squared) ## matched-pair differences IPNS - NPK mp <- s %>% select(Farm, target, group, Yield_kg_ha, ach, F_applied_total, Uptake_N, Uptake_P, Uptake_K, BCR_reported, RR_F, RR_T) %>% pivot_wider(names_from = group, values_from = c(Yield_kg_ha, ach, F_applied_total, Uptake_N, Uptake_P, Uptake_K, BCR_reported, RR_F, RR_T)) mp <- mp %>% mutate(dY = 100 * (`Yield_kg_ha_STCR-IPNS` / `Yield_kg_ha_STCR-NPK` - 1), dAch = `ach_STCR-IPNS` - `ach_STCR-NPK`, dF = 100 * (`F_applied_total_STCR-IPNS` / `F_applied_total_STCR-NPK` - 1), dN = 100 * (`Uptake_N_STCR-IPNS` / `Uptake_N_STCR-NPK` - 1), dP = 100 * (`Uptake_P_STCR-IPNS` / `Uptake_P_STCR-NPK` - 1), dK = 100 * (`Uptake_K_STCR-IPNS` / `Uptake_K_STCR-NPK` - 1), dB = 100 * (`BCR_reported_STCR-IPNS` / `BCR_reported_STCR-NPK` - 1)) cat("\n== matched pairs (IPNS vs NPK) ==\n"); print(mp %>% select(Farm, target, dY, dAch, dF, dN, dP, dK, dB) %>% mutate(across(where(is.numeric), ~ rnd(.x, 2)))) pp <- d %>% group_by(Trt, short, group, target) %>% summarise(across(c(Yield_kg_ha, F_applied_total, Uptake_N, Uptake_P, Uptake_K, BCR_reported, RR_F, RR_T, ach), mean), .groups = "drop") for (tg in c(3.0, 3.5, 4.0)) { a <- filter(pp, group == "STCR-IPNS", target == tg); n <- filter(pp, group == "STCR-NPK", target == tg) cat(sprintf("target %.1f pooled: yield %+.2f%%, fert %+.1f%%, N up %+.2f%%, P up %+.2f%%, K up %+.2f%%, BCR %+.2f%%, ach diff %+.2f pp\n", tg, 100*(a$Yield_kg_ha/n$Yield_kg_ha-1), 100*(a$F_applied_total/n$F_applied_total-1), 100*(a$Uptake_N/n$Uptake_N-1), 100*(a$Uptake_P/n$Uptake_P-1), 100*(a$Uptake_K/n$Uptake_K-1), 100*(a$BCR_reported/n$BCR_reported-1), a$ach-n$ach)) } ## yield vs comparators (T8) p8 <- pp$Yield_kg_ha[pp$Trt == "T8"] cat("\nT8 vs T10/T2/T1/T9/T5 (%):", paste(sapply(c("T10","T2","T1","T9","T5"), function(k) rnd(100*(p8/pp$Yield_kg_ha[pp$Trt==k]-1),1)), collapse=" / "), "\n") ## ---------- B. realised nutrient requirement ---------- nr <- d %>% group_by(Trt, short) %>% summarise(N = mean(NR_N), P2O5 = mean(NR_P2O5), K2O = mean(NR_K2O), .groups = "drop") cat("\n== realised NR (kg per t grain), pooled by treatment ==\n"); print(nr %>% mutate(across(where(is.numeric), ~ rnd(.x, 1)))) cat("range across all 20 rows: N", paste(rnd(range(d$NR_N),1),collapse="-"), " P2O5", paste(rnd(range(d$NR_P2O5),1),collapse="-"), " K2O", paste(rnd(range(d$NR_K2O),1),collapse="-"), "\n") cat("range across STCR rows (12): N", paste(rnd(range(s$NR_N),1),collapse="-"), " P2O5", paste(rnd(range(s$NR_P2O5),1),collapse="-"), " K2O", paste(rnd(range(s$NR_K2O),1),collapse="-"), "\n") cat("mean ratio realised/calibrated (all 20): N", rnd(mean(d$NR_N)/NR["N"],3), " P2O5", rnd(mean(d$NR_P2O5)/NR["P2O5"],3), " K2O", rnd(mean(d$NR_K2O)/NR["K2O"],3), "\n") cat("mean ratio realised/calibrated (12 STCR): N", rnd(mean(s$NR_N)/NR["N"],3), " P2O5", rnd(mean(s$NR_P2O5)/NR["P2O5"],3), " K2O", rnd(mean(s$NR_K2O)/NR["K2O"],3), "\n") cat("control: N", rnd(mean(d$NR_N[d$Trt=="T10"]),1), " P2O5", rnd(mean(d$NR_P2O5[d$Trt=="T10"]),1), " K2O", rnd(mean(d$NR_K2O[d$Trt=="T10"]),1), "\n") cat("P2O5 NR in fertilised plots (non-control) range:", paste(rnd(range(d$NR_P2O5[d$Trt!="T10"]),1), collapse="-"), "\n") ## uptake shares sh <- d %>% mutate(tot = Uptake_N + Uptake_P*2.29 + Uptake_K*1.21, sN = 100*Uptake_N/tot, sP = 100*Uptake_P*2.29/tot, sK = 100*Uptake_K*1.21/tot) ref_sh <- 100 * NR / sum(NR); cat("calibrated NR shares N:P2O5:K2O =", paste(rnd(ref_sh,1), collapse=":"), "\n") cat("uptake shares range N", paste(rnd(range(sh$sN),1),collapse="-"), " P2O5", paste(rnd(range(sh$sP),1),collapse="-"), " K2O", paste(rnd(range(sh$sK),1),collapse="-"), "\n") print(sh %>% group_by(short) %>% summarise(sN = mean(sN), sP = mean(sP), sK = mean(sK)) %>% mutate(across(where(is.numeric), ~ rnd(.x, 1)))) ## ---------- C. PCA ---------- traits <- c("Yield_kg_ha", "Uptake_N", "Uptake_P", "Uptake_K", "PlantHeight", "LAI", "Tillers_m2", "RootLength", "Fingers", "EarheadLength", "EarheadWeight", "TestWeight", "SCMR", "LeafN_mg_g", "LeafMoisture_pct") tl <- c(Yield_kg_ha = "Grain yield", Uptake_N = "N uptake", Uptake_P = "P uptake", Uptake_K = "K uptake", PlantHeight = "Plant height", LAI = "LAI", Tillers_m2 = "Tillers", RootLength = "Root length", Fingers = "Fingers", EarheadLength = "Earhead length", EarheadWeight = "Earhead weight", TestWeight = "Test weight", SCMR = "SPAD", LeafN_mg_g = "Leaf N", LeafMoisture_pct = "Leaf moisture") Z <- d[, traits] for (loc in unique(d$Location)) { i <- d$Location == loc; Z[i, ] <- scale(d[i, traits]) } rownames(Z) <- paste(d$Trt, substr(d$Farm, 1, 1), sep = "_") pc <- PCA(Z, scale.unit = TRUE, graph = FALSE, ncp = 15) ev <- pc$eig[, 1]; pv <- pc$eig[, 2] set.seed(123); n <- nrow(Z); p <- ncol(Z) sim <- replicate(1000, eigen(cor(matrix(rnorm(n * p), n, p)), only.values = TRUE)$values) thr <- apply(sim, 1, quantile, 0.95) cat("\n== PCA ==\neig:", paste(rnd(ev[1:4], 3), collapse = ", "), "| %:", paste(rnd(pv[1:4], 2), collapse = ", "), "| cum PC1-2:", rnd(pc$eig[2, 3], 2), "\n") cat("parallel thresholds PC1-4:", paste(rnd(thr[1:4], 2), collapse = ", "), "\n") ld <- pc$var$cor[, 1:2]; cat("PC1 correlations range:", paste(rnd(range(ld[, 1]), 3), collapse = " to "), " | lowest:", names(which.min(ld[, 1])), rnd(min(ld[, 1]), 3), "\n") cat("PC2 correlations: SCMR", rnd(ld["SCMR", 2], 3), " Leaf moisture", rnd(ld["LeafMoisture_pct", 2], 3), " Root length", rnd(ld["RootLength", 2], 3), "\n") cat("PC2 loadings range:", paste(rnd(range(ld[, 2]), 3), collapse = " to "), "\n") sc <- pc$ind$coord[, 1:2]; scd <- cbind(d[, c("Trt", "short", "group", "Farm", "F_applied_total", "FYM_t_ha")], PC1 = sc[, 1], PC2 = sc[, 2]) fa <- scd %>% select(Trt, Farm, PC1) %>% pivot_wider(names_from = Farm, values_from = PC1) cat("PC1 farm agreement r =", rnd(cor(fa$Ayyakannur, fa$Palayam), 5), "\n") rk <- scd %>% group_by(Trt, short) %>% summarise(PC1 = mean(PC1), .groups = "drop") %>% arrange(PC1) cat("PC1 ranking (low->high):\n"); print(rk %>% mutate(PC1 = rnd(PC1, 2))) cat("PC1 range of scores:", paste(rnd(range(sc[,1]),2), collapse=" to "), " | SD PC1:", rnd(sd(sc[,1]),2), " SD PC2:", rnd(sd(sc[,2]),2), "\n") cat("contribution to PC1 (top 3):", paste(names(sort(pc$var$contrib[,1], decreasing=TRUE))[1:3], collapse=", "), "\n") ## supplementary correlations with PC scores supp <- list(F_applied = d$F_applied_total, BCR = d$BCR_reported, RR_F = d$RR_F, RR_T = d$RR_T, FYM_t = d$FYM_t_ha) sup_cor <- t(sapply(supp, function(v) c(PC1 = cor(v, sc[, 1], use = "complete.obs"), PC2 = cor(v, sc[, 2], use = "complete.obs")))) cat("\nSupplementary variable correlations with PC1/PC2:\n"); print(round(sup_cor, 3)) ## frontier: PC1 vs fertiliser for fertiliser-only treatments fo <- scd %>% filter(Trt %in% c("T1", "T3", "T4", "T5", "T9", "T10")) fq <- lm(PC1 ~ F_applied_total + I(F_applied_total^2), data = fo) cat("\nFrontier quadratic fit R2 =", rnd(summary(fq)$r.squared, 3), "\n") ip <- scd %>% filter(Trt %in% c("T2", "T6", "T7", "T8")) %>% mutate(pred = predict(fq, newdata = data.frame(F_applied_total = F_applied_total)), gap = PC1 - pred) print(ip %>% select(Trt, Farm, F_applied_total, PC1, pred, gap) %>% mutate(across(where(is.numeric), ~ rnd(.x, 2)))) ## clustering of treatment profiles zt <- as.data.frame(Z) %>% mutate(Trt = d$Trt) %>% group_by(Trt) %>% summarise(across(everything(), mean)) %>% as.data.frame() rownames(zt) <- trt$short[match(zt$Trt, trt$Trt)]; zt$Trt <- NULL hc <- hclust(dist(as.matrix(zt)), method = "average") cat("\nCluster order:", paste(hc$labels[hc$order], collapse = " | "), "\n") cl2 <- cutree(hc, 2); cl3 <- cutree(hc, 3); cat("k=2:\n"); print(split(names(cl2), cl2)); cat("k=3:\n"); print(split(names(cl3), cl3)) hcc <- hclust(dist(t(as.matrix(zt))), method = "average"); cat("trait clusters k=2:\n"); print(split(names(cutree(hcc, 2)), cutree(hcc, 2))) cat("corr of traits: min pairwise r =", rnd(min(cor(Z)), 3), "\n") ## ---------- D. dose tables ---------- Sref <- c(N = 260, P2O5 = 22, K2O = 280) dt <- do.call(rbind, lapply(c(0, 6.25, 12.5), function(fy) do.call(rbind, lapply(c(3.0, 3.5, 4.0), function(T) { O <- fym_elem(fy, FYM_REF); r <- dose(T, Sref, O) data.frame(FYM = fy, T = T, N_raw = r$raw[1], P_raw = r$raw[2], K_raw = r$raw[3], N = r$final[1], P = r$final[2], K = r$final[3], N_flag = ifelse(r$raw[1] < LO[1], "floor", ifelse(r$raw[1] > HI[1], "cap", "")), P_flag = ifelse(r$raw[2] < LO[2], "floor", ifelse(r$raw[2] > HI[2], "cap", "")), K_flag = ifelse(r$raw[3] < LO[3], "floor", ifelse(r$raw[3] > HI[3], "cap", ""))) })))) write.csv(dt, file.path(OUT, "tables", "dose_reference.csv"), row.names = FALSE) cat("\n== reference-soil doses ==\n"); print(dt %>% mutate(across(where(is.numeric), ~ rnd(.x, 1)))) base0 <- dt %>% filter(FYM == 0) %>% select(T, N0 = N, P0 = P, K0 = K) red <- dt %>% filter(FYM > 0) %>% left_join(base0, by = "T") %>% mutate(rN = 100*(1-N/N0), rP = 100*(1-P/P0), rK = 100*(1-K/K0), rTot = 100*(1-(N+P+K)/(N0+P0+K0))) cat("\nReductions vs NPK alone (%):\n"); print(red %>% select(FYM, T, rN, rP, rK, rTot) %>% mutate(across(where(is.numeric), ~ rnd(.x, 1)))) crit <- do.call(rbind, lapply(c(0, 6.25, 12.5), function(fy) do.call(rbind, lapply(c(3.0, 3.5, 4.0), function(T) { O <- fym_elem(fy, FYM_REF); cs <- (A_T * T - B_O * O) / B_S; data.frame(FYM = fy, T = T, N = cs[1], P = cs[2], K = cs[3]) })))) write.csv(crit, file.path(OUT, "tables", "critical_values.csv"), row.names = FALSE) cat("\ncritical soil test values:\n"); print(crit %>% mutate(across(where(is.numeric), ~ rnd(.x, 0)))) cat("\nFYM credit at 12.5 t (ref comp), fert-equivalent N/P2O5/K2O:", paste(rnd(B_O * fym_elem(12.5, FYM_REF), 1), collapse = " / "), " total", rnd(sum(B_O * fym_elem(12.5, FYM_REF)),1), "\n") cat("FYM credit at 12.5 t (validation comp):", paste(rnd(B_O * fym_elem(12.5, FYM_VAL), 1), collapse = " / "), " total", rnd(sum(B_O * fym_elem(12.5, FYM_VAL)),1), "\n") ## ---------- E. pooled validation + traits tables ---------- vt <- d %>% group_by(Trt, short, long, group, letter) %>% summarise(yield = mean(Yield_kg_ha), yA = Yield_kg_ha[Farm == "Ayyakannur"], yP = Yield_kg_ha[Farm == "Palayam"], achA = ach[Farm == "Ayyakannur"], achP = ach[Farm == "Palayam"], ach = mean(ach), RR_F = mean(RR_F), RR_T = mean(RR_T), BCR = mean(BCR_reported), bA = BCR_reported[Farm == "Ayyakannur"], bP = BCR_reported[Farm == "Palayam"], F = mean(F_applied_total), .groups = "drop") write.csv(vt, file.path(OUT, "tables", "validation_pooled.csv"), row.names = FALSE) cat("\n== pooled validation ==\n"); print(vt %>% select(Trt, yield, ach, RR_F, RR_T, BCR, F) %>% mutate(across(where(is.numeric), ~ rnd(.x, 2)))) cat("\nnames in CSV:\n"); print(names(d)) saveRDS(list(pc = pc, scd = scd, thr = thr, ev = ev, pv = pv, sup_cor = sup_cor, fq = fq, zt = zt, hc = hc, sh = sh, ref_sh = ref_sh, tl = tl, traits = traits, Z = Z), file.path(OUT, "tables", "pca_objects.rds")) write.csv(data.frame(trait = names(tl), label = tl, PC1 = ld[, 1], PC2 = ld[, 2], contrib1 = pc$var$contrib[, 1]), file.path(OUT, "tables", "pca_loadings.csv"), row.names = FALSE) write.csv(scd, file.path(OUT, "tables", "pca_scores.csv"), row.names = FALSE) ## ###################################################################### ## 02_tables.R ## ###################################################################### ## 02_tables.R - manuscript tables (CSV/JSON) from the validation dataset cat("columns:", paste(names(d), collapse = ", "), "\n") ## Table 6: validation app <- function(i) paste0(fmt(d$N_applied[i], 0), ":", fmt(d$P2O5_applied[i], 0), ":", fmt(d$K2O_applied[i], 0)) d$applied <- sapply(seq_len(nrow(d)), app) t6 <- d %>% group_by(Trt, short, long) %>% summarise( applied = paste(applied[Farm == "Ayyakannur"], applied[Farm == "Palayam"], sep = " / "), FYM = FYM_t_ha[1], yield = rnd(mean(Yield_kg_ha), 0), ach = ifelse(is.na(Target_kg_ha[1]), "-", paste(fmt(ach[Farm == "Ayyakannur"], 1), fmt(ach[Farm == "Palayam"], 1), fmt(mean(ach), 1), sep = " / ")), RR_F = ifelse(all(is.na(RR_F)), "-", fmt(mean(RR_F), 2)), RR_T = ifelse(all(is.na(RR_T)), "-", fmt(mean(RR_T), 2)), BCR = fmt(mean(BCR_reported), 2), .groups = "drop") %>% left_join(trt[, c("Trt", "letter")], by = "Trt") t6$Trt <- factor(t6$Trt, levels = paste0("T", 1:10)); t6 <- t6[order(t6$Trt), ] write.csv(t6, file.path(OUT, "tables", "table6_validation.csv"), row.names = FALSE) print(as.data.frame(t6)) ## Table 7: traits (mean of two farms) t7 <- d %>% group_by(Trt, short) %>% summarise(PH = mean(PlantHeight), TIL = mean(Tillers_m2), FING = mean(Fingers), EW = mean(EarheadWeight), SPAD = mean(SCMR), LN = mean(LeafN_mg_g), UN = mean(Uptake_N), UP = mean(Uptake_P), UK = mean(Uptake_K), LAI = mean(LAI), TW = mean(TestWeight), .groups = "drop") t7$Trt <- factor(t7$Trt, levels = paste0("T", 1:10)); t7 <- t7[order(t7$Trt), ] write.csv(t7, file.path(OUT, "tables", "table7_traits.csv"), row.names = FALSE) draft <- rbind( c(81.5,92.5,8.5,8.8,24.0,16.5,62.6,10.3,56.7), c(84.0,98.9,9.3,9.7,25.5,18.5,71.2,13.1,64.1), c(84.2,94.6,8.7,8.9,24.6,17.4,68.4,11.7,60.5), c(87.6,102.2,9.5,10.2,26.2,18.9,75.8,14.0,67.3), c(90.8,111.1,10.1,11.5,28.9,20.2,82.5,16.8,76.7), c(86.1,97.6,8.9,9.4,25.2,18.1,70.4,12.5,62.3), c(89.1,107.8,9.9,10.9,27.7,19.8,77.7,15.0,70.6), c(91.1,116.7,11.0,12.5,30.9,20.8,86.4,17.8,82.6), c(79.4,87.5,7.8,8.5,23.6,15.8,58.5,9.5,53.4), c(69.0,78.3,6.4,7.2,23.1,14.1,46.7,6.3,47.3)) mine <- as.matrix(t7[, c("PH", "TIL", "FING", "EW", "SPAD", "LN", "UN", "UP", "UK")]) diff <- abs(rnd(mine, 1) - draft) cat("\nmax abs difference to draft Table 5:", max(diff), "\n"); if (max(diff) > 0.051) print(which(diff > 0.051, arr.ind = TRUE)) cat("LAI/TW pooled ranges:", paste(rnd(range(t7$LAI), 2), collapse = "-"), "|", paste(rnd(range(t7$TW), 2), collapse = "-"), "\n") ## Table 1 (site properties) and a compact JSON bundle write_json(list(t6 = t6, t7 = t7, acc = read.csv(file.path(OUT, "tables", "accuracy.csv")), dose = read.csv(file.path(OUT, "tables", "dose_reference.csv")), crit = read.csv(file.path(OUT, "tables", "critical_values.csv"))), file.path(OUT, "tables", "tables.json"), digits = 6, auto_unbox = TRUE, na = "null") cat("tables.json written\n") ## ###################################################################### ## fig01_map.R ## ###################################################################### ## Fig. 1 - study area (GIS, R/sf): India > Tamil Nadu > Dindigul, sites, soil-test position sf_use_s2(FALSE); CRS <- 7755 G <- file.path(BASE, "gis") dist <- st_make_valid(st_read(file.path(G, "2011_Dist.shp"), quiet = TRUE)) sts <- st_make_valid(st_read(file.path(G, "states_Admin2.shp"), quiet = TRUE)) dist_p <- st_transform(dist, CRS); sts_p <- st_transform(sts, CRS) tn <- dist_p[grepl("Tamil", dist_p$ST_NM, ignore.case = TRUE), ] dg <- tn[tn$DISTRICT == "Dindigul", ] nb <- tn[lengths(st_touches(tn, dg)) > 0, ] sts_s <- st_simplify(sts_p, dTolerance = 4000, preserveTopology = TRUE) tn_state <- sts_s[grepl("Tamil", sts_s$ST_NM, ignore.case = TRUE), ] ## ---- site layer (WGS 84): exact coordinates only where the draft gives valid ones ---- pts_ll <- st_sf( site = c("Thoppupatti", "Guziliamparai block"), kind = c("Calibration (Phases I-II)", "Validation farms (Phase III)"), note = c("10 deg 34'49\" N, 78 deg 04'35\" E (as reported)", "approximate block-level position (Guziliamparai); replace with farm GPS"), geometry = st_sfc(st_point(c(78.07639, 10.58028)), st_point(c(78.1107, 10.6799)), crs = 4326)) st_write(pts_ll, file.path(OUT, "gis", "study_sites.gpkg"), layer = "study_sites", delete_dsn = TRUE, quiet = TRUE) st_write(st_transform(dg, 4326)[, c("DISTRICT", "ST_NM")], file.path(OUT, "gis", "study_sites.gpkg"), layer = "dindigul_district", append = TRUE, quiet = TRUE) pts <- st_transform(pts_ll, CRS) city <- st_transform(st_sfc(st_point(c(77.9803, 10.3673)), crs = 4326), CRS) cat("validation point inside Dindigul:", lengths(st_within(pts_ll[2, ], st_transform(dg, 4326)))[1] > 0, " | Thoppupatti inside:", lengths(st_within(pts_ll[1, ], st_transform(dg, 4326)))[1] > 0, "\n") cat("distance Thoppupatti - validation marker (km):", round(as.numeric(st_distance(pts[1, ], pts[2, ])) / 1000, 1), "\n") GRN <- "#009E73"; ORG <- "#D55E00" base_theme <- theme_void(base_family = FAM, base_size = 8) + theme(panel.border = element_rect(colour = "grey35", fill = NA, linewidth = 0.4), plot.margin = margin(2, 2, 2, 2)) ## (a) India pa <- ggplot() + geom_sf(data = sts_s, fill = "#E4E4E4", colour = "white", linewidth = 0.12) + geom_sf(data = tn_state, fill = "#7FC4A9", colour = "white", linewidth = 0.15) + annotate("text", x = 3.95e6, y = 3.55e6, label = "INDIA", family = FAM, size = 2.6, colour = "grey40", fontface = "bold") + annotate("text", x = 3.60e6, y = 2.05e6, label = "Tamil Nadu", family = FAM, size = 2.3, colour = "#146B4F", fontface = "italic", hjust = 1) + coord_sf(crs = CRS, datum = NA, expand = TRUE) + base_theme ## (b) Tamil Nadu bb_c <- unlist(lapply(st_bbox(dg), as.numeric)); names(bb_c) <- c("xmin","ymin","xmax","ymax"); mx <- 9000 box_c <- st_as_sfc(st_bbox(c(xmin = bb_c[["xmin"]] - 22000, ymin = bb_c[["ymin"]] - 22000, xmax = bb_c[["xmax"]] + 22000, ymax = bb_c[["ymax"]] + 22000), crs = st_crs(dg))) pb <- ggplot() + geom_sf(data = tn, fill = "#EFEFEF", colour = "grey60", linewidth = 0.15) + geom_sf(data = dg, fill = "#7FC4A9", colour = "grey25", linewidth = 0.3) + geom_sf(data = box_c, fill = NA, colour = ORG, linewidth = 0.5) + annotate("text", x = st_coordinates(st_centroid(dg))[1] - 40000, y = st_coordinates(st_centroid(dg))[2] - 70000, label = "Dindigul", family = FAM, size = 2.5, fontface = "bold", hjust = 1) + coord_sf(crs = CRS, datum = NA, expand = TRUE) + base_theme ## (c) Dindigul district mx <- 22000 xl <- c(bb_c[["xmin"]] - mx, bb_c[["xmax"]] + mx); yl <- c(bb_c[["ymin"]] - mx, bb_c[["ymax"]] + mx) W <- diff(xl); H <- diff(yl) panel_box <- st_as_sfc(st_bbox(c(xmin = xl[1] + 3000, ymin = yl[1] + 3000, xmax = xl[2] - 3000, ymax = yl[2] - 3000), crs = st_crs(dg))) nb_only <- nb[nb$DISTRICT != "Dindigul", ] nb_clip <- suppressWarnings(st_intersection(st_make_valid(nb_only), panel_box)) nb_lab <- suppressWarnings(st_point_on_surface(nb_clip)); nb_lab$x <- st_coordinates(nb_lab)[, 1]; nb_lab$y <- st_coordinates(nb_lab)[, 2] dg_lab <- suppressWarnings(st_point_on_surface(dg)); dgx <- st_coordinates(dg_lab) sbx <- xl[1] + 0.05 * W; sby <- yl[1] + 0.07 * H nax <- xl[2] - 0.06 * W; nay <- yl[1] + 0.09 * H xT <- st_coordinates(pts[1, ])[1]; yT <- st_coordinates(pts[1, ])[2] xV <- st_coordinates(pts[2, ])[1]; yV <- st_coordinates(pts[2, ])[2] pc <- ggplot() + geom_sf(data = nb, fill = "#F1F1F1", colour = "grey60", linewidth = 0.25) + geom_sf(data = dg, fill = "#CFE9DD", colour = "grey20", linewidth = 0.45) + geom_sf(data = st_buffer(pts[2, ], 5000), fill = NA, colour = ORG, linetype = "22", linewidth = 0.45) + geom_sf(data = city, shape = 22, size = 2.2, fill = "white", colour = "grey15", stroke = 0.6) + geom_sf(data = pts[1, ], shape = 21, size = 3.4, fill = GRN, colour = "black", stroke = 0.6) + geom_sf(data = pts[2, ], shape = 24, size = 3.4, fill = ORG, colour = "black", stroke = 0.6) + geom_text(data = st_drop_geometry(nb_lab), aes(x, y, label = DISTRICT), family = FAM, size = 2.5, colour = "grey45", fontface = "italic") + annotate("text", x = dgx[1] - 30000, y = dgx[2] - 18000, label = "DINDIGUL DISTRICT", family = FAM, size = 2.8, fontface = "bold", colour = "grey20") + annotate("text", x = st_coordinates(city)[1] + 3500, y = st_coordinates(city)[2] - 5500, label = "Dindigul", family = FAM, size = 2.3, hjust = 0, colour = "grey15") + annotate("label", x = xT - 6500, y = yT - 3500, hjust = 1, vjust = 0.5, family = FAM, size = 2.45, label.size = 0.2, fill = "white", colour = "black", label = "Thoppupatti, Vedasandur block\nPhases I-II (calibration)") + annotate("label", x = xV - 7000, y = yV + 9000, hjust = 1, vjust = 0, family = FAM, size = 2.45, label.size = 0.2, fill = "white", colour = "black", label = "Ayyakannur and Palayam, Guziliamparai block\nPhase III (validation; approximate position)") + annotate("segment", x = xV - 7000, xend = xV - 2500, y = yV + 9000, yend = yV + 3000, linewidth = 0.3, colour = "grey20") + ## scale bar and north arrow annotate("segment", x = sbx, xend = sbx + 20000, y = sby, yend = sby, linewidth = 1.2, colour = "black") + annotate("segment", x = c(sbx, sbx + 10000, sbx + 20000), xend = c(sbx, sbx + 10000, sbx + 20000), y = sby - 1500, yend = sby + 1800, linewidth = 0.4) + annotate("text", x = c(sbx, sbx + 10000, sbx + 20000), y = sby + 5200, label = c("0", "10", "20 km"), family = FAM, size = 2.2) + annotate("segment", x = nax, xend = nax, y = nay, yend = nay + 14000, linewidth = 0.6, arrow = arrow(length = unit(2.2, "mm"), type = "closed")) + annotate("text", x = nax, y = nay + 19500, label = "N", family = FAM, size = 3, fontface = "bold") + scale_x_continuous(breaks = seq(77.2, 78.6, 0.2), labels = function(x) paste0(x, "\u00B0E")) + scale_y_continuous(breaks = seq(10.0, 10.8, 0.2), labels = function(x) paste0(x, "\u00B0N")) + coord_sf(crs = CRS, xlim = xl, ylim = yl, expand = FALSE, datum = st_crs(4326)) + theme_bw(base_family = FAM, base_size = 7.5) + theme(panel.grid.major = element_line(colour = "grey88", linewidth = 0.2), panel.border = element_rect(colour = "grey35", fill = NA, linewidth = 0.4), axis.title = element_blank(), axis.text = element_text(colour = "grey25", size = 6.5), plot.margin = margin(2, 3, 2, 2)) ## legend strip made from a dummy plot leg_df <- data.frame(x = 1:3, y = 1, lab = c("Calibration site (Phases I-II)", "Validation farms (Phase III)", "Dindigul city"), k = c("a", "b", "c")) ## (d) soil-test position of sites relative to the calibrated range rng <- data.frame(var = factor(c("N", "P", "K"), levels = c("N", "P", "K")), lo = RANGE$lo, hi = RANGE$hi) sp <- sites %>% pivot_longer(c(SN, SP, SK), names_to = "v", values_to = "val") %>% mutate(var = factor(recode(v, SN = "N", SP = "P", SK = "K"), levels = c("N", "P", "K")), type = ifelse(site == "Thoppupatti", "Calibration site", "Validation farm")) labs_f <- c(N = "KMnO[4]*'-N (kg ha'^-1*')'", P = "'Olsen-P (kg ha'^-1*')'", K = "NH[4]*'OAc-K (kg ha'^-1*')'") pd <- ggplot() + geom_rect(data = rng, aes(xmin = lo, xmax = hi, ymin = 0.62, ymax = 1.38), fill = "grey84", colour = "grey40", linewidth = 0.3) + geom_text(data = data.frame(var = factor("N", levels = c("N", "P", "K")), x = 224, label = "calibrated range"), aes(x, 0.46, label = label), family = FAM, size = 2.2, colour = "grey30") + geom_point(data = sp, aes(val, 1, shape = type, fill = type), size = 2.8, colour = "black", stroke = 0.5) + geom_text_repel(data = sp, aes(val, 1, label = short), nudge_y = 0.33, size = 2.6, family = FAM, fontface = "bold", segment.size = 0.2, min.segment.length = 0.1, box.padding = 0.15, direction = "x") + facet_wrap(~var, scales = "free_x", labeller = as_labeller(labs_f, label_parsed)) + scale_shape_manual(values = c("Calibration site" = 21, "Validation farm" = 24), name = NULL) + scale_fill_manual(values = c("Calibration site" = GRN, "Validation farm" = "#E69F00"), name = NULL) + scale_y_continuous(limits = c(0.38, 1.85)) + scale_x_continuous(expand = expansion(mult = 0.08)) + labs(x = NULL, y = NULL) + theme_ms(7.5) + theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(), panel.grid.major.y = element_blank(), legend.position = "bottom", legend.margin = margin(0, 0, 0, 0), legend.box.margin = margin(-4, 0, 0, 0)) fig <- ((pa / pb) | pc) / pd + plot_layout(heights = c(1, 0.25)) + tagit() fig <- ((pa / pb) | pc) + plot_layout(widths = c(0.36, 0.64)) fig <- (fig / pd) + plot_layout(heights = c(1, 0.27)) + plot_annotation(tag_levels = list(c("a", "b", "c", "d")), tag_prefix = "(", tag_suffix = ")") save_fig(fig, "Fig1_study_area", 6.6, 6.5) cat("Fig1 done\n") ## ###################################################################### ## fig02_design.R ## ###################################################################### ## Fig. 2 - experimental timeline and workflow D <- as.Date bars <- data.frame( y = c(4, 3, 2, 2, 1, 1), x0 = D(c("2021-12-24", "2022-04-04", "2022-12-10", "2023-01-07", "2023-01-19", "2023-02-14")), x1 = D(c("2022-02-28", "2022-08-10", "2023-01-07", "2023-04-04", "2023-02-14", "2023-05-15")), col = c("#8C8C8C", "#009E73", "#E69F00", "#E69F00", "#D55E00", "#D55E00"), al = c(1, 1, 0.38, 1, 0.38, 1)) ylab <- c("4" = "Phase I gradient crop\nfodder sorghum CO 30", "3" = "Phase II test crop\nfinger millet ATL 1, 72 plots", "2" = "Phase III validation\nAyyakannur", "1" = "Phase III validation\nPalayam") lab <- data.frame( x = D(c("2021-12-20", "2022-03-04", "2022-03-30", "2022-08-16", "2022-12-04", "2023-01-07", "2023-04-10", "2023-01-13", "2023-02-14", "2023-05-21")), y = c(4, 4, 3, 3, 2, 2, 2, 1, 1, 1), txt = c("24 Dec 2021", "28 Feb 2022", "4 Apr 2022", "10 Aug 2022", "sown 10 Dec 2022", "transplanted 7 Jan 2023", "harvest 4 Apr 2023", "sown 19 Jan 2023", "transplanted 14 Feb 2023", "harvest 15 May 2023"), hj = c(1, 0, 1, 0, 1, 0.5, 0, 1, 0.5, 0)) lab$yy <- ifelse(lab$txt %in% c("transplanted 7 Jan 2023", "transplanted 14 Feb 2023"), lab$y - 0.38, lab$y) lab$yy[lab$txt == "harvest 15 May 2023"] <- 1.38; lab$x[lab$txt == "harvest 15 May 2023"] <- D("2023-05-15"); lab$hj[lab$txt == "harvest 15 May 2023"] <- 1 pa <- ggplot() + geom_segment(data = bars, aes(x = x0, xend = x1, y = y, yend = y, colour = col, alpha = al), linewidth = 6.5, lineend = "butt") + scale_colour_identity() + scale_alpha_identity() + geom_text(data = lab, aes(x = x, y = yy, label = txt, hjust = hj), family = FAM, size = 2.35, vjust = 0.5) + geom_point(data = data.frame(x = D(c("2023-01-07", "2023-02-14")), y = c(2, 1)), aes(x, y), shape = 25, size = 2.2, fill = "white", colour = "black", stroke = 0.5) + annotate("text", x = D(c("2022-12-24", "2023-01-31")), y = c(2.36, 1.36), label = "nursery", family = FAM, size = 2.0, colour = "grey30") + scale_y_continuous(breaks = 1:4, labels = ylab[as.character(1:4)], limits = c(0.45, 4.4), expand = c(0, 0)) + scale_x_date(limits = D(c("2021-10-01", "2023-09-20")), date_breaks = "2 months", date_labels = "%b\n%Y", expand = c(0, 0)) + labs(x = NULL, y = NULL) + theme_ms(7.5) + theme(panel.grid.major.y = element_blank(), axis.text.y = element_text(hjust = 0, lineheight = 0.95), axis.text.x = element_text(size = 6.5)) bx <- data.frame( x0 = c(1, 35.5, 70, 70, 35.5, 1), y0 = c(53, 53, 53, 0, 0, 0), w = 29, h = 46, fill = c("#E6E6E6", "#CDEBDD", "#D6E6F4", "#D6E6F4", "#FBE3B8", "#E7DDF0"), title = c("1 Phase I: fertility gradient", "2 Phase II: test crop", "3 Basic parameters", "4 Prescription equations", "5 Phase III: validation", "6 Evaluation"), body = c("Fodder sorghum CO 30 on 3 strips\n(600 m\u00B2 each) with graded NPK:\nlow, medium and high fertility", "Finger millet ATL 1, 24 treatments\nper strip, FYM 0, 6.25, 12.5 t/ha;\n72 plots of 25 m\u00B2", "NR: uptake per tonne of grain\nCs, Cf, Cfym: share of uptake\nfrom soil, fertiliser and FYM", "Dose equations for N, P and K,\nNPK alone and IPNS; limits at\n50% and 150% of blanket 60:30:30", "2 farms, RBD, 3 replications,\n10 treatments; targets of\n3.0, 3.5 and 4.0 t/ha", "Achievement, bias, RMSE, RR, BCR;\nPCA and clustering in R;\nGIS mapping with sf")) bx$x1 <- bx$x0 + bx$w; bx$y1 <- bx$y0 + bx$h pb <- ggplot(bx) + geom_rect(aes(xmin = x0, xmax = x1, ymin = y0, ymax = y1), fill = bx$fill, colour = "grey30", linewidth = 0.35) + geom_text(aes(x = x0 + w / 2, y = y1 - 9, label = title), family = FAM, size = 2.8, fontface = "bold") + geom_text(aes(x = x0 + w / 2, y = y0 + 15, label = body), family = FAM, size = 2.45, lineheight = 1.0) + annotate("segment", x = c(30.3, 64.8, 69.7, 35.2), xend = c(35.2, 69.7, 64.8, 30.3), y = c(76, 76, 23, 23), yend = c(76, 76, 23, 23), arrow = arrow(length = unit(1.6, "mm"), type = "closed"), linewidth = 0.45) + coord_cartesian(xlim = c(0, 100), ylim = c(-1, 109), expand = FALSE) + theme_void(base_family = FAM) + theme(plot.tag = element_text(face = "bold", size = 10, family = FAM)) ## the order of boxes is 1 -> 2 -> 3 (top row, left to right), then 4 <- 3 (down), 5 <- 4, 6 <- 5 (bottom row, right to left) pb <- pb + annotate("segment", x = 84.5, xend = 84.5, y = 53, yend = 47.2, arrow = arrow(length = unit(1.6, "mm"), type = "closed"), linewidth = 0.45) fig <- pa / wrap_elements(full = pb) + plot_layout(heights = c(1.0, 0.95)) + tagit() save_fig(fig, "Fig2_design_timeline", 6.6, 5.4) cat("Fig2 done\n") ## ###################################################################### ## fig03_calibration.R ## ###################################################################### ## Fig. 3 - calibration dataset (Phase II strips) and basic parameters lv <- c("KMnO4-N", "Olsen-P", "NH4OAc-K", "Grain yield", "N uptake", "P uptake", "K uptake") labs_f <- c("KMnO4-N" = "KMnO[4]*'-N (kg ha'^-1*')'", "Olsen-P" = "'Olsen-P (kg ha'^-1*')'", "NH4OAc-K" = "NH[4]*'OAc-K (kg ha'^-1*')'", "Grain yield" = "'Grain yield (kg ha'^-1*')'", "N uptake" = "'N uptake (kg ha'^-1*')'", "P uptake" = "'P uptake (kg ha'^-1*')'", "K uptake" = "'K uptake (kg ha'^-1*')'") strip$var <- factor(strip$var, levels = lv); strip$strip <- factor(strip$strip, levels = c("I", "II", "III")) SC <- c(I = "#B7DFCB", II = "#4FB58F", III = "#00674A") mk <- function(vars, ncol) { ggplot(filter(strip, var %in% vars), aes(strip, mean, colour = strip, fill = strip)) + geom_linerange(aes(ymin = min, ymax = max), linewidth = 1.6, alpha = 0.9) + geom_point(shape = 21, size = 2.8, colour = "black", stroke = 0.5) + geom_text(aes(label = format(mean, nsmall = 0, trim = TRUE, drop0trailing = TRUE)), nudge_x = 0.34, size = 2.2, family = FAM, colour = "grey15", hjust = 0) + scale_colour_manual(values = SC) + scale_fill_manual(values = SC) + scale_x_discrete(expand = expansion(add = c(0.5, 0.95))) + scale_y_continuous(expand = expansion(mult = 0.12)) + facet_wrap(~var, scales = "free_y", nrow = 1, labeller = as_labeller(labs_f, label_parsed)) + labs(x = "Fertility strip", y = NULL) + theme_ms(7.5) + theme(legend.position = "none") } p1 <- mk(c("KMnO4-N", "Olsen-P", "NH4OAc-K", "Grain yield"), 4) p2 <- mk(c("N uptake", "P uptake", "K uptake"), 3) pn <- data.frame(n = factor(c("N", "P2O5", "K2O"), levels = c("N", "P2O5", "K2O")), v = NR) p3 <- ggplot(pn, aes(n, v, fill = n)) + geom_col(width = 0.62, colour = "grey25", linewidth = 0.3) + geom_text(aes(label = fmt(v, 1)), vjust = -0.45, size = 2.5, family = FAM) + scale_fill_manual(values = c(N = "#4C78A8", P2O5 = "#E39B2D", K2O = "#7B5EA7")) + scale_x_discrete(labels = c("N", expression(P[2]*O[5]), expression(K[2]*O))) + scale_y_continuous(expand = expansion(mult = c(0, 0.18))) + labs(x = NULL, y = NULL, title = NULL) + facet_wrap(~"NR (kg per t grain)") + theme_ms(7.5) + theme(legend.position = "none") cd <- data.frame(n = factor(rep(c("N", "P2O5", "K2O"), each = 3), levels = c("N", "P2O5", "K2O")), src = factor(rep(c("Soil (Cs)", "Fertiliser (Cf)", "FYM (Cfym)"), 3), levels = c("Soil (Cs)", "Fertiliser (Cf)", "FYM (Cfym)")), v = c(Cs[1], Cf[1], Cfy[1], Cs[2], Cf[2], Cfy[2], Cs[3], Cf[3], Cfy[3])) p4 <- ggplot(cd, aes(n, v, fill = src)) + geom_col(position = position_dodge(0.72), width = 0.66, colour = "grey25", linewidth = 0.3) + geom_text(aes(label = fmt(v, 2)), position = position_dodge(0.72), vjust = -0.4, size = 2.4, family = FAM) + scale_fill_manual(values = c("Soil (Cs)" = "#9C7A4B", "Fertiliser (Cf)" = "#3C7DB8", "FYM (Cfym)" = "#009E73"), name = NULL) + scale_x_discrete(labels = c("N", expression(P[2]*O[5]), expression(K[2]*O))) + scale_y_continuous(expand = expansion(mult = c(0, 0.14)), limits = c(0, NA)) + labs(x = NULL, y = "Share of nutrient uptake (%)") + theme_ms(7.5) + theme(legend.position = "top", legend.margin = margin(0, 0, 0, 0), legend.box.margin = margin(0, 0, -3, 0)) fig <- p1 / (p2 + p3 + plot_layout(widths = c(3, 1))) / p4 + plot_layout(heights = c(1, 1, 0.95)) + tagit() save_fig(fig, "Fig3_calibration", 6.6, 6.0) cat("Fig3 done\n") ## ###################################################################### ## fig04_nomogram.R ## ###################################################################### ## Fig. 4 - prescription nomograms, domain of applicability, FYM substitution nuts <- c("N", "P2O5", "K2O"); idx <- c(N = 1, P2O5 = 2, K2O = 3) Srng <- list(N = c(180, 320), P2O5 = c(12, 46), K2O = c(170, 320)) xlab <- list(N = expression("KMnO"[4]*"-N (kg ha"^-1*")"), P2O5 = expression("Olsen-P (kg ha"^-1*")"), K2O = expression("NH"[4]*"OAc-K (kg ha"^-1*")")) ttl <- list(N = expression("N dose"), P2O5 = expression(P[2]*O[5]~"dose"), K2O = expression(K[2]*O~"dose")) siteval <- list(N = sites$SN, P2O5 = sites$SP, K2O = sites$SK) rng_lo <- c(N = 198, P2O5 = 18.2, K2O = 191); rng_hi <- c(N = 250, P2O5 = 37.4, K2O = 255) nomo <- function(nu, fym, pts = FALSE, show_x = TRUE) { S <- seq(Srng[[nu]][1], Srng[[nu]][2], length.out = 141); Tt <- seq(2.5, 4.5, length.out = 101) g <- expand.grid(S = S, T = Tt) O <- fym_elem(fym, FYM_REF)[idx[nu]] g$raw <- A_T[nu] * g$T - B_S[nu] * g$S - B_O[nu] * O g$dose <- pmin(pmax(g$raw, LO[nu]), HI[nu]) brk <- seq(LO[nu], HI[nu], by = 15) p <- ggplot(g, aes(S, T)) + geom_raster(aes(fill = dose), interpolate = TRUE) + geom_contour(aes(z = raw), breaks = brk[-c(1, length(brk))], colour = "grey10", alpha = 0.5, linewidth = 0.22) + geom_contour(aes(z = raw), breaks = c(LO[nu], HI[nu]), colour = "black", linewidth = 0.55, linetype = "22") + annotate("rect", xmin = Srng[[nu]][1], xmax = rng_lo[nu], ymin = 2.5, ymax = 4.5, fill = "white", alpha = 0.58) + annotate("rect", xmin = rng_hi[nu], xmax = Srng[[nu]][2], ymin = 2.5, ymax = 4.5, fill = "white", alpha = 0.58) + geom_vline(xintercept = siteval[[nu]], colour = "grey10", linewidth = 0.3, linetype = "dotted") + annotate("text", x = siteval[[nu]], y = 4.47, label = c("T", "A", "P"), size = 2.3, family = FAM, fontface = "bold", vjust = 1, hjust = c(1.3, ifelse(siteval[[nu]][2] < siteval[[nu]][3], 1.3, -0.3), ifelse(siteval[[nu]][2] < siteval[[nu]][3], -0.3, 1.3))) + scale_fill_viridis_c(option = "D", limits = c(LO[nu], HI[nu]), breaks = brk, name = expression("Dose (kg ha"^-1*")"), guide = guide_colourbar(barwidth = 5.5, barheight = 0.4, title.position = "top", title.hjust = 0.5)) + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0)) + labs(x = if (show_x) xlab[[nu]] else NULL, y = if (nu == "N") expression("Yield target (t ha"^-1*")") else NULL, title = ttl[[nu]]) + theme_ms(7.5) + theme(legend.position = "bottom", legend.margin = margin(0, 0, 0, 0), legend.box.margin = margin(-3, 0, 0, 0), plot.title = element_text(hjust = 0.5)) if (pts) { vp <- expand.grid(T = c(3, 3.5, 4), Farm = c("Ayyakannur", "Palayam")); vp$S <- ifelse(vp$Farm == "Ayyakannur", sites$SN[2], sites$SN[3]) vp$S <- c(N = 1, P2O5 = 1, K2O = 1)[nu] * ifelse(vp$Farm == "Ayyakannur", siteval[[nu]][2], siteval[[nu]][3]) p <- p + geom_point(data = vp, aes(S, T, shape = Farm), size = 1.9, fill = "white", colour = "black", stroke = 0.55) + scale_shape_manual(values = SHP, guide = "none") } p } rowA <- lapply(nuts, function(n) nomo(n, 0, pts = TRUE, show_x = FALSE)) rowB <- lapply(nuts, function(n) nomo(n, 12.5, pts = FALSE, show_x = TRUE)) ## substitution bars dt <- read.csv(file.path(OUT, "tables", "dose_reference.csv")) long <- bind_rows(lapply(nuts, function(n) { col <- c(N = "N", P2O5 = "P", K2O = "K")[n] data.frame(nut = n, FYM = dt$FYM, T = dt$T, dose = dt[[col]], flag = dt[[paste0(col, "_flag")]]) })) base <- long %>% filter(FYM == 0) %>% select(nut, T, d0 = dose) long <- long %>% left_join(base, by = c("nut", "T")) %>% mutate(red = 100 * (1 - dose / d0), star = ifelse(flag == "floor", "*", ifelse(flag == "cap", "**", "")), lab = paste0(fmt(dose, 0), star), lab2 = ifelse(FYM == 12.5, paste0(lab, "\n(-", fmt(red, 0), "%)"), lab), FYMf = factor(FYM, levels = c(0, 6.25, 12.5), labels = c("0", "6.25", "12.5")), Tf = factor(fmt(T, 1))) redl <- long %>% filter(FYM == 12.5) %>% group_by(nut, Tf) %>% summarise(red = red, .groups = "drop") %>% left_join(long %>% group_by(nut, Tf) %>% summarise(top = max(dose), .groups = "drop"), by = c("nut", "Tf")) bars <- lapply(nuts, function(n) { ggplot(filter(long, nut == n), aes(Tf, dose, fill = FYMf)) + geom_col(position = position_dodge(0.9), width = 0.82, colour = "grey25", linewidth = 0.3) + geom_text(aes(label = lab), position = position_dodge(0.9), vjust = -0.3, size = 2.0, family = FAM) + geom_text(data = filter(redl, nut == n), aes(Tf, top, label = paste0("-", fmt(red, 0), "%")), inherit.aes = FALSE, vjust = -1.9, size = 2.35, family = FAM, fontface = "bold", colour = "#00694C") + scale_fill_manual(values = c("0" = "#BDBDBD", "6.25" = "#8FD0B6", "12.5" = "#009E73"), name = expression("FYM (t ha"^-1*")"), guide = guide_legend(nrow = 1, title.position = "left")) + scale_y_continuous(expand = expansion(mult = c(0, 0.25)), limits = c(0, NA)) + labs(x = expression("Yield target (t ha"^-1*")"), y = if (n == "N") expression("Dose (kg ha"^-1*")") else NULL) + theme_ms(7.5) + theme(legend.position = "bottom", legend.margin = margin(0, 0, 0, 0), legend.box.margin = margin(-3, 0, 0, 0)) }) fig <- wrap_plots(c(rowA, rowB, bars), ncol = 3, guides = "collect") + plot_layout(heights = c(1, 1, 0.78)) + tagit() & theme(legend.position = "bottom", legend.box = "horizontal", legend.spacing.x = unit(4, "mm"), legend.text = element_text(size = 6.5), legend.title = element_text(size = 6.8)) save_fig(fig, "Fig4_nomograms", 6.7, 8.2) cat("Fig4 done\n") ## ###################################################################### ## fig05_validation.R ## ###################################################################### ## Fig. 5 - accuracy of the prescriptions and effect of dose limits s <- d %>% filter(!is.na(Target_kg_ha)) %>% mutate(tt = Target_kg_ha / 1000, yy = Yield_kg_ha / 1000) fit <- lm(Yield_kg_ha ~ I(Target_kg_ha / 1000) + I(group == "STCR-IPNS"), data = s) b <- coef(fit) fl <- expand.grid(x = c(2.85, 4.15), group = c("STCR-IPNS", "STCR-NPK")) fl$y <- (b[1] + b[2] * fl$x + b[3] * (fl$group == "STCR-IPNS")) / 1000 band <- data.frame(x = c(2.7, 4.3)); band$lo <- 0.9 * band$x; band$hi <- 1.1 * band$x bias <- mean(s$err); rmse <- sqrt(mean(s$err^2)) lab_df <- s %>% filter(Farm == "Palayam") pa <- ggplot(s, aes(tt, yy)) + geom_ribbon(data = band, aes(x = x, ymin = lo, ymax = hi), inherit.aes = FALSE, fill = "grey88") + geom_abline(slope = 1, intercept = 0, linetype = "22", linewidth = 0.4, colour = "grey25") + geom_line(data = fl, aes(x, y, colour = group), linewidth = 0.55) + geom_point(aes(fill = group, shape = Farm), size = 2.5, colour = "black", stroke = 0.45) + annotate("text", x = 2.76, y = 4.2, hjust = 0, vjust = 1, size = 2.3, family = FAM, lineheight = 1.05, label = paste0("n = 12\nbias = ", fmt(bias, 0), " kg/ha\nRMSE = ", fmt(rmse, 0), " kg/ha\nR2 = ", fmt(summary(fit)$r.squared, 2))) + annotate("text", x = 4.12, y = 3.57, label = "1:1", size = 2.2, family = FAM, angle = 28, colour = "grey25") + annotate("text", x = 3.12, y = 3.58, label = "+/- 10%", size = 2.1, family = FAM, angle = 28, colour = "grey45") + scale_colour_manual(values = COL, guide = "none") + scale_fill_manual(values = COL, name = NULL, guide = guide_legend(order = 1, nrow = 1, override.aes = list(shape = 21))) + scale_shape_manual(values = SHP, name = NULL, guide = guide_legend(order = 2, override.aes = list(fill = "grey70"))) + coord_fixed(xlim = c(2.7, 4.3), ylim = c(2.7, 4.3), expand = FALSE) + labs(x = expression("Yield target (t ha"^-1*")"), y = expression("Observed grain yield (t ha"^-1*")")) + theme_ms(7.5) ## (b) achievement sb <- s %>% mutate(xpos = tt + ifelse(group == "STCR-IPNS", 0.05, -0.05)) notes <- data.frame(xpos = c(4.0, 3.0, 3.55), ach = c(88.2, 106.6, 104.4), txt = c("cap on N, P, K", "floor on N, P, K", "floor on K"), group = c("STCR-NPK", "STCR-IPNS", "STCR-IPNS")) pb <- ggplot(sb, aes(xpos, ach, colour = group)) + annotate("rect", xmin = 2.8, xmax = 4.2, ymin = 90, ymax = 110, fill = "grey93") + geom_hline(yintercept = 100, linetype = "22", linewidth = 0.4, colour = "grey25") + geom_line(aes(group = interaction(group, tt)), linewidth = 0.9, alpha = 0.9) + geom_point(aes(fill = group, shape = Farm), size = 2.6, colour = "black", stroke = 0.45) + geom_text(data = notes, aes(xpos, ach, label = txt, colour = group), size = 2.15, family = FAM, inherit.aes = FALSE, fontface = "italic") + scale_colour_manual(values = COL, guide = "none") + scale_fill_manual(values = COL, name = NULL, guide = guide_legend(order = 1, override.aes = list(shape = 21))) + scale_shape_manual(values = SHP, name = NULL, guide = guide_legend(order = 2, override.aes = list(fill = "grey70"))) + scale_x_continuous(breaks = c(3, 3.5, 4), limits = c(2.8, 4.2), expand = c(0, 0)) + scale_y_continuous(limits = c(86, 112), breaks = seq(90, 110, 5), expand = c(0, 0)) + annotate("text", x = 2.82, y = 108.8, label = "+10%", size = 2.1, family = FAM, hjust = 0, colour = "grey40") + annotate("text", x = 2.82, y = 91.2, label = "-10%", size = 2.1, family = FAM, hjust = 0, colour = "grey40") + labs(x = expression("Yield target (t ha"^-1*")"), y = "Achievement of target (%)") + theme_ms(7.5) + theme(aspect.ratio = 1) ## (c-e) raw equation output vs prescribed dose after limits dl <- bind_rows(lapply(c("N", "P2O5", "K2O"), function(n) { s %>% transmute(short, Farm, group, nut = n, raw = .data[[paste0("Raw_", n)]], fin = .data[[paste0("Prescribed_", n)]]) })) %>% mutate(lbl = paste0(short, " (", substr(Farm, 1, 1), ")"), nut = factor(nut, levels = c("N", "P2O5", "K2O"))) ord <- s %>% arrange(Trt, Farm) %>% mutate(lbl = paste0(short, " (", substr(Farm, 1, 1), ")")) %>% pull(lbl) dl$lbl <- factor(dl$lbl, levels = rev(ord)) lim <- data.frame(nut = factor(c("N", "P2O5", "K2O"), levels = c("N", "P2O5", "K2O")), lo = LO, hi = HI) labs_f <- c(N = "'N dose (kg ha'^-1*')'", P2O5 = "P[2]*O[5]~'dose (kg ha'^-1*')'", K2O = "K[2]*O~'dose (kg ha'^-1*')'") pc <- ggplot(dl) + geom_vline(data = lim, aes(xintercept = lo), linetype = "22", linewidth = 0.4, colour = "grey35") + geom_vline(data = lim, aes(xintercept = hi), linetype = "22", linewidth = 0.4, colour = "grey35") + geom_segment(data = filter(dl, abs(raw - fin) > 0.5), aes(x = raw, xend = fin, y = lbl, yend = lbl, colour = group), linewidth = 0.55, arrow = arrow(length = unit(1.3, "mm"), type = "closed")) + geom_point(aes(raw, lbl, colour = group), shape = 1, size = 1.9, stroke = 0.6) + geom_point(aes(fin, lbl, colour = group, shape = Farm), size = 1.9, fill = "white") + facet_wrap(~nut, scales = "free_x", labeller = as_labeller(labs_f, label_parsed)) + scale_y_discrete(limits = rev(ord)) + scale_colour_manual(values = COL, guide = "none") + scale_shape_manual(values = c(Ayyakannur = 16, Palayam = 17), guide = "none") + labs(x = NULL, y = NULL) + theme_ms(7.2) + theme(axis.text.y = element_text(size = 6.4), panel.grid.major.y = element_line(colour = "grey94", linewidth = 0.2)) leg <- cowplot::get_legend(pb + theme(legend.position = "bottom", legend.box = "horizontal", legend.margin = margin(0, 0, 0, 0), legend.text = element_text(size = 7.5))) pa <- pa + theme(legend.position = "none"); pb <- pb + theme(legend.position = "none") pa <- pa + labs(tag = "(a)"); pb <- pb + labs(tag = "(b)"); pc <- pc + labs(tag = "(c)") fig <- ((pa | pb) / wrap_elements(full = leg) / pc) + plot_layout(heights = c(1, 0.07, 0.95)) & theme(plot.tag = element_text(face = "bold", size = 10, family = FAM)) save_fig(fig, "Fig5_validation", 6.6, 7.6) cat("Fig5 done\n") ## ###################################################################### ## fig06_yield_eff.R ## ###################################################################### ## Fig. 6 - yield, response ratios and benefit-cost ratio; Fig. 7 - matched-target comparison vt <- read.csv(file.path(OUT, "tables", "validation_pooled.csv"), stringsAsFactors = FALSE) vt$Trt <- factor(vt$Trt, levels = paste0("T", 1:10)); vt$group <- factor(vt$group, levels = GROUPS) vt$xl <- factor(paste0(vt$Trt, "\n", vt$short), levels = paste0(vt$Trt, "\n", vt$short)) yf <- bind_rows(vt %>% transmute(xl, group, Farm = "Ayyakannur", y = yA), vt %>% transmute(xl, group, Farm = "Palayam", y = yP)) pa <- ggplot(vt, aes(xl, yield, fill = group)) + geom_col(width = 0.7, colour = "grey20", linewidth = 0.3) + geom_point(data = yf, aes(xl, y, shape = Farm), inherit.aes = FALSE, size = 1.7, fill = "white", colour = "black", stroke = 0.5, position = position_dodge(0)) + geom_text(aes(label = paste0(fmt(yield, 0), " ", letter), y = pmax(yA, yP)), vjust = -0.9, size = 2.2, family = FAM) + scale_fill_manual(values = COL, name = NULL) + scale_shape_manual(values = SHP, name = NULL, guide = guide_legend(override.aes = list(fill = "grey70"))) + scale_y_continuous(expand = expansion(mult = c(0, 0.12)), limits = c(0, NA)) + labs(x = NULL, y = expression("Grain yield (kg ha"^-1*")")) + theme_ms(7.5) + theme(legend.position = "top", legend.margin = margin(0, 0, 0, 0), legend.box.margin = margin(0, 0, -3, 0), axis.text.x = element_text(size = 6.6, lineheight = 0.9)) rr <- vt %>% filter(Trt != "T10") %>% mutate(yl = factor(as.character(short), levels = rev(as.character(vt$short)))) pb <- ggplot(rr) + geom_segment(aes(x = RR_T, xend = RR_F, y = yl, yend = yl, colour = group), linewidth = 1.0) + geom_point(aes(RR_T, yl), shape = 23, size = 2.4, fill = "white", colour = "black", stroke = 0.55) + geom_point(aes(RR_F, yl, fill = group), shape = 21, size = 2.6, colour = "black", stroke = 0.5) + geom_text(aes(RR_F, yl, label = fmt(RR_F, 1)), hjust = -0.5, size = 2.1, family = FAM) + scale_colour_manual(values = COL, guide = "none") + scale_fill_manual(values = COL, guide = "none") + scale_y_discrete(limits = rev(as.character(vt$short)[vt$Trt != "T10"])) + scale_x_continuous(expand = expansion(mult = c(0.04, 0.12)), limits = c(0, NA)) + labs(x = expression("Response ratio (kg grain per kg nutrient)"), y = NULL) + theme_ms(7.5) bc <- vt %>% mutate(yl = factor(as.character(short), levels = rev(as.character(vt$short)))) bf <- bind_rows(bc %>% transmute(yl, Farm = "Ayyakannur", b = bA), bc %>% transmute(yl, Farm = "Palayam", b = bP)) pc <- ggplot(bc) + geom_vline(xintercept = 1, linewidth = 0.4, linetype = "22", colour = "grey30") + geom_segment(aes(x = 1, xend = BCR, y = yl, yend = yl, colour = group), linewidth = 1.0) + geom_point(aes(BCR, yl, fill = group), shape = 21, size = 2.8, colour = "black", stroke = 0.5) + geom_point(data = bf, aes(b, yl, shape = Farm), size = 1.3, fill = "white", colour = "black", stroke = 0.4) + geom_text(data = bc %>% mutate(xl2 = pmax(BCR, bA, bP)), aes(xl2, yl, label = fmt(BCR, 2)), hjust = -0.55, size = 2.1, family = FAM) + scale_colour_manual(values = COL, guide = "none") + scale_fill_manual(values = COL, guide = "none") + scale_shape_manual(values = SHP, guide = "none") + scale_y_discrete(limits = rev(as.character(vt$short))) + scale_x_continuous(breaks = seq(1, 2, 0.2), limits = c(0.95, 2.12), expand = c(0, 0)) + labs(x = "Benefit-cost ratio (break-even = 1)", y = NULL) + theme_ms(7.5) fig <- pa / (pb + pc + plot_layout(widths = c(1.05, 1))) + plot_layout(heights = c(1, 0.95)) + tagit() save_fig(fig, "Fig6_yield_efficiency", 6.6, 6.2) cat("Fig6 done\n") ## ---- Fig. 7: matched-target comparison (IPNS vs NPK alone) ---- pp <- d %>% filter(!is.na(target)) %>% group_by(group, target) %>% summarise(Yield = mean(Yield_kg_ha), Fert = mean(F_applied_total), Nup = mean(Uptake_N), Pup = mean(Uptake_P), Kup = mean(Uptake_K), BCR = mean(BCR_reported), .groups = "drop") fv <- d %>% filter(!is.na(target)) %>% select(group, target, Farm, Yield = Yield_kg_ha, Fert = F_applied_total, Nup = Uptake_N, Pup = Uptake_P, Kup = Uptake_K, BCR = BCR_reported) mets <- c(Yield = "'Grain yield (kg ha'^-1*')'", Fert = "'Fertiliser N+'*P[2]*O[5]*'+'*K[2]*O~'applied (kg ha'^-1*')'", BCR = "'Benefit-cost ratio'", Nup = "'N uptake (kg ha'^-1*')'", Pup = "'P uptake (kg ha'^-1*')'", Kup = "'K uptake (kg ha'^-1*')'") long <- pp %>% pivot_longer(c(Yield, Fert, Nup, Pup, Kup, BCR), names_to = "met", values_to = "v") %>% mutate(met = factor(met, levels = names(mets))) wide <- long %>% pivot_wider(names_from = group, values_from = v) %>% mutate(pct = 100 * (`STCR-IPNS` / `STCR-NPK` - 1), met = factor(met, levels = names(mets)), tf = factor(fmt(target, 1), levels = c("4.0", "3.5", "3.0"))) fl <- fv %>% pivot_longer(c(Yield, Fert, Nup, Pup, Kup, BCR), names_to = "met", values_to = "v") %>% mutate(met = factor(met, levels = names(mets)), tf = factor(fmt(target, 1), levels = c("4.0", "3.5", "3.0"))) p7 <- ggplot() + geom_segment(data = wide, aes(x = `STCR-NPK`, xend = `STCR-IPNS`, y = tf, yend = tf), linewidth = 1.2, colour = "grey55") + geom_point(data = fl, aes(v, tf, colour = group, shape = Farm), size = 1.35, alpha = 0.8, position = position_nudge(y = 0)) + geom_point(data = long, aes(v, factor(fmt(target, 1), levels = c("4.0", "3.5", "3.0")), fill = group), shape = 21, size = 3.1, colour = "black", stroke = 0.5) + geom_text(data = wide, aes(x = pmax(`STCR-NPK`, `STCR-IPNS`), y = tf, label = paste0(ifelse(pct > 0, "+", ""), fmt(pct, 1), "%")), hjust = -0.35, vjust = -1.0, size = 2.2, family = FAM, fontface = "bold") + facet_wrap(~met, scales = "free_x", nrow = 2, labeller = as_labeller(mets, label_parsed)) + scale_fill_manual(values = COL, breaks = c("STCR-NPK", "STCR-IPNS"), name = "Farm means") + scale_colour_manual(values = COL, guide = "none") + scale_shape_manual(values = c(Ayyakannur = 1, Palayam = 2), name = "Single farms") + scale_x_continuous(expand = expansion(mult = c(0.14, 0.34)), n.breaks = 3) + labs(x = NULL, y = expression("Yield target (t ha"^-1*")")) + theme_ms(7.5) + theme(strip.text = element_text(face = "plain", size = 7.5), legend.position = "bottom", legend.box = "horizontal", legend.margin = margin(0, 0, 0, 0), legend.box.margin = margin(-3, 0, 0, 0)) save_fig(p7, "Fig7_matched_targets", 6.6, 4.5) cat("Fig7 done\n") ## ###################################################################### ## fig08_stoich.R ## ###################################################################### ## Fig. 8 - uptake stoichiometry (ternary-projected balance plot) and realised nutrient requirement sh <- d %>% mutate(tot = Uptake_N + Uptake_P * 2.29 + Uptake_K * 1.21, sN = 100 * Uptake_N / tot, sP = 100 * Uptake_P * 2.29 / tot, sK = 100 * Uptake_K * 1.21 / tot) ref <- 100 * NR / sum(NR) isoN <- do.call(rbind, lapply(c(36, 38, 40, 42), function(n) data.frame(n = n, x = c(10, 22), y = (100 - n) - c(10, 22)))) isoLab <- do.call(rbind, lapply(c(36, 38, 40, 42), function(n) data.frame(n = n, x = 19.5, y = (100 - n) - 19.5))) isoN$lab <- paste0("N ", isoN$n, "%") lab_pts <- sh %>% group_by(short, group) %>% summarise(sP = mean(sP), sK = mean(sK), .groups = "drop") pa <- ggplot(sh, aes(sP, sK)) + geom_line(data = isoN, aes(x, y, group = n), colour = "grey70", linewidth = 0.3, linetype = "22") + geom_text(data = isoLab, aes(x, y, label = paste0("N ", n, "%")), hjust = 1, vjust = -0.5, size = 2.0, colour = "grey45", family = FAM, inherit.aes = FALSE, angle = -45) + geom_line(aes(group = Trt, colour = group), linewidth = 0.4, alpha = 0.9) + geom_point(aes(fill = group, shape = Farm), size = 2.3, colour = "black", stroke = 0.4) + geom_point(data = data.frame(sP = ref[2], sK = ref[3]), aes(sP, sK), shape = 8, size = 3.2, stroke = 0.8, colour = "black", inherit.aes = FALSE) + annotate("text", x = ref[2] - 0.3, y = ref[3] + 0.55, label = "calibrated NR", size = 2.2, family = FAM, hjust = 1, fontface = "italic") + geom_text_repel(data = lab_pts, aes(sP, sK, label = short), size = 2.2, family = FAM, colour = "grey10", min.segment.length = 0.05, segment.size = 0.2, box.padding = 0.45, point.padding = 0.3, force = 3, seed = 11, max.overlaps = Inf, inherit.aes = FALSE) + scale_fill_manual(values = COL, name = NULL, guide = guide_legend(override.aes = list(shape = 21), nrow = 2)) + scale_colour_manual(values = COL, guide = "none") + scale_shape_manual(values = SHP, name = NULL, guide = guide_legend(override.aes = list(fill = "grey70"))) + coord_cartesian(xlim = c(11.2, 19.6), ylim = c(42.2, 49.8), expand = FALSE) + labs(x = expression("Share of "*P[2]*O[5]*" in N + "*P[2]*O[5]*" + "*K[2]*O*" uptake (%)"), y = expression("Share of "*K[2]*O*" in uptake (%)")) + theme_ms(7.5) + theme(legend.position = "bottom", legend.box = "horizontal", legend.box.just = "top", legend.margin = margin(0, 0, 0, 0), legend.box.margin = margin(-3, 0, 0, 0), legend.spacing.x = unit(5, "mm")) ## (b) realised requirement relative to calibrated NR rq <- d %>% select(Trt, short, group, Farm, N = NR_N, P2O5 = NR_P2O5, K2O = NR_K2O) %>% pivot_longer(c(N, P2O5, K2O), names_to = "nut", values_to = "nr") %>% mutate(ratio = nr / NR[nut], nut = factor(nut, levels = c("N", "P2O5", "K2O"))) rm <- rq %>% group_by(short, nut) %>% summarise(ratio = mean(ratio), lo = min(ratio), hi = max(ratio), .groups = "drop") NC <- c(N = "#4C78A8", P2O5 = "#E39B2D", K2O = "#7B5EA7") pb <- ggplot(rm, aes(short, ratio, colour = nut)) + annotate("rect", xmin = 0.4, xmax = 10.6, ymin = 0.9, ymax = 1.1, fill = "grey93") + geom_hline(yintercept = 1, linetype = "22", linewidth = 0.4, colour = "grey25") + geom_linerange(aes(ymin = lo, ymax = hi), position = position_dodge(0.55), linewidth = 0.5) + geom_point(aes(fill = nut), position = position_dodge(0.55), shape = 21, size = 2.2, colour = "black", stroke = 0.4) + scale_colour_manual(values = NC, guide = "none") + scale_fill_manual(values = NC, name = NULL, labels = c("N", expression(P[2]*O[5]), expression(K[2]*O))) + scale_x_discrete(expand = expansion(add = 0.5)) + scale_y_continuous(breaks = seq(0.8, 1.6, 0.2)) + labs(x = NULL, y = "Realised / calibrated requirement per tonne of grain") + theme_ms(7.5) + theme(axis.text.x = element_text(size = 7), legend.position = "top", legend.margin = margin(0, 0, 0, 0), legend.box.margin = margin(0, 0, -3, 0)) fig <- pa / pb + plot_layout(heights = c(1.12, 0.9)) + tagit() save_fig(fig, "Fig8_stoichiometry", 6.6, 6.6) cat("Fig8 done\n") ## ###################################################################### ## fig09_pca.R ## ###################################################################### ## Fig. 9 - principal component analysis (R: FactoMineR); Fig. 10 - clustered heat map (pheatmap) obj <- readRDS(file.path(OUT, "tables", "pca_objects.rds")) pc <- obj$pc; scd <- obj$scd; thr <- obj$thr; ev <- obj$ev; pv <- obj$pv; sup <- obj$sup_cor; fq <- obj$fq; tl <- obj$tl scd$group <- factor(scd$group, levels = GROUPS) ## (a) scree with parallel analysis k <- 7 sc_df <- data.frame(pc = 1:k, ev = ev[1:k], thr = thr[1:k], pct = pv[1:k]) pa <- ggplot(sc_df, aes(pc)) + geom_line(aes(y = thr), linetype = "22", colour = "grey35", linewidth = 0.45) + geom_point(aes(y = thr), shape = 23, size = 2.2, fill = "white", colour = "grey20", stroke = 0.5) + geom_line(aes(y = ev), colour = "#0072B2", linewidth = 0.6) + geom_point(aes(y = ev), shape = 21, size = 2.6, fill = "#0072B2", colour = "black", stroke = 0.4) + geom_text(data = sc_df[1:3, ], aes(y = ev, label = paste0(fmt(pct, 1), "%")), nudge_x = 0.28, hjust = 0, vjust = c(0.3, -0.7, -0.7), size = 2.3, family = FAM) + annotate("text", x = 7, y = 4.7, label = "parallel analysis (95th percentile)", hjust = 1, size = 2.2, family = FAM, colour = "grey30") + annotate("text", x = 7, y = 0.2, label = "observed eigenvalue", hjust = 1, size = 2.2, family = FAM, colour = "#0072B2") + scale_y_log10(breaks = c(0.01, 0.1, 1, 10), labels = c("0.01", "0.1", "1", "10"), limits = c(0.006, 30)) + scale_x_continuous(breaks = 1:k, limits = c(0.7, 7.4)) + labs(x = "Principal component", y = "Eigenvalue (log scale)") + theme_ms(7.5) ## (b) score plot cen <- scd %>% group_by(short, group) %>% summarise(PC1 = mean(PC1), PC2 = mean(PC2), .groups = "drop") pb <- ggplot(scd, aes(PC1, PC2)) + geom_hline(yintercept = 0, colour = "grey75", linewidth = 0.3) + geom_vline(xintercept = 0, colour = "grey75", linewidth = 0.3) + geom_line(aes(group = Trt, colour = group), linewidth = 0.5) + geom_point(aes(fill = group, shape = Farm), size = 2.5, colour = "black", stroke = 0.4) + geom_text_repel(data = cen, aes(label = short), size = 2.2, family = FAM, colour = "grey10", min.segment.length = 0.1, segment.size = 0.2, box.padding = 0.35, seed = 5, max.overlaps = Inf, ylim = c(-Inf, Inf)) + scale_fill_manual(values = COL, guide = "none") + scale_colour_manual(values = COL, guide = "none") + scale_shape_manual(values = SHP, name = NULL, guide = guide_legend(override.aes = list(fill = "grey70"))) + scale_y_continuous(limits = c(-1.7, 1.7)) + labs(x = paste0("PC1 (", fmt(pv[1], 1), "%)"), y = paste0("PC2 (", fmt(pv[2], 1), "%)")) + theme_ms(7.5) + theme(legend.position = "bottom", legend.margin = margin(0, 0, 0, 0), legend.box.margin = margin(-4, 0, 0, 0)) ## (c) correlation circle with supplementary variables vc <- as.data.frame(pc$var$cor[, 1:2]); colnames(vc) <- c("x", "y"); vc$lab <- tl[rownames(vc)] sp <- as.data.frame(sup); colnames(sp) <- c("x", "y"); sp$lab <- c("Fertiliser applied", "BCR", "RR_F", "RR_T", "FYM dose") sp <- sp[sp$lab != "FYM dose", ] circ <- data.frame(x = cos(seq(0, 2 * pi, length.out = 240)), y = sin(seq(0, 2 * pi, length.out = 240))) SPC <- c("Fertiliser applied" = "#B03A2E", "BCR" = "#1F77B4", "RR_F" = "#7B5EA7", "RR_T" = "#E39B2D") pc_plot <- ggplot() + geom_path(data = circ, aes(x, y), colour = "grey55", linewidth = 0.35) + geom_hline(yintercept = 0, colour = "grey80", linewidth = 0.3) + geom_vline(xintercept = 0, colour = "grey80", linewidth = 0.3) + geom_segment(data = vc, aes(x = 0, y = 0, xend = x, yend = y), colour = "grey35", linewidth = 0.3, arrow = arrow(length = unit(1.1, "mm"), type = "closed")) + geom_segment(data = sp, aes(x = 0, y = 0, xend = x, yend = y, colour = lab), linewidth = 0.55, linetype = "42", arrow = arrow(length = unit(1.3, "mm"), type = "closed")) + geom_text_repel(data = vc, aes(x, y, label = lab), size = 1.95, family = FAM, colour = "grey20", nudge_x = 0.42, direction = "y", hjust = 0, segment.size = 0.15, min.segment.length = 0, box.padding = 0.06, seed = 2, max.overlaps = Inf) + geom_text_repel(data = sp, aes(x, y, label = lab, colour = lab), size = 2.2, family = FAM, fontface = "bold", xlim = c(-1.6, 0.9), ylim = c(-1.25, -0.5), direction = "both", segment.size = 0.2, min.segment.length = 0, box.padding = 0.3, seed = 3, max.overlaps = Inf) + scale_colour_manual(values = SPC, guide = "none") + coord_fixed(xlim = c(-1.1, 2.3), ylim = c(-1.3, 1.1), expand = FALSE) + labs(x = paste0("PC1 (", fmt(pv[1], 1), "%)"), y = paste0("PC2 (", fmt(pv[2], 1), "%)")) + theme_ms(7.5) ## (d) PC1 against purchased fertiliser: fertiliser-only curve and FYM gain fgrid <- data.frame(F_applied_total = seq(0, 185, length.out = 100)); fgrid$pc1 <- predict(fq, newdata = fgrid) fy <- scd %>% filter(Trt %in% c("T2", "T6", "T7", "T8")) %>% mutate(pred = predict(fq, newdata = data.frame(F_applied_total = F_applied_total))) cen2 <- scd %>% group_by(short, group) %>% summarise(F = mean(F_applied_total), PC1 = mean(PC1), .groups = "drop") pd <- ggplot(scd, aes(F_applied_total, PC1)) + geom_line(data = fgrid, aes(F_applied_total, pc1), inherit.aes = FALSE, linetype = "22", colour = "grey30", linewidth = 0.55) + geom_segment(data = fy, aes(x = F_applied_total, xend = F_applied_total, y = pred, yend = PC1), colour = "#009E73", linewidth = 0.5, arrow = arrow(length = unit(1.2, "mm"), type = "closed")) + geom_point(aes(fill = group, shape = Farm), size = 2.5, colour = "black", stroke = 0.4) + geom_text_repel(data = cen2, aes(F, PC1, label = short), inherit.aes = FALSE, size = 2.2, family = FAM, colour = "grey10", min.segment.length = 0.1, segment.size = 0.2, box.padding = 0.4, seed = 8, max.overlaps = Inf) + annotate("text", x = 183, y = -5.2, label = paste0("fertiliser-only curve\n(R2 = ", fmt(summary(fq)$r.squared, 2), ")"), hjust = 1, size = 2.1, family = FAM, colour = "grey25", lineheight = 0.95) + scale_fill_manual(values = COL, name = NULL, guide = guide_legend(override.aes = list(shape = 21), nrow = 3)) + scale_shape_manual(values = SHP, guide = "none") + scale_x_continuous(limits = c(-5, 190), breaks = seq(0, 180, 30)) + labs(x = expression("Purchased fertiliser N + "*P[2]*O[5]*" + "*K[2]*O~"(kg ha"^-1*")"), y = "PC1 score (crop vigour index)") + theme_ms(7.5) + theme(legend.position = "bottom", legend.margin = margin(0, 0, 0, 0), legend.box.margin = margin(-4, 0, 0, 0)) fig <- (pa + pb + pc_plot + pd) + plot_layout(ncol = 2, heights = c(1, 1.05)) + tagit() save_fig(fig, "Fig9_PCA", 6.6, 7.2) cat("Fig9 done\n") ## ---- Fig. 10: clustered heat map ---- zt <- obj$zt; colnames(zt) <- tl[colnames(zt)] ann <- data.frame(Approach = as.character(trt$group[match(rownames(zt), trt$short)]), Fertiliser = as.numeric(tapply(d$F_applied_total, d$short, mean)[rownames(zt)]), FYM = ifelse(rownames(zt) %in% c("RDF+FYM", "IPNS-3.0", "IPNS-3.5", "IPNS-4.0"), "12.5 t/ha", "none"), row.names = rownames(zt)) names(ann)[2] <- "Fert. (kg/ha)" ann_col <- list(Approach = COL, FYM = c("none" = "white", "12.5 t/ha" = "#009E73"), "Fert. (kg/ha)" = c("white", "#08519C")) pal <- colorRampPalette(rev(RColorBrewer::brewer.pal(11, "RdBu")))(101) ph <- pheatmap::pheatmap(as.matrix(zt), clustering_method = "average", clustering_distance_rows = "euclidean", clustering_distance_cols = "euclidean", color = pal, breaks = seq(-2, 2, length.out = 102), annotation_row = ann, annotation_colors = ann_col, border_color = "white", fontsize = 7, fontsize_row = 7.5, fontsize_col = 7, treeheight_row = 24, treeheight_col = 26, cellwidth = 16.5, cellheight = 16, display_numbers = round(as.matrix(zt), 1), number_format = "%.1f", fontsize_number = 5.2, number_color = "grey10", angle_col = 90, silent = TRUE, legend_breaks = c(-2, -1, 0, 1, 2), legend_labels = c("-2", "-1", "0", "1", "2"), main = "") ragg::agg_png(file.path(OUT, "figs", "Fig10_heatmap.png"), width = 6.9, height = 4.3, units = "in", res = 300, background = "white") grid::grid.newpage(); grid::grid.draw(ph$gtable); invisible(dev.off()) cat("Fig10 done\n")