1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
use rand;
use rand::distributions::{IndependentSample, Range};
use errors::*;
use prelude::*;
use problem::ArgminProblem;
use result::ArgminResult;
use termination::TerminationReason;
pub enum SATempFunc {
TemperatureFast,
Boltzmann,
Exponential(f64),
Custom,
}
pub struct SimulatedAnnealing<'a, T, U, V = U>
where
T: ArgminParameter + 'a,
U: ArgminCostValue + 'a,
V: 'a,
{
pub init_temp: f64,
pub max_iters: u64,
pub temp_func: SATempFunc,
pub custom_temp_func: Option<&'a Fn(f64, u64) -> f64>,
pub state: Option<SimulatedAnnealingState<'a, T, U, V>>,
}
pub struct SimulatedAnnealingState<'a, T, U, V>
where
T: ArgminParameter + 'a,
U: ArgminCostValue + 'a,
V: 'a,
{
problem: &'a ArgminProblem<'a, T, U, V>,
param: T,
iter: u64,
cur_temp: f64,
prev_cost: U,
best_param: T,
best_cost: U,
}
impl<'a, T, U, V> SimulatedAnnealing<'a, T, U, V>
where
T: ArgminParameter,
U: ArgminCostValue,
V: 'a,
{
pub fn new(init_temp: f64, max_iters: u64) -> Result<Self> {
if init_temp <= 0_f64 {
Err(
ErrorKind::InvalidParameter("SimulatedAnnealing: Temperature must be > 0.".into())
.into(),
)
} else {
Ok(SimulatedAnnealing {
init_temp: init_temp,
max_iters: max_iters,
temp_func: SATempFunc::TemperatureFast,
custom_temp_func: None,
state: None,
})
}
}
pub fn temp_func(&mut self, temperature_func: SATempFunc) -> &mut Self {
self.temp_func = temperature_func;
self
}
pub fn custom_temp_func(&mut self, func: &'a Fn(f64, u64) -> f64) -> &mut Self {
self.temp_func = SATempFunc::Custom;
self.custom_temp_func = Some(func);
self
}
fn accept(&self, state: &SimulatedAnnealingState<T, U, V>, next_cost: f64) -> bool {
let prev_cost = state.prev_cost.to_f64().unwrap();
let step = Range::new(0.0, 1.0);
let mut rng = rand::thread_rng();
let prob: f64 = step.ind_sample(&mut rng);
(next_cost < prev_cost)
|| (1_f64 / (1_f64 + ((next_cost - prev_cost) / state.cur_temp).exp()) > prob)
}
fn update_temperature(&self, iter: u64) -> Result<f64> {
match self.temp_func {
SATempFunc::TemperatureFast => Ok(self.init_temp / ((iter + 1) as f64)),
SATempFunc::Boltzmann => Ok(self.init_temp / ((iter + 1) as f64).ln()),
SATempFunc::Exponential(x) => if x < 1_f64 && x > 0_f64 {
Ok(self.init_temp * x.powf((iter + 1) as f64))
} else {
Err(ErrorKind::InvalidParameter(
"SimulatedAnnealing: Parameter for exponential \
temperature update function needs to be >0 and <1."
.into(),
).into())
},
SATempFunc::Custom => match self.custom_temp_func {
Some(func) => Ok(func(self.init_temp, iter)),
None => Err(ErrorKind::InvalidParameter(
"SimulatedAnnealing: No custom temperature update function provided.".into(),
).into()),
},
}
}
}
impl<'a, T, U, V> ArgminSolver<'a> for SimulatedAnnealing<'a, T, U, V>
where
T: ArgminParameter + 'a,
U: ArgminCostValue + 'a,
V: 'a,
{
type Parameter = T;
type CostValue = U;
type Hessian = V;
type StartingPoints = T;
type ProblemDefinition = ArgminProblem<'a, Self::Parameter, Self::CostValue, Self::Hessian>;
fn init(
&mut self,
problem: &'a Self::ProblemDefinition,
init_param: &Self::StartingPoints,
) -> Result<()> {
let prev_cost = (problem.cost_function)(init_param);
self.state = Some(SimulatedAnnealingState {
problem: problem,
param: init_param.to_owned(),
iter: 0_u64,
cur_temp: self.init_temp,
prev_cost: prev_cost,
best_param: init_param.to_owned(),
best_cost: prev_cost,
});
Ok(())
}
fn next_iter(&mut self) -> Result<ArgminResult<Self::Parameter, Self::CostValue>> {
let mut state = self.state.take().unwrap();
let mut param_new = state.param.modify().0;
for _ in 0..(state.cur_temp.floor() as u64) {
param_new = param_new.modify().0;
param_new = match (&state.problem.lower_bound, &state.problem.upper_bound) {
(&Some(ref l), &Some(ref u)) => {
let (mut tmp, idx) = param_new.modify();
if tmp[idx] < l[idx] {
tmp[idx] = l[idx].clone();
}
if tmp[idx] > u[idx] {
tmp[idx] = u[idx].clone();
}
tmp
}
_ => param_new.modify().0,
}
}
let new_cost = (state.problem.cost_function)(¶m_new);
if self.accept(&state, new_cost.to_f64().unwrap()) {
state.prev_cost = new_cost;
state.param = param_new.clone();
if new_cost < state.best_cost {
state.best_cost = new_cost;
state.best_param = param_new;
}
}
let cur_iter = state.iter;
state.cur_temp = self.update_temperature(cur_iter)?;
state.iter += 1;
let mut out = ArgminResult::new(state.param.clone(), state.best_cost, state.iter);
self.state = Some(state);
out.set_termination_reason(self.terminate());
Ok(out)
}
make_terminate!(self,
self.state.as_ref().unwrap().iter >= self.max_iters, TerminationReason::MaxItersReached;
self.state.as_ref().unwrap().best_cost <= self.state.as_ref().unwrap().problem.target_cost, TerminationReason::TargetCostReached;
);
make_run!(
Self::ProblemDefinition,
Self::StartingPoints,
Self::Parameter,
Self::CostValue
);
}