Last active
March 22, 2017 10:17
-
-
Save jakob-r/6be022d49e135c7905fd4c097bc3d376 to your computer and use it in GitHub Desktop.
optimizing a executable shell script with mlrMBO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(mlrMBO) | |
library(stringi) | |
library(jsonlite) | |
# read command line args (in a not very safe way) | |
# Script can be called like that: | |
# Rscript runMBO.R iters=20 time=10 seed=1 | |
args = commandArgs(TRUE) | |
# defaults: | |
iters = 50 | |
time = 30 | |
seed = 123 | |
# parse args (and possibly overwrite defaults) | |
for (arg in args) { | |
eval(parse(text = arg)) | |
} | |
set.seed(seed) | |
# write bash script | |
lines = '#!/bin/bash | |
fun () | |
{ | |
x1=$1 | |
x2=$2 | |
command="(s($x1-1) + ($x1^2 + $x2^2))" | |
result=$(bc -l <<< $command) | |
} | |
echo "Start calculation." | |
fun $1 $2 | |
echo "The result is $result!" > "result.txt" | |
echo "Finish calculation." | |
' | |
writeLines(lines, "fun.sh") | |
system("chmod +x fun.sh") | |
# runScript function to execute bash script | |
runScript = function(x) { | |
# console output file output_1490030005_1.1_2.4.txt | |
output_file = sprintf("output_%i_%.1f_%.1f.txt", as.integer(Sys.time()), x[['x1']], x[['x2']]) | |
# redirect output with ./fun.sh 1.1 2.4 > output.txt | |
# alternative: ./fun.sh 1.1 2.4 > /dev/null to drop it | |
command = sprintf("./fun.sh %f %f > %s", x[['x1']], x[['x2']], output_file) | |
error.code = system(command) | |
if (error.code != 0) { | |
stop("Simulation had error.code != 0!") | |
} | |
result = readLines("result.txt") | |
# the pattern matches 12 as well as 12.34 and .34 | |
# the ?: makes the decimals a non-capturing group. | |
result = stri_match_first_regex(result, pattern = "\\d*(?:\\.\\d+)?(?=\\!)") | |
as.numeric(result) | |
} | |
# define mlrMBO optimization | |
par.set = makeParamSet( | |
makeNumericParam("x1", lower = -3, upper = 3), | |
makeNumericParam("x2", lower = -2.5, upper = 2.5) | |
) | |
fn = makeSingleObjectiveFunction( | |
id = "fun.sh", | |
fn = runScript, | |
par.set = par.set, | |
has.simple.signature = FALSE | |
) | |
ctrl = makeMBOControl() | |
ctrl = setMBOControlInfill(ctrl, crit = crit.ei) | |
ctrl = setMBOControlTermination(ctrl, iters = iters, time.budget = time) | |
configureMlr(show.info = FALSE, show.learner.output = FALSE) | |
run = mbo(fun = fn, control = ctrl) | |
# save result to json | |
write_json(run[c("x","y")], "mbo_res.json") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment