Commit 626c153e authored by Toni's avatar Toni
Browse files

Added Rscript to make plots

  Create R plots from a GAMS GDX file

  Expects the GDX file to contain a 3 dimensional parameter, e.g. p(x,y)
  First index x maps to x-axis, e.g. t1,t2,...t3 (converted to numeric)
  Second index y maps to categories, e.g. oil, gas, nuclear (categories)
  Third index contains parameter values, e.g. 9 ,7 ,5 (numeric expected)
  Example:  Rscript do_r_plot.r plot4R.gdx -p p -w 50 -a TRUE
parent 24280a55
$title Run Rscript do_r_plot.r
Set
t "Time (e.g. hours) " /t1*t200/
c "Structure measurement point (Celcius) " /outside, wall, inside/
;
Parameter
p(t,c) "Building temperature (celcius) "
;
p(t,c)=ord(t)*ord(t)*ord(c);
execute_unload "%gams.curDir%r\plot4r.gdx";
execute 'Rscript "%gams.curDir%r\do_r_plot.r" -h'
execute 'Rscript "%gams.curDir%r\do_r_plot.r" -f "%gams.curDir%r\plot4r.gdx" -p p -w 50 -a TRUE';
scalar myerrorlevel;
myerrorlevel = errorlevel;
if(myerrorlevel=0,
execute.async 'SumatraPDF.exe "%gams.curDir%Rplots.pdf"';
)
# Program description (run "Rscript do_r_plot.r -h")
text <- vector("character")
text[1 ] <- " Create R plots from a GAMS GDX file"
text[2 ] <- ""
text[3 ] <- " Expects the GDX file to contain a 3 dimensional parameter, e.g. p(x,y)"
text[4 ] <- " First index x maps to x-axis, e.g. t1,t2,...t3 (converted to numeric)"
text[5 ] <- " Second index y maps to categories, e.g. oil, gas, nuclear (categories)"
text[6 ] <- " Third index contains parameter values, e.g. 9 ,7 ,5 (numeric expected)"
text[7 ] <- " Example: Rscript do_r_plot.r plot4r.gdx -p p -w 50 -a TRUE"
text[8 ] <- ""
text[9 ] <- " version 2021-12-31"
text[10 ] <- ""
text[11] <- " author Toni Lastusilta (VTT) "
program_description <- vector("character")
for (i in text) {
program_description <- invisible(paste(program_description,i, sep="\n" ))
}
#Import libraries
library(gdxrrw)
library(ggplot2)
library(optparse)
library(tools)
library(rlang)
#Preprocessing : delete old pdf
pdf_name="Rplots.pdf"
tryCatch({
if(file.exists(pdf_name)){
invisible(file.remove(pdf_name))
}
}
, error = function(ex) { print(ex) ; stop("FAILED: see above message", call.=FALSE) }
)
#CMD Line Option Management and Error Checking
option_list = list(
make_option(c("-f", "--file"), type="character", default="plot4r.gdx",
help="GDX file name [default= %default]", metavar="character"),
make_option(c("-p", "--parameter"), type="character", default="p",
help="parameter name in gdx, expects 3-dimensional, e.g. p(x,y) [default= %default]", metavar="character"),
make_option(c("-w", "--window"), type="integer", default="",
help="do additional plots by splitting x (x-axis) to the specified time step length [default= %default]", metavar="integer"),
make_option(c("-a", "--archive"), type="logical", default=FALSE,
help="archive the created pdf in folder ggplots [default= %default]", metavar="logical")
);
opt_parser = OptionParser(option_list=option_list, description = program_description)
opt = parse_args(opt_parser);
# check that gdx file and gdx reader is found
if (is.null(opt$file) || isFALSE(file.exists(opt$file))) {
print_help(opt_parser)
stop(sprintf("Input GDX file not found: %s/%s",getwd(),opt$file), call.=FALSE)
}
if (! require(gdxrrw)) stop ("gdxrrw package is not available")
if (0 == igdx(silent=TRUE)) stop ("the gdx shared library has not been loaded")
# read gdx parameter p of p(x,y)
tryCatch({
gdxName <- opt$file
symName <- opt$parameter
df_p <- rgdx.param(gdxName,symName, ts=TRUE)
}
, error = function(ex) { print(ex) ; stop("FAILED: see above message", call.=FALSE) }
)
# gdx error check, expecting parameter format p(x,y)
if(ncol(df_p)!=3){
print(head(df_p))
stop(sprintf("Symbol %s has %d columns, expected 3 (third column holds values)", symName, ncol(df_p)), call.=FALSE)
}
# read set x and y from parameter p(x,y)
xvar_desc <- vector("character")
tryCatch({
gdxName <- opt$file
symName <- opt$parameter
xvar=as_string(sym(colnames(df_p)[1]))
df_x <- rgdx.set(gdxName, xvar, names=xvar, ts=TRUE)
xvar_desc = paste(attr(df_x,"ts"), " ")
}
, error = function(ex) { yvar_desc="" ; print(ex) ; print("FAILED to read set description: see above message", call.=FALSE) }
)
yvar_desc <- vector("character")
tryCatch({
gdxName <- opt$file
symName <- opt$parameter
yvar=as_string(sym(colnames(df_p)[2]))
df_y <- rgdx.set(gdxName, yvar, names=yvar, ts=TRUE)
yvar_desc = paste(attr(df_y,"ts"), " ")
}
, error = function(ex) { yvar_desc="" ; print(ex) ; print("FAILED to read set description: see above message", call.=FALSE) }
)
# store data from gdx
xvar_labels <- unique(df_p[1])
window_end <- nrow(xvar_labels)
if(!is.null(attr(df_p,"ts"))){
ptitle <- attr(df_p,"ts")
}else{
ptitle <- symName
}
exec_sys_date=format(Sys.time(), "%Y-%m-%d%Z_%H-%M-%S")
ptitle <- sprintf("%s %s",ptitle,exec_sys_date)
# check value of input option window
window_step=0
if (!is.null(opt$window) && !is.na(opt$window)) {
if(!is.integer(opt$window) || is.na(opt$window) || opt$window<1 || opt$window>window_end){
print(paste("Invalid input: Found",opt$window,"for option window, expected an integer in range 1 to ", window_end))
print("Additional graphs will not be created")
}else{
window_step=opt$window
}
}
# convert x-axis to numeric
df_p[,1] <- ordered(df_p[,1])
levels(df_p[,1]) <- 1:nrow(unique(df_p[1]))
df_p[,1] <- as.numeric(as.character(df_p[,1]))
# Create Plots
xvar <- sym(colnames(df_p)[1])
yvar <- sym(colnames(df_p)[2])
value <- sym(colnames(df_p)[3])
xlabel <- paste(xvar_desc,xvar,"(",xvar_labels[1,1],"=1, ...,",xvar_labels[window_end,1],"=",window_end,")")
ylabel <- paste(yvar_desc,yvar)
g <- ggplot(df_p, aes(x=!!xvar, y=!!value, group=!!yvar, color=!!yvar)) + geom_line() + ggtitle(ptitle) + xlab(xlabel) + ylab(ylabel)
# create PDF
pdf(file = pdf_name, width = 6.25, height = 4, family = "Times", pointsize = 8, onefile = TRUE)
print(g)
cnt_plots=1;
# additional figures to PDF with switch -w (window)
if(window_step>=1){
for(window_curr_start in seq(1, window_end, window_step)){
window_curr_end = window_curr_start + window_step -1
if (window_curr_end>window_end){
window_curr_end=window_end
}
xlabel <- paste(xvar_desc,xvar,"(",xvar_labels[window_curr_start,1],"=",window_curr_start,", ...,",xvar_labels[window_curr_end,1],"=",window_curr_end,")")
print(g + xlab(xlabel) + coord_cartesian(xlim = c(window_curr_start,window_curr_end), expand=0))
cnt_plots=cnt_plots+1
}
}
invisible(dev.off())
# create a copy of the plot with switch -a (archive)
if(file.exists(pdf_name)){
pdf_path=paste(file_path_as_absolute(pdf_name))
print(sprintf("Rscript created %d figures (%s) see:",cnt_plots, exec_sys_date))
print(sprintf("%s",pdf_path))
flush.console()
if(opt$archive){
dir_name="ggplots"
if(!dir.exists(dir_name)){
dir.create(dir_name)
}
dataPath <- sprintf("%s/%s_%s.pdf",file_path_as_absolute(dir_name),exec_sys_date,symName)
invisible(file.copy(pdf_name, dataPath, overwrite = TRUE ))
}
}else{
stop("Rscript failed to create PDF")
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment