-
Notifications
You must be signed in to change notification settings - Fork 4
/
statplot-pythia-outputs.R
173 lines (143 loc) · 7.51 KB
/
statplot-pythia-outputs.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#library(here)
library(argparser)
library(data.table)
library(ggplot2)
library(stringr)
setwd(".")
data_cde_file <- "DATA_CDE.csv"
if (file.exists(data_cde_file)) {
var_dic <- data.table::fread(data_cde_file)
} else {
# const_ha_vars <- c("DWAP", "CWAM", "HWAM", "HWAH", "BWAH", "PWAM", "")
# const_temp_vars <- c("TMAXA", "TMINA")
# const_date_vars <- c("SDAT", "PDAT", "EDAT", "ADAT", "MDAT", "HDAT")
}
crop_cde_file <- "crop_codes.csv"
if (file.exists(crop_cde_file)) {
crop_dic <- data.table::fread(crop_cde_file)
}
plotXVarHeader <- var_dic[name == "FILE", factor]
p <- argparser::arg_parser("Generate statistics boxplot based on two aggregation results from Pythia outputs for World Modelers(fixed)")
p <- argparser::add_argument(p, "input_base", "Aggregation result file for baseline data")
p <- argparser::add_argument(p, "input_scenario", "Aggregation result file for scenario data")
p <- argparser::add_argument(p, "output", "folder Path to generaete box plot graphs")
p <- argparser::add_argument(p, "--variables", short = "-v", nargs = Inf, help = paste("Variable HEADER names for comparison, if not given, then comparing all non-factor columns"))
p <- argparser::add_argument(p, "--factors", short="-f", nargs=Inf, help=paste0("Factor names for grouping the comparison result: if not given, then any header in the following list will be considered as factor [", paste(unique(var_dic[factor != "" & factor != "file", factor]), collapse=","), "]"))
# p <- argparser::add_argument(p, "--max_bar_num", short="-n", default = 25, help = "Maximum number of box bar per graph")
argv <- argparser::parse_args(p)
# for test only
# argv <- argparser::parse_args(p, c("test\\data\\case17\\agg_result\\agg_crop_per_person_base_adm1.csv", "test\\data\\case17\\agg_result\\agg_crop_per_person_scenario_adm1.csv", "test\\data\\case17\\boxplot", "-f", "ADMLV1"))
# argv <- argparser::parse_args(p, c("test\\data\\case18\\baseline\\analysis_out\\stage_7_admlv0.csv", "test\\data\\case18\\scenario\\analysis_out\\stage_7_admlv0.csv", "test\\data\\case18\\debug", "-f", "ADMLV0"))
suppressWarnings(in_dir_base <- normalizePath(argv$input_base))
suppressWarnings(in_dir_scenario <- normalizePath(argv$input_scenario))
suppressWarnings(out_dir <- normalizePath(argv$output))
variables <- argv$variables
factors <- argv$factors
# maxBarNum <- argv$max_bar_num
maxBarNum <- 25
if (!dir.exists(in_dir_base) && !file.exists(in_dir_base)) {
stop(sprintf("%s does not exist.", in_dir_base))
}
if (!dir.exists(in_dir_scenario) && !file.exists(in_dir_scenario)) {
stop(sprintf("%s does not exist.", in_dir_scenario))
}
if (!dir.exists(out_dir)) {
dir.create(out_dir, recursive = TRUE)
}
# Process baseline data and calculate threshold
print("Loading files for relative difference comparison")
df_base <- data.table::fread(in_dir_base)[,(plotXVarHeader):="Baseline"]
df_scenario <- data.table::fread(in_dir_scenario)[,(plotXVarHeader):="Scenario"]
df <- data.table::rbindlist(list(df_base, df_scenario))
if (is.na(factors)) {
headers <- colnames(df)
plotFactorHeaders <- headers[headers %in% var_dic[factor != "" & factor != "file", factor]]
} else {
if (T %in% (paste0("ADMLV", 0:5) %in% factors)) {
factors <- unique(c(paste0("ADMLV", 0:c(5:0)[match(T,paste0("ADMLV", 5:0) %in% factors)]), factors))
}
plotFactorHeaders <- var_dic[name %in% factors, factor]
}
if (is.na(variables)) {
headers <- colnames(df)
variables <- headers[!headers %in% var_dic[factor != "", factor]]
variables <- variables[!variables %in% plotFactorHeaders]
}
print("Generating boxplot graphs...")
extension <- "png"
xLaxAngel <- 90
plotDatas <- split(df, by=plotFactorHeaders, keep.by=FALSE, collapse="__")
plotKeys <- names(plotDatas)
for (variable in variables) {
for (key in plotKeys) {
print(paste0("Processing ", variable, " for ", key))
plotData <- plotDatas[key][[1]]
rows <- unique(plotData[,c(..plotXVarHeader), ])[order(get(plotXVarHeader))]
rows[,factor_id:=1:rows[,.N]]
plotData <- merge(plotData, rows, by=c(plotXVarHeader), all=T)
factorlist <- rows
setcolorder(factorlist, c("factor_id", plotXVarHeader))
factorNum <- factorlist[,.N]
if (class(plotData[,get(plotXVarHeader)]) != "character") {
plotData[,(plotXVarHeader):=as.character(get(plotXVarHeader))]
}
# Title rule: factors list, crop name, variable name (e.g. average yield)
if (var_dic[name=="CR", factor] %in% colnames(plotData)) {
crop <- crop_dic[DSSAT_code==plotData[,get(var_dic[name=="CR", factor])][1], Common_name]
} else {
crop <- "crop"
}
if (var_dic[average==variable, .N] > 0) {
plotTitle <- paste(str_replace_all(key, "\\.", "_"), crop, paste0("average ", var_dic[average==variable, boxplot], " (", var_dic[average==variable, unit], ")"), sep=", ")
variableInFile <- paste0("average ", var_dic[average==variable, boxplot])
} else if (var_dic[total==variable, .N] > 0) {
plotTitle <- paste(str_replace_all(key, "\\.", "_"), crop, paste0("total ", var_dic[total==variable, boxplot], " (", str_replace_all(var_dic[total==variable, unit], "/ha", ""), ")"), sep=", ")
variableInFile <- paste0("total ", var_dic[total==variable, boxplot])
} else if (var_dic[total_ton==variable, .N] > 0) {
plotTitle <- paste(str_replace_all(key, "\\.", "_"), crop, paste0("total ", var_dic[total_ton==variable, boxplot], " (ton)"), sep=", ")
variableInFile <- paste0("total ", var_dic[total_ton==variable, boxplot])
} else if (var_dic[name==toupper(variable), .N] > 0) {
plotTitle <- paste(str_replace_all(key, "\\.", "_"), crop, paste0(var_dic[name==toupper(variable), boxplot], " (", var_dic[name==toupper(variable), unit], ")"), sep=", ")
variableInFile <- var_dic[name==toupper(variable), boxplot]
} else {
plotTitle <- paste(str_replace_all(key, "\\.", "_"), crop, variable, sep=", ")
variableInFile <- tolower(variable)
}
plotTitle <- str_wrap(plotTitle, 40)
for (i in 1:ceiling(factorNum/maxBarNum)) {
plotSubData <- plotData[factor_id %in% (1 + (i-1) * maxBarNum) : (i*maxBarNum)]
plot <- ggplot(data = plotSubData, aes(x = get(plotXVarHeader), y = get(variable))) +
geom_boxplot(
# aes(fill = HWAH),
outlier.colour = NA,
color = "darkgrey"
) +
stat_boxplot(geom ='errorbar')+
geom_boxplot()+
coord_cartesian(ylim = range(df[,..variable])) +
# theme_light() +
theme(legend.text = element_text(size = 13),
legend.title = element_text(size = 13)) +
# theme(axis.text = element_text(size = 13)) +
theme(axis.title = element_text(size = 13, face = "bold")) +
labs(x = plotXVarHeader, y = variableInFile, colour = "Legend", title = plotTitle) +
theme(axis.text.x = element_text(angle = xLaxAngel, vjust = 0.5, hjust = 1)) +
theme(panel.grid.minor = element_blank()) +
theme(plot.margin = unit(c(1, 1, 1, 1), "mm")) +
theme(plot.title = element_text(size=20, face="bold", hjust = 0.5))
# scale_fill_manual(values=colors)
if (ceiling(factorNum/maxBarNum) == 1) {
file_name <- paste0(str_replace_all(variableInFile, " ", "_"), "-", str_replace_all(key, "\\.", "__"), ".", extension)
} else {
file_name <- paste0(str_replace_all(variableInFile, " ", "_"), "-", str_replace_all(key, "\\.", "__"), "_", i, ".", extension)
}
ggsave(
plot,
filename = file_name,
# plot = last_plot(),
path = out_dir
)
}
}
}
print("Complete.")