22template <
typename State>
37 std::function<State(
const State&)> neighbor,
38 std::function<
double(
const State&)> cost)
39 : m_initialTemperature{initialTemperature},
50 State
Solve(
const State& initialGuess,
int iterations) {
51 State minState = initialGuess;
52 double minCost = std::numeric_limits<double>::infinity();
54 std::random_device
rd;
55 std::mt19937 gen{
rd()};
56 std::uniform_real_distribution<> distr{0.0, 1.0};
58 State
state = initialGuess;
59 double cost = m_cost(
state);
61 for (
int i = 0; i < iterations; ++i) {
62 double temperature = m_initialTemperature / i;
64 State proposedState = m_neighbor(
state);
65 double proposedCost = m_cost(proposedState);
66 double deltaCost = proposedCost - cost;
68 double acceptanceProbability = std::exp(-deltaCost / temperature);
72 if (deltaCost < 0 || acceptanceProbability >= distr(gen)) {
73 state = proposedState;
79 if (proposedCost < minCost) {
80 minState = proposedState;
81 minCost = proposedCost;
89 double m_initialTemperature;
90 std::function<State(
const State&)> m_neighbor;
91 std::function<double(
const State&)> m_cost;
An implementation of the Simulated Annealing stochastic nonlinear optimization method.
Definition: SimulatedAnnealing.h:23
State Solve(const State &initialGuess, int iterations)
Runs the Simulated Annealing algorithm.
Definition: SimulatedAnnealing.h:50
constexpr SimulatedAnnealing(double initialTemperature, std::function< State(const State &)> neighbor, std::function< double(const State &)> cost)
Constructor for Simulated Annealing that can be used for the same functions but with different initia...
Definition: SimulatedAnnealing.h:36
state
Definition: core.h:2271
Definition: AprilTagPoseEstimator.h:15
compound_unit< energy::joules, inverse< mass::kilogram > > rd
Definition: radiation.h:61