Commit 3d8ce511 authored by Jean-Baptiste Mouret's avatar Jean-Baptiste Mouret
Browse files

Initial import from the ISIR's repository

parent e9f3a0ff
#!/usr/bin/env python
# encoding: utf-8
#
# partially based on boost.py written by Gernot Vormayr
# written by Ruediger Sonderfeld <ruediger@c-plusplus.de>, 2008
# modified by Bjoern Michaelsen, 2008
# modified by Luca Fossati, 2008
# rewritten for waf 1.5.1, Thomas Nagy, 2008
# rewritten for waf 1.6.2, Sylvain Rouquette, 2011
'''
To add the boost tool to the waf file:
$ ./waf-light --tools=compat15,boost
or, if you have waf >= 1.6.2
$ ./waf update --files=boost
The wscript will look like:
def options(opt):
opt.load('compiler_cxx boost')
def configure(conf):
conf.load('compiler_cxx boost')
conf.check_boost(lib='system filesystem', mt=True, static=True)
def build(bld):
bld(source='main.cpp', target='app', use='BOOST')
'''
import sys
import re
from waflib import Utils, Logs
from waflib.Configure import conf
BOOST_LIBS = ['/usr/lib', '/usr/local/lib', '/opt/local/lib', '/sw/lib', '/lib']
BOOST_INCLUDES = ['/usr/include', '/usr/local/include', '/opt/local/include', '/sw/include']
BOOST_VERSION_FILE = 'boost/version.hpp'
BOOST_VERSION_CODE = '''
#include <iostream>
#include <boost/version.hpp>
int main() { std::cout << BOOST_LIB_VERSION << std::endl; }
'''
# toolsets from {boost_dir}/tools/build/v2/tools/common.jam
PLATFORM = Utils.unversioned_sys_platform()
detect_intel = lambda env: (PLATFORM == 'win32') and 'iw' or 'il'
detect_clang = lambda env: (PLATFORM == 'darwin') and 'clang-darwin' or 'clang'
detect_mingw = lambda env: (re.search('MinGW', env.CXX[0])) and 'mgw' or 'gcc'
BOOST_TOOLSETS = {
'borland': 'bcb',
'clang': detect_clang,
'como': 'como',
'cw': 'cw',
'darwin': 'xgcc',
'edg': 'edg',
'g++': detect_mingw,
'gcc': detect_mingw,
'icpc': detect_intel,
'intel': detect_intel,
'kcc': 'kcc',
'kylix': 'bck',
'mipspro': 'mp',
'mingw': 'mgw',
'msvc': 'vc',
'qcc': 'qcc',
'sun': 'sw',
'sunc++': 'sw',
'tru64cxx': 'tru',
'vacpp': 'xlc'
}
def options(opt):
opt.add_option('--boost-includes', type='string',
default='', dest='boost_includes',
help='''path to the boost directory where the includes are
e.g. /boost_1_45_0/include''')
opt.add_option('--boost-libs', type='string',
default='', dest='boost_libs',
help='''path to the directory where the boost libs are
e.g. /boost_1_45_0/stage/lib''')
opt.add_option('--boost-static', action='store_true',
default=False, dest='boost_static',
help='link static libraries')
opt.add_option('--boost-mt', action='store_true',
default=False, dest='boost_mt',
help='select multi-threaded libraries')
opt.add_option('--boost-abi', type='string', default='', dest='boost_abi',
help='''select libraries with tags (dgsyp, d for debug),
see doc Boost, Getting Started, chapter 6.1''')
opt.add_option('--boost-toolset', type='string',
default='', dest='boost_toolset',
help='force a toolset e.g. msvc, vc90, \
gcc, mingw, mgw45 (default: auto)')
py_version = '%d%d' % (sys.version_info[0], sys.version_info[1])
opt.add_option('--boost-python', type='string',
default=py_version, dest='boost_python',
help='select the lib python with this version \
(default: %s)' % py_version)
@conf
def __boost_get_version_file(self, dir):
try:
return self.root.find_dir(dir).find_node(BOOST_VERSION_FILE)
except:
return None
@conf
def boost_get_version(self, dir):
"""silently retrieve the boost version number"""
re_but = re.compile('^#define\\s+BOOST_LIB_VERSION\\s+"(.*)"$', re.M)
try:
val = re_but.search(self.__boost_get_version_file(dir).read()).group(1)
except:
val = self.check_cxx(fragment=BOOST_VERSION_CODE, includes=[dir],
execute=True, define_ret=True)
return val
@conf
def boost_get_includes(self, *k, **kw):
includes = k and k[0] or kw.get('includes', None)
if includes and self.__boost_get_version_file(includes):
return includes
for dir in BOOST_INCLUDES:
if self.__boost_get_version_file(dir):
return dir
if includes:
self.fatal('headers not found in %s' % includes)
else:
self.fatal('headers not found, use --boost-includes=/path/to/boost')
@conf
def boost_get_toolset(self, cc):
toolset = cc
if not cc:
build_platform = Utils.unversioned_sys_platform()
if build_platform in BOOST_TOOLSETS:
cc = build_platform
else:
cc = self.env.CXX_NAME
if cc in BOOST_TOOLSETS:
toolset = BOOST_TOOLSETS[cc]
return isinstance(toolset, str) and toolset or toolset(self.env)
@conf
def __boost_get_libs_path(self, *k, **kw):
''' return the lib path and all the files in it '''
if 'files' in kw:
return self.root.find_dir('.'), Utils.to_list(kw['files'])
libs = k and k[0] or kw.get('libs', None)
if libs:
path = self.root.find_dir(libs)
files = path.ant_glob('*boost_*')
if not libs or not files:
for dir in BOOST_LIBS:
try:
path = self.root.find_dir(dir)
files = path.ant_glob('*boost_*')
if files:
break
path = self.root.find_dir(dir + '64')
files = path.ant_glob('*boost_*')
if files:
break
except:
path = None
if not path:
if libs:
self.fatal('libs not found in %s' % libs)
else:
self.fatal('libs not found, use --boost-includes=/path/to/boost/lib')
self.to_log('Found the boost path in %r with the libraries:' % path)
for x in files:
self.to_log(' %r' % x)
return path, files
@conf
def boost_get_libs(self, *k, **kw):
'''
return the lib path and the required libs
according to the parameters
'''
path, files = self.__boost_get_libs_path(**kw)
t = []
if kw.get('mt', False):
t.append('mt')
if kw.get('abi', None):
t.append(kw['abi'])
tags = t and '(-%s)+' % '-'.join(t) or ''
toolset = '(-%s[0-9]{0,3})+' % self.boost_get_toolset(kw.get('toolset', ''))
version = '(-%s)+' % self.env.BOOST_VERSION
def find_lib(re_lib, files):
for file in files:
if re_lib.search(file.name):
self.to_log('Found boost lib %s' % file)
return file
return None
def format_lib_name(name):
if name.startswith('lib'):
name = name[3:]
return name.split('.')[0]
libs = []
for lib in Utils.to_list(k and k[0] or kw.get('lib', None)):
py = (lib == 'python') and '(-py%s)+' % kw['python'] or ''
# Trying libraries, from most strict match to least one
for pattern in ['boost_%s%s%s%s%s' % (lib, toolset, tags, py, version),
'boost_%s%s%s%s' % (lib, tags, py, version),
'boost_%s%s%s' % (lib, tags, version),
# Give up trying to find the right version
'boost_%s%s%s%s' % (lib, toolset, tags, py),
'boost_%s%s%s' % (lib, tags, py),
'boost_%s%s' % (lib, tags)]:
self.to_log('Trying pattern %s' % pattern)
file = find_lib(re.compile(pattern), files)
if file:
libs.append(format_lib_name(file.name))
break
else:
self.fatal('lib %s not found in %s' % (lib, path))
return path.abspath(), libs
@conf
def check_boost(self, *k, **kw):
"""
initialize boost
You can pass the same parameters as the command line (without "--boost-"),
but the command line has the priority.
"""
if not self.env['CXX']:
self.fatal('load a c++ compiler first, conf.load("compiler_cxx")')
params = {'lib': k and k[0] or kw.get('lib', None)}
for key, value in self.options.__dict__.items():
if not key.startswith('boost_'):
continue
key = key[len('boost_'):]
params[key] = value and value or kw.get(key, '')
var = kw.get('uselib_store', 'BOOST')
self.start_msg('Checking boost includes')
self.env['INCLUDES_%s' % var] = self.boost_get_includes(**params)
self.env.BOOST_VERSION = self.boost_get_version(self.env['INCLUDES_%s' % var])
self.end_msg(self.env.BOOST_VERSION)
if Logs.verbose:
Logs.pprint('CYAN', ' path : %s' % self.env['INCLUDES_%s' % var])
if not params['lib']:
return
self.start_msg('Checking boost libs')
suffix = params.get('static', 'ST') or ''
path, libs = self.boost_get_libs(**params)
self.env['%sLIBPATH_%s' % (suffix, var)] = [path]
self.env['%sLIB_%s' % (suffix, var)] = libs
self.end_msg('ok')
if Logs.verbose:
Logs.pprint('CYAN', ' path : %s' % path)
Logs.pprint('CYAN', ' libs : %s' % libs)
#! /usr/bin/env python
# encoding: utf-8
# JB Mouret - 2009
"""
Quick n dirty eigen2 detection
"""
import os, glob, types
from waflib.Configure import conf
def options(opt):
opt.add_option('--eigen', type='string', help='path to eigen', dest='eigen')
@conf
def check_eigen(conf):
if conf.options.eigen:
conf.env.INCLUDES_EIGEN = [conf.options.eigen]
conf.env.LIBPATH_EIGEN = [conf.options.eigen]
else:
conf.env.INCLUDES_EIGEN = ['/usr/include/eigen2',
'/usr/local/include/eigen2',
'/usr/include', '/usr/local/include']
res = conf.find_file('Eigen/Core', conf.env.INCLUDES_EIGEN)
return 1
#!/bin/sh
find .|egrep "(cpp|hpp)$"|xargs astyle -L -A14 -N -H -c -p --indent=spaces=2
find .|grep ".orig$"|xargs rm
//#define SHOW_TIMER
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/include/vector.hpp>
#include "limbo/limbo.hpp"
#include "limbo/inner_cmaes.hpp"
using namespace limbo;
struct Params {
struct gp_ucb : public defaults::gp_ucb {};
struct cmaes : public defaults::cmaes {};
struct gp_auto : public defaults::gp_auto {};
struct meanconstant : public defaults::meanconstant {};
struct boptimizer {
BO_PARAM(double, noise, 0.001);
BO_PARAM(int, dump_period, 1);
};
struct init {
BO_PARAM(int, nb_samples, 5);
};
struct maxiterations {
BO_PARAM(int, n_iterations, 20);
};
};
struct fit_eval {
static constexpr size_t dim = 2;
double operator()(const Eigen::VectorXd& x) const {
double res = 0;
for (int i = 0; i < x.size(); i++)
res += 1 - (x[i] - 0.3) * (x[i] - 0.3) + sin(10 * x[i]) * 0.2;
return res;
}
};
int main() {
BOptimizer<Params> opt;
opt.optimize(fit_eval());
std::cout << opt.best_observation()
<< " res " << opt.best_sample().transpose()
<< std::endl;
return 0;
}
#include "limbo/parego.hpp"
using namespace limbo;
struct Params {
struct boptimizer {
BO_PARAM(double, noise, 0.005);
BO_PARAM(int, dump_period, -1);
};
struct init {
BO_PARAM(int, nb_samples, 10);
// calandra: number of dimensions * 5
// knowles : 11 * dim - 1
};
struct maxiterations {
BO_PARAM(int, n_iterations, 50);
};
struct ucb : public defaults::ucb {};
struct gp_ucb : public defaults::gp_ucb {};
struct cmaes : public defaults::cmaes {};
struct gp_auto : public defaults::gp_auto {};
struct meanconstant : public defaults::meanconstant {};
struct parego : public defaults::parego{};
};
struct zdt2 {
static constexpr size_t dim = 30;
Eigen::VectorXd operator()(const Eigen::VectorXd& x) const {
Eigen::VectorXd res(2);
double f1 = x(0);
double g = 1.0;
for (size_t i = 1; i < x.size(); ++i)
g += 9.0 / (x.size() - 1) * x(i) * x(i);
double h = 1.0f - pow((f1 / g), 2.0);
double f2 = g * h;
res(0) = -f1;
res(1) = -f2;
return res;
}
};
struct mop2 {
static constexpr size_t dim = 2;
Eigen::VectorXd operator()(const Eigen::VectorXd& x) const {
Eigen::VectorXd res(2);
// scale to [-2, 2]
Eigen::VectorXd xx = (x * 4.0).array() - 2.0;
// f1, f2
Eigen::VectorXd v1 = (xx.array() - 1.0 / sqrt(xx.size())).array().square();
Eigen::VectorXd v2 = (xx.array() + 1.0 / sqrt(xx.size())).array().square();
double f1 = 1.0 - exp(-v1.sum());
double f2 = 1.0 - exp(-v2.sum());
// we _maximize in [0:1]
res(0) = -f1 + 1;
res(1) = -f2 + 1;
return res;
}
};
// note UCB ne marche pas si fonction positive _ou_ negative?
int main() {
par::init();
// if you want to use a standard GP & basic UCB:
// typedef kernel_functions::MaternFiveHalfs<Params> kernel_t;
// typedef model::GP<Params, kernel_t, mean_t> gp_t;
// typedef acquisition_functions::UCB<Params, gp_t> ucb_t;
//Parego<Params, model_fun<gp_t>, acq_fun<ucb_t> > opt;
Parego<Params> opt;
opt.optimize(mop2());
auto p_model = opt.model_pareto_front(0, 1.0, 0.0025);
auto p_data = opt.data_pareto_front();
std::ofstream pareto_model("pareto_model.dat"), pareto_data("pareto_data.dat");
for (auto x : p_model)
pareto_model << std::get<1>(x).transpose() << " "
<< (std::get<1>(x).array() + std::get<2>(x)).transpose() << " "
<< (std::get<1>(x).array() - std::get<2>(x)).transpose() << " "
<< std::endl;
for (auto x : p_data)
pareto_data << std::get<1>(x).transpose() << std::endl;
return 0;
}
#!/usr/bin/env python
# encoding: utf-8
def build(bld):
obj = bld.program(features = 'cxx',
source = 'mono_dim.cpp',
includes = '. .. ../../',
target = 'mono_dim',
uselib = 'BOOST EIGEN',
use = 'limbo')
obj = bld.program(features = 'cxx',
source = 'parego.cpp',
includes = '. .. ../../',
target = 'parego',
uselib = 'BOOST EIGEN TBB',
use = 'limbo')
#ifndef ACQUISITION_FUNCTIONS_HPP_
#define ACQUISITION_FUNCTIONS_HPP_
#include <vector>
#include <iostream>
#include <Eigen/Core>
#include <limits>
namespace limbo {
namespace defaults {
struct gp_ucb {
BO_PARAM(float, delta, 0.001);
};
struct ucb {
BO_PARAM(float, alpha, 0.5);
};
}
namespace acquisition_functions {
template<typename Params, typename Model>
class UCB {
public:
UCB(const Model& model, int iteration = 0) : _model(model) {
}
size_t dim() const {
return _model.dim();
}
double operator()(const Eigen::VectorXd& v) const {
double mu, sigma;
std::tie(mu, sigma) = _model.query(v);
return (mu + Params::ucb::alpha() * sqrt(sigma));
}
protected:
const Model& _model;
};
template<typename Params, typename Model>
class GP_UCB {
public:
GP_UCB(const Model& model, int iteration) : _model(model) {
double t3 = pow(iteration, 3.0);
static constexpr double delta3 = Params::gp_ucb::delta() * 3;
static constexpr double pi2 = M_PI * M_PI;
_beta = sqrtf(2.0 * log(t3 * pi2 / delta3));
}
size_t dim() const {
return _model.dim();
}
double operator()(const Eigen::VectorXd& v) const {
double mu, sigma;
std::tie(mu, sigma) = _model.query(v);
return (mu + _beta * sqrt(sigma));
}
protected:
const Model& _model;
double _beta;
};
}
}
#endif
#ifndef BO_BASE_HPP_
#define BO_BASE_HPP_
#include <vector>
#include <iostream>
#include <boost/parameter.hpp>
#include <boost/progress.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/algorithm/iteration/accumulate.hpp>
#include <boost/fusion/include/accumulate.hpp>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/filesystem.hpp>
#include <Eigen/Core>
#include <Eigen/LU>
#include <limits>
// we need everything to have the defaults
#include "macros.hpp"
#include "stopping_criterion.hpp"
#include "stat.hpp"
#include "misc.hpp"
#include "kernel_functions.hpp"
#include "acquisition_functions.hpp"
#include "mean_functions.hpp"
#include "inner_optimization.hpp"
#include "inner_cmaes.hpp"
#include "gp.hpp"
#include "gp_auto.hpp"
#include "init_functions.hpp"
namespace limbo {
template<typename BO>
struct RefreshStat_f {
RefreshStat_f(const BO &bo) : _bo(bo) {
}
const BO& _bo;
template<typename T>
void operator() (T & x) const {
x(_bo);
}
};
// we use optimal named template parameters
// see: http://www.boost.org/doc/libs/1_55_0/libs/parameter/doc/html/index.html#parameter-enabled-class-templates
BOOST_PARAMETER_TEMPLATE_KEYWORD(inneropt_fun)
BOOST_PARAMETER_TEMPLATE_KEYWORD(init_fun)
BOOST_PARAMETER_TEMPLATE_KEYWORD(acq_fun)
BOOST_PARAMETER_TEMPLATE_KEYWORD(model_fun)
BOOST_PARAMETER_TEMPLATE_KEYWORD(stat_fun)
BOOST_PARAMETER_TEMPLATE_KEYWORD(stop_fun)
BOOST_PARAMETER_TEMPLATE_KEYWORD(obs_type)
typedef boost::parameter::parameters <
boost::parameter::optional<tag::inneropt_fun>
, boost::parameter::optional<tag::stat_fun>
, boost::parameter::optional<tag::init_fun>
, boost::parameter::optional<tag::acq_fun>
, boost::parameter::optional<tag::stop_fun>
, boost::parameter::optional<tag::model_fun>
, boost::parameter::optional<tag::obs_type>
> class_signature;
template <
class Params
, class A1 = boost::parameter::void_
, class A2 = boost::parameter::void_
, class A3 = boost::parameter::void_
, class A4 = boost::parameter::void_
, class A5 = boost::parameter::void_
, class A6 = boost::parameter::void_
, class A7 = boost::parameter::void_