Use mlrMBO to optimize via command line

R r-bloggers

Tutorial on using mlrMBO from the command line

Many people who want to apply Bayesian optimization want to use it to optimize an algorithm that is not implemented in R but runs on the command line as a shell script or an executable.

We recently published mlrMBO on CRAN. As a normal package it normally operates inside of R, but with this post I want to demonstrate how mlrMBO can be used to optimize an external application. At the same time I will highlight some issues you can likely run into.

First of all we need a bash script that we want to optimize. This tutorial will only run on Unix systems (Linux, OSX etc.) but should also be informative for windows users. The following code will write a tiny bash script that uses bc to calculate \(sin(x_1-1) + (x_1^2 + x_2^2)\) and write the result “hidden” in a sentence (The result is 12.34!) in a result.txt text file.

The bash script

# write bash script
lines = '#!/bin/bash
fun ()
  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, "")
# make it executable:
system("chmod +x")

Running the script from R

Now we need a R function that starts the script, reads the result from the text file and returns it.

runScript = function(x) {
  command = sprintf("./ %f %f", x[['x1']], x[['x2']])
  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+)?(?=\\!)")

This function uses stringi and regular expressions to match the result within the sentence. Depending on the output different strategies to read the result make sense. XML files can usually be accessed with XML::xmlParse, XML::getNodeSet, XML::xmlAttrs etc. using XPath queries. Sometimes the good old read.table() is also sufficient. If, for example, the output is written in a file like this:

value1 = 23.45
value2 = 13.82

You can easily use source() like that:

EV = new.env()
eval(expr = {a = 1}, envir = EV)
source(file = "result.txt", local = EV)
res = as.list(EV)

which will return a list with the entries $value1 and $value2.

Define bounds, wrap function.

To evaluate the function from within mlrMBO it has to be wrapped in smoof function. The smoof function also contains information about the bounds and scales of the domain of the objective function defined in a ParameterSet.

# Defining the bounds of the parameters:
par.set = makeParamSet(
  makeNumericParam("x1", lower = -3, upper = 3),
  makeNumericParam("x2", lower = -2.5, upper = 2.5)
# Wrapping everything in a smoof function:
fn = makeSingleObjectiveFunction(
  id = "", 
  fn = runScript,
  par.set = par.set,
  has.simple.signature = FALSE
# let's see if the function is working
des = generateGridDesign(par.set, resolution = 3)
des$y = apply(des, 1, fn)
  x1   x2         y
1 -3 -2.5 16.006802
2  0 -2.5  5.408529
3  3 -2.5 16.159297
4 -3  0.0  9.756802
5  0  0.0  0.841471
6  3  0.0  9.909297
7 -3  2.5 16.006802
8  0  2.5  5.408529
9  3  2.5 16.159297

If you run this locally, you will see that the console output generated by our shell script directly appears in the R-console. This can be helpful but also annoying.

Redirecting output

If a lot of output is generated during a single call of system() it might even crash R. To avoid that I suggest to redirect the output into a file. This way no output is lost and the R console does not get flooded. We can simply achieve that by replacing the command in the function runScript from above with the following code:

  # 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 ./ 1.1 2.4 > output.txt
  # alternative: ./ 1.1 2.4 > /dev/null to drop it
  command = sprintf("./ %f %f > %s", x[['x1']], x[['x2']], output_file)

Start the Optimization

Now everything is set so we can proceed with the usual MBO setup:

ctrl = makeMBOControl()
ctrl = setMBOControlInfill(ctrl, crit = crit.ei)
ctrl = setMBOControlTermination(ctrl, iters = 10)
configureMlr( = FALSE, show.learner.output = FALSE)
run = mbo(fun = fn, control = ctrl)
# The resulting optimal configuration:
[1] -0.8867509

[1] 0.3332594
# The best reached value:
[1] 0.05311128

Execute the R script from a shell

Also you might not want to bothered having to start R and run this script manually so what I would recommend is saving all above as an R-script plus some lines that write the output in a JSON file like this:

write_json(run[c("x","y")], "mbo_res.json")

Let’s assume we saved all of that above as an R-script under the name runMBO.R (actually it is available as a gist).

Then you can simply run it from the command line:

Rscript runMBO.R 

As an extra the script in the gist also contains a simple handler for command line arguments. In this case you can define the number of optimization iterations and the maximal allowed time in seconds for the optimization. You can also define the seed to make runs reproducible:

Rscript runMBO.R iters=20 time=10 seed=3

If you want to build a more advanced command line interface you might want to have a look at docopt.

Clean up

To clean up all the files generated by this script you can run:

output.files = list.files(pattern = "output_\\d+_[0-9_.-]+\\.txt")


For attribution, please cite this work as

Richter (2017, March 22). mlr-org: Use mlrMBO to optimize via command line. Retrieved from

BibTeX citation

  author = {Richter, Jakob},
  title = {mlr-org: Use mlrMBO to optimize via command line},
  url = {},
  year = {2017}