# \donttest{
if (fz_available()) {
# run inside a throwaway directory: fz writes analysis/ and .fz/ under cwd
ex_dir <- file.path(tempdir(), "fz-fzd-example")
dir.create(ex_dir, showWarnings = FALSE)
owd <- setwd(ex_dir)
tf <- tempfile(fileext = ".txt")
writeLines(c("x = ${x~0}", "y = ${y~0}"), tf)
model <- list(
varprefix = "$", delim = "{}", formulaprefix = "@", commentline = "#",
output = list(z = "grep z output.txt | cut -d= -f2")
)
# A minimal self-contained random-sampling algorithm (see
# https://github.com/Funz/fz for ready-made algorithms to install)
algo <- tempfile(fileext = ".py")
writeLines(c(
"import random",
"class RandomSampler:",
" def __init__(self, **options):",
" self.batch = int(options.get('batch_sample_size', 5))",
" self.max_iterations = int(options.get('max_iterations', 3))",
" self.iteration = 0",
" self.input_vars = {}",
" def get_initial_design(self, input_vars, output_vars):",
" self.input_vars = input_vars",
" self.iteration = 1",
" return [{k: random.uniform(*v) for k, v in input_vars.items()}",
" for _ in range(self.batch)]",
" def get_next_design(self, previous_input_vars, previous_output_values):",
" self.iteration += 1",
" if self.iteration > self.max_iterations:",
" return []",
" return [{k: random.uniform(*v) for k, v in self.input_vars.items()}",
" for _ in range(self.batch)]",
" def get_analysis(self, input_vars, output_values):",
" valid = [v for v in output_values if v is not None]",
" mean = sum(valid) / len(valid) if valid else None",
" return {'text': f'mean={mean}', 'data': {'mean': mean}}"
), algo)
result <- fzd(
tf,
list(x = "[0;1]", y = "[-5;5]"),
model,
output_expression = "z",
algorithm = algo,
algorithm_options = list(batch_sample_size = 10, max_iterations = 3)
)
setwd(owd)
unlink(ex_dir, recursive = TRUE)
}
# }
if (FALSE) {
# Direct function model (requires funz-fz >= 1.2)
rosenbrock <- function(x, y) {
list(result = (1 - x)^2 + 100 * (y - x^2)^2)
}
result <- fzd(
input_path = NULL,
input_variables = list(x = "[-2;2]", y = "[-2;2]"),
model = rosenbrock,
output_expression = "result",
algorithm = "examples/algorithms/bfgs.py",
calculators = 1L, # forced to 1L anyway for R functions -- see "Direct function model"
algorithm_options = list(max_iter = 20, tol = 1e-4)
)
}
Run the code above in your browser using DataLab