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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
use crate::prelude::*;
use serde::{Deserialize, Serialize};
use std::default::Default;
#[derive(Serialize, Deserialize)]
pub struct NelderMead<O: ArgminOp> {
alpha: f64,
gamma: f64,
rho: f64,
sigma: f64,
params: Vec<(O::Param, f64)>,
sd_tolerance: f64,
}
impl<O: ArgminOp> NelderMead<O>
where
O: ArgminOp<Output = f64>,
O::Param: Default
+ ArgminAdd<O::Param, O::Param>
+ ArgminSub<O::Param, O::Param>
+ ArgminMul<f64, O::Param>,
{
pub fn new() -> Self {
NelderMead {
alpha: 1.0,
gamma: 2.0,
rho: 0.5,
sigma: 0.5,
params: vec![],
sd_tolerance: std::f64::EPSILON,
}
}
pub fn with_initial_params(mut self, params: Vec<O::Param>) -> Self {
self.params = params.into_iter().map(|p| (p, std::f64::NAN)).collect();
self
}
pub fn sd_tolerance(mut self, tol: f64) -> Self {
self.sd_tolerance = tol;
self
}
pub fn alpha(mut self, alpha: f64) -> Result<Self, Error> {
if alpha <= 0.0 {
return Err(ArgminError::InvalidParameter {
text: "Nelder-Mead: must be > 0.".to_string(),
}
.into());
}
self.alpha = alpha;
Ok(self)
}
pub fn gamma(mut self, gamma: f64) -> Result<Self, Error> {
if gamma <= 1.0 {
return Err(ArgminError::InvalidParameter {
text: "Nelder-Mead: gamma must be > 1.".to_string(),
}
.into());
}
self.gamma = gamma;
Ok(self)
}
pub fn rho(mut self, rho: f64) -> Result<Self, Error> {
if rho <= 0.0 || rho > 0.5 {
return Err(ArgminError::InvalidParameter {
text: "Nelder-Mead: rho must be in (0.0, 0.5].".to_string(),
}
.into());
}
self.rho = rho;
Ok(self)
}
pub fn sigma(mut self, sigma: f64) -> Result<Self, Error> {
if sigma <= 0.0 || sigma > 1.0 {
return Err(ArgminError::InvalidParameter {
text: "Nelder-Mead: sigma must be in (0.0, 1.0].".to_string(),
}
.into());
}
self.sigma = sigma;
Ok(self)
}
fn sort_param_vecs(&mut self) {
self.params
.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
}
fn calculate_centroid(&self) -> O::Param {
let num_param = self.params.len() - 1;
let mut x0: O::Param = self.params[0].0.clone();
for idx in 1..num_param {
x0 = x0.add(&self.params[idx].0)
}
x0.mul(&(1.0 / (num_param as f64)))
}
fn reflect(&self, x0: &O::Param, x: &O::Param) -> O::Param {
x0.add(&x0.sub(&x).mul(&self.alpha))
}
fn expand(&self, x0: &O::Param, x: &O::Param) -> O::Param {
x0.add(&x.sub(&x0).mul(&self.gamma))
}
fn contract(&self, x0: &O::Param, x: &O::Param) -> O::Param {
x0.add(&x.sub(&x0).mul(&self.rho))
}
fn shrink<F>(&mut self, mut cost: F) -> Result<(), Error>
where
F: FnMut(&O::Param) -> Result<O::Output, Error>,
{
let mut out = Vec::with_capacity(self.params.len());
out.push(self.params[0].clone());
for idx in 1..self.params.len() {
let xi = out[0]
.0
.add(&self.params[idx].0.sub(&out[0].0).mul(&self.sigma));
let ci = (cost)(&xi)?;
out.push((xi, ci));
}
self.params = out;
Ok(())
}
}
impl<O> Solver<O> for NelderMead<O>
where
O: ArgminOp<Output = f64>,
O::Param: Default
+ std::fmt::Debug
+ ArgminScaledSub<O::Param, f64, O::Param>
+ ArgminSub<O::Param, O::Param>
+ ArgminAdd<O::Param, O::Param>
+ ArgminMul<f64, O::Param>,
{
const NAME: &'static str = "Nelder-Mead method";
fn init(
&mut self,
op: &mut OpWrapper<O>,
_state: &IterState<O>,
) -> Result<Option<ArgminIterData<O>>, Error> {
self.params = self
.params
.iter()
.cloned()
.map(|(p, _)| {
let c = op.apply(&p).unwrap();
(p, c)
})
.collect();
self.sort_param_vecs();
Ok(Some(
ArgminIterData::new()
.param(self.params[0].0.clone())
.cost(self.params[0].1),
))
}
fn next_iter(
&mut self,
op: &mut OpWrapper<O>,
_state: &IterState<O>,
) -> Result<ArgminIterData<O>, Error> {
let num_param = self.params.len();
let x0 = self.calculate_centroid();
let xr = self.reflect(&x0, &self.params[num_param - 1].0);
let xr_cost = op.apply(&xr)?;
let action = if xr_cost < self.params[num_param - 2].1 && xr_cost >= self.params[0].1 {
self.params.last_mut().unwrap().0 = xr;
self.params.last_mut().unwrap().1 = xr_cost;
"reflection"
} else if xr_cost < self.params[0].1 {
let xe = self.expand(&x0, &xr);
let xe_cost = op.apply(&xe)?;
if xe_cost < xr_cost {
self.params.last_mut().unwrap().0 = xe;
self.params.last_mut().unwrap().1 = xe_cost;
} else {
self.params.last_mut().unwrap().0 = xr;
self.params.last_mut().unwrap().1 = xr_cost;
}
"expansion"
} else if xr_cost >= self.params[num_param - 2].1 {
let xc = self.contract(&x0, &self.params[num_param - 1].0);
let xc_cost = op.apply(&xc)?;
if xc_cost < self.params[num_param - 1].1 {
self.params.last_mut().unwrap().0 = xc;
self.params.last_mut().unwrap().1 = xc_cost;
}
"contraction"
} else {
self.shrink(|x| op.apply(x))?;
"shrink"
};
self.sort_param_vecs();
Ok(ArgminIterData::new()
.param(self.params[0].0.clone())
.cost(self.params[0].1)
.kv(make_kv!("action" => action;)))
}
fn terminate(&mut self, _state: &IterState<O>) -> TerminationReason {
let n = self.params.len() as f64;
let c0: f64 = self.params.iter().map(|(_, c)| c).sum::<f64>() / n;
let s: f64 = (1.0 / (n - 1.0)
* self
.params
.iter()
.map(|(_, c)| (c - c0).powi(2))
.sum::<f64>())
.sqrt();
if s < self.sd_tolerance {
return TerminationReason::TargetToleranceReached;
}
TerminationReason::NotTerminated
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::send_sync_test;
type Operator = MinimalNoOperator;
send_sync_test!(nelder_mead, NelderMead<Operator>);
}