29template <
typename State>
45 std::function<
double(
const State&)> cost)
46 : m_initialTemperature{initialTemperature},
58 State minState = initialGuess;
59 double minCost = std::numeric_limits<double>::infinity();
61 std::random_device
rd;
62 std::mt19937 gen{
rd()};
63 std::uniform_real_distribution<> distr{0.0, 1.0};
66 double cost = m_cost(
state);
68 for (
int i = 0; i < iterations; ++i) {
69 double temperature = m_initialTemperature / i;
72 double proposedCost = m_cost(proposedState);
73 double deltaCost = proposedCost - cost;
75 double acceptanceProbability = std::exp(-deltaCost / temperature);
79 if (deltaCost < 0 || acceptanceProbability >= distr(gen)) {
80 state = proposedState;
86 if (proposedCost < minCost) {
87 minState = proposedState;
88 minCost = proposedCost;
96 double m_initialTemperature;
98 std::function<double(
const State&)> m_cost;
An implementation of the Simulated Annealing stochastic nonlinear optimization method.
Definition: SimulatedAnnealing.h:30
State Solve(const State &initialGuess, int iterations)
Runs the Simulated Annealing algorithm.
Definition: SimulatedAnnealing.h:57
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:43
state
Definition: core.h:2271
State
Possible state of a SysId routine.
Definition: SysIdRoutineLog.h:25
Definition: AprilTagPoseEstimator.h:15
compound_unit< energy::joules, inverse< mass::kilogram > > rd
Definition: radiation.h:61