Skip to content

Commit

Permalink
Random search
Browse files Browse the repository at this point in the history
  • Loading branch information
NAThompson committed Jan 24, 2024
1 parent 31b76ee commit 9ab5539
Show file tree
Hide file tree
Showing 8 changed files with 499 additions and 21 deletions.
2 changes: 2 additions & 0 deletions doc/math.qbk
Original file line number Diff line number Diff line change
Expand Up @@ -726,6 +726,8 @@ and as a CD ISBN 0-9504833-2-X 978-0-9504833-2-0, Classification 519.2-dc22.
[endmathpart] [/mathpart roots Root Finding Algorithms]
[mathpart optimization Optimization]
[include optimization/differential_evolution.qbk]
[include optimization/jso.qbk]
[include optimization/random_search.qbk]
[endmathpart] [/mathpart optimization Optimization]

[mathpart poly Polynomials and Rational Functions]
Expand Down
91 changes: 91 additions & 0 deletions doc/optimization/random_search.qbk
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
[/
Copyright (c) 2024 Nick Thompson
Use, modification and distribution are subject to the
Boost Software License, Version 1.0. (See accompanying file
LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
]

[section:random_search Random Search]

[heading Synopsis]

``
#include <boost/math/optimization/random_search.hpp>

namespace boost::math::optimization {

template <typename ArgumentContainer> struct random_search_parameters {
using Real = typename ArgumentContainer::value_type;
ArgumentContainer lower_bounds;
ArgumentContainer upper_bounds;
size_t max_function_calls = 0;
ArgumentContainer const * initial_guess = nullptr;
};

template <typename ArgumentContainer, class Func, class URBG>
ArgumentContainer random_search(
const Func cost_function,
random_search_parameters<ArgumentContainer> const &params,
URBG &gen,
std::invoke_result_t<Func, ArgumentContainer> target_value = std::numeric_limits<std::invoke_result_t<Func, ArgumentContainer>>::quiet_NaN(),
std::atomic<bool> *cancellation = nullptr,
std::atomic<std::invoke_result_t<Func, ArgumentContainer>> *current_minimum_cost = nullptr,
std::vector<std::pair<ArgumentContainer, std::invoke_result_t<Func, ArgumentContainer>>> *queries = nullptr);

} // namespaces
``

The `random_search` function searches for a global minimum of a function.
There is no special sauce to this algorithm-it merely blasts function calls over threads.
It's existence is justified by the "No free lunch" theorem in optimization,
which "establishes that for any algorithm, any elevated performance over one class of problems is offset by performance over another class."
In practice, it is not clear that the conditions of the NFL theorem holds,
and on test cases, `random_search` is slower and less accurate than (say) differential evolution and jSO.
However, it is often the case that rapid convergence is not the goal:
For example, we often want to spend some time exploring the cost function surface before moving to a faster converging algorithm.
In addition, random search is embarrassingly parallel, which allows us to avoid Amdahl's law-induced performance problems.


[heading Parameters]

`lower_bounds`: A container representing the lower bounds of the optimization space along each dimension. The `.size()` of the bounds should return the dimension of the problem.
`upper_bounds`: A container representing the upper bounds of the optimization space along each dimension. It should have the same size of `lower_bounds`, and each element should be >= the corresponding element of `lower_bounds`.
`max_function_calls`: Defaults to 10000*threads.
`initial_guess`: An optional guess for where we should start looking for solutions. This is provided for consistency with other optimization functions-it's not particularly useful for this function.

[heading The function]

``
template <typename ArgumentContainer, class Func, class URBG>
ArgumentContainer random_search(const Func cost_function,
random_search_parameters<ArgumentContainer> const &params,
URBG &gen,
std::invoke_result_t<Func, ArgumentContainer> value_to_reach = std::numeric_limits<std::invoke_result_t<Func, ArgumentContainer>>::quiet_NaN(),
std::atomic<bool> *cancellation = nullptr,
std::atomic<std::invoke_result_t<Func, ArgumentContainer>> *current_minimum_cost = nullptr,
std::vector<std::pair<ArgumentContainer, std::invoke_result_t<Func, ArgumentContainer>>> *queries = nullptr)
``

Parameters:

`cost_function`: The cost function to be minimized.
`params`: The parameters to the algorithm as described above.
`gen`: A uniform random bit generator, like `std::mt19937_64`.
`value_to_reach`: An optional value that, if reached, stops the optimization. This is the most robust way to terminate the calculation, but in most cases the optimal value of the cost function is unknown. If it is, use it! Physical considerations can often be used to find optimal values for cost functions.
`cancellation`: An optional atomic boolean to allow the user to stop the computation and gracefully return the best result found up to that point. N.B.: Cancellation is not immediate; the in-progress generation finishes.
`current_minimum_cost`: An optional atomic variable to store the current minimum cost during optimization. This allows developers to (e.g.) plot the progress of the minimization over time and in conjunction with the `cancellation` argument allow halting the computation when the progress stagnates.
`queries`: An optional vector to store intermediate results during optimization. This is useful for debugging and perhaps volume rendering of the objective function after the calculation is complete.

Returns:

The argument vector corresponding to the minimum cost found by the optimization.

[h4:examples Examples]

An example exhibiting graceful cancellation and progress observability can be studied in [@../../example/random_search_example.cpp random_search_example.cpp].

[h4:references References]

* D. H. Wolpert and W. G. Macready, ['No free lunch theorems for optimization.] IEEE Transactions on Evolutionary Computation, vol. 1, no. 1, pp. 67-82, April 1997, doi: 10.1109/4235.585893.

[endsect] [/section:random_search]
79 changes: 79 additions & 0 deletions example/random_search_example.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* Copyright Nick Thompson, 2024
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#if __APPLE__ || __linux__
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <future>
#include <chrono>
#include <iostream>
#include <boost/math/constants/constants.hpp>
#include <boost/math/optimization/random_search.hpp>

using boost::math::optimization::random_search_parameters;
using boost::math::optimization::random_search;
using namespace std::chrono_literals;

template <class Real> Real rastrigin(std::vector<Real> const &v) {
using std::cos;
using boost::math::constants::two_pi;
Real A = 10;
Real y = 10 * v.size();
for (auto x : v) {
y += x * x - A * cos(two_pi<Real>() * x);
}
return y;
}

std::atomic<bool> cancel = false;

void ctrl_c_handler(int){
cancel = true;
std::cout << "Cancellation requested-this could take a second . . ." << std::endl;
}

int main() {
std::cout << "Running random search on Rastrigin function (global minimum = (0,0,...,0))\n";
signal(SIGINT, ctrl_c_handler);
using ArgType = std::vector<double>;
auto params = random_search_parameters<ArgType>();
params.lower_bounds.resize(3, -5.12);
params.upper_bounds.resize(3, 5.12);
params.max_function_calls = 100000000;
// Leave one thread available to respond to ctrl-C:
params.threads = std::thread::hardware_concurrency() - 1;
std::random_device rd;
std::mt19937_64 gen(rd());

// By definition, the value of the function which a target value is provided must be <= target_value.
double target_value = 1e-3;
std::atomic<double> current_minimum_cost;
std::cout << "Hit ctrl-C to gracefully terminate the optimization." << std::endl;
auto f = [&]() {
return random_search(rastrigin<double>, params, gen, target_value, &cancel, &current_minimum_cost);
};
auto future = std::async(std::launch::async, f);
std::future_status status = future.wait_for(3ms);
while (!cancel && (status != std::future_status::ready)) {
status = future.wait_for(3ms);
std::cout << "Current cost is " << current_minimum_cost << "\r";
}

auto local_minima = future.get();
std::cout << "Local minimum is {";
for (size_t i = 0; i < local_minima.size() - 1; ++i) {
std::cout << local_minima[i] << ", ";
}
std::cout << local_minima.back() << "}.\n";
std::cout << "Final cost: " << current_minimum_cost << "\n";
}
#else
#warning "Signal handling for the random search example only works on Linux and Mac."
int main() {
return 0;
}
#endif
148 changes: 148 additions & 0 deletions include/boost/math/optimization/random_search.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*
* Copyright Nick Thompson, 2024
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_MATH_OPTIMIZATION_RANDOM_SEARCH_HPP
#define BOOST_MATH_OPTIMIZATION_RANDOM_SEARCH_HPP
#include <algorithm>
#include <array>
#include <atomic>
#include <cmath>
#include <limits>
#include <list>
#include <mutex>
#include <random>
#include <sstream>
#include <stdexcept>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
#include <boost/math/optimization/detail/common.hpp>

namespace boost::math::optimization {

template <typename ArgumentContainer> struct random_search_parameters {
using Real = typename ArgumentContainer::value_type;
ArgumentContainer lower_bounds;
ArgumentContainer upper_bounds;
size_t max_function_calls = 10000*std::thread::hardware_concurrency();
ArgumentContainer const *initial_guess = nullptr;
unsigned threads = std::thread::hardware_concurrency();
};

template <typename ArgumentContainer>
void validate_random_search_parameters(random_search_parameters<ArgumentContainer> const &params) {
using std::isfinite;
using std::isnan;
std::ostringstream oss;
detail::validate_bounds(params.lower_bounds, params.upper_bounds);
if (params.initial_guess) {
detail::validate_initial_guess(*params.initial_guess, params.lower_bounds, params.upper_bounds);
}
if (params.threads == 0) {
oss << __FILE__ << ":" << __LINE__ << ":" << __func__;
oss << ": There must be at least one thread.";
throw std::invalid_argument(oss.str());
}
}

template <typename ArgumentContainer, class Func, class URBG>
ArgumentContainer random_search(
const Func cost_function,
random_search_parameters<ArgumentContainer> const &params,
URBG &gen,
std::invoke_result_t<Func, ArgumentContainer> target_value = std::numeric_limits<std::invoke_result_t<Func, ArgumentContainer>>::quiet_NaN(),
std::atomic<bool> *cancellation = nullptr,
std::atomic<std::invoke_result_t<Func, ArgumentContainer>> *current_minimum_cost = nullptr,
std::vector<std::pair<ArgumentContainer, std::invoke_result_t<Func, ArgumentContainer>>> *queries = nullptr)
{
using Real = typename ArgumentContainer::value_type;
using ResultType = std::invoke_result_t<Func, ArgumentContainer>;
using std::isnan;
using std::uniform_real_distribution;
validate_random_search_parameters(params);
const size_t dimension = params.lower_bounds.size();
std::atomic<bool> target_attained = false;
// Unfortunately, the "minimum_cost" variable can either be passed
// (for observability) or not (if the user doesn't care).
// That makes this a bit awkward . . .
std::atomic<ResultType> lowest_cost = std::numeric_limits<ResultType>::infinity();

ArgumentContainer best_vector;
if constexpr (detail::has_resize_v<ArgumentContainer>) {
best_vector.resize(dimension, std::numeric_limits<Real>::quiet_NaN());
}
if (params.initial_guess) {
auto initial_cost = cost_function(*params.initial_guess);
if (!isnan(initial_cost)) {
lowest_cost = initial_cost;
best_vector = *params.initial_guess;
if (current_minimum_cost) {
*current_minimum_cost = initial_cost;
}
}
}
std::mutex mt;
std::vector<std::thread> thread_pool;
std::atomic<size_t> function_calls = 0;
for (unsigned j = 0; j < params.threads; ++j) {
auto seed = gen();
thread_pool.emplace_back([&, seed]() {
URBG g(seed);
ArgumentContainer trial_vector;
// This vector is empty unless the user requests the queries be stored:
std::vector<std::pair<ArgumentContainer, std::invoke_result_t<Func, ArgumentContainer>>> local_queries;
if constexpr (detail::has_resize_v<ArgumentContainer>) {
trial_vector.resize(dimension, std::numeric_limits<Real>::quiet_NaN());
}
while (function_calls < params.max_function_calls) {
if (cancellation && *cancellation) {
break;
}
if (target_attained) {
break;
}
// Fill trial vector:
uniform_real_distribution<Real> unif01(Real(0), Real(1));
for (size_t i = 0; i < dimension; ++i) {
trial_vector[i] = params.lower_bounds[i] + (params.upper_bounds[i] - params.lower_bounds[i])*unif01(g);
}
ResultType trial_cost = cost_function(trial_vector);
++function_calls;
if (isnan(trial_cost)) {
continue;
}
if (trial_cost < lowest_cost) {
lowest_cost = trial_cost;
if (current_minimum_cost) {
*current_minimum_cost = trial_cost;
}
// We expect to need to acquire this lock with decreasing frequency
// as the computation proceeds:
std::scoped_lock lock(mt);
best_vector = trial_vector;
}
if (queries) {
local_queries.push_back(std::make_pair(trial_vector, trial_cost));
}
if (!isnan(target_value) && trial_cost <= target_value) {
target_attained = true;
}
}
if (queries) {
std::scoped_lock lock(mt);
queries->insert(queries->begin(), local_queries.begin(), local_queries.end());
}
});
}
for (auto &thread : thread_pool) {
thread.join();
}
return best_vector;
}

} // namespace boost::math::optimization
#endif
1 change: 1 addition & 0 deletions test/Jamfile.v2
Original file line number Diff line number Diff line change
Expand Up @@ -1257,6 +1257,7 @@ test-suite interpolators :
[ run test_standalone_asserts.cpp ]
[ run differential_evolution_test.cpp : : : [ requires cxx17_if_constexpr cxx17_std_apply ] ]
[ run jso_test.cpp : : : [ requires cxx17_if_constexpr cxx17_std_apply ] ]
[ run random_search_test.cpp : : : [ requires cxx17_if_constexpr cxx17_std_apply ] ]
;

test-suite quadrature :
Expand Down
41 changes: 22 additions & 19 deletions test/math_unit_test.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include <iomanip>
#include <cmath> // for std::isnan
#include <string>
#include <type_traits>
#include <boost/math/tools/assert.hpp>
#include <boost/math/special_functions/next.hpp>
#include <boost/math/special_functions/trunc.hpp>
Expand Down Expand Up @@ -155,26 +156,28 @@ bool check_le(Real lesser, Real greater, std::string const & filename, std::stri
using std::abs;
using std::isnan;

if (isnan(lesser))
{
std::ios_base::fmtflags f( std::cerr.flags() );
std::cerr << std::setprecision(3);
std::cerr << "\033[0;31mError at " << filename << ":" << function << ":" << line << ":\n"
<< " \033[0m Lesser value is a nan\n";
std::cerr.flags(f);
++detail::global_error_count;
return false;
}
if (std::is_floating_point<Real>::value) {
if (isnan(lesser))
{
std::ios_base::fmtflags f( std::cerr.flags() );
std::cerr << std::setprecision(3);
std::cerr << "\033[0;31mError at " << filename << ":" << function << ":" << line << ":\n"
<< " \033[0m Lesser value is a nan\n";
std::cerr.flags(f);
++detail::global_error_count;
return false;
}

if (isnan(greater))
{
std::ios_base::fmtflags f( std::cerr.flags() );
std::cerr << std::setprecision(3);
std::cerr << "\033[0;31mError at " << filename << ":" << function << ":" << line << ":\n"
<< " \033[0m Greater value is a nan\n";
std::cerr.flags(f);
++detail::global_error_count;
return false;
if (isnan(greater))
{
std::ios_base::fmtflags f( std::cerr.flags() );
std::cerr << std::setprecision(3);
std::cerr << "\033[0;31mError at " << filename << ":" << function << ":" << line << ":\n"
<< " \033[0m Greater value is a nan\n";
std::cerr.flags(f);
++detail::global_error_count;
return false;
}
}

if (lesser > greater)
Expand Down
Loading

0 comments on commit 9ab5539

Please sign in to comment.