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
use crate::prelude::*;
use argmin_core::ArgminAdd;
use argmin_core::ArgminOp;
use serde::{Deserialize, Serialize};
use std;
use std::default::Default;
use std::f64;
type Callback<T> = FnMut(&T, f64, &Vec<Particle<T>>) -> ();
#[derive(Serialize, Deserialize)]
pub struct ParticleSwarm<'a, O>
where
O: ArgminOp<Output = f64>,
<O as ArgminOp>::Param: Position,
{
cost_function: O,
#[serde(skip)]
iter_callback: Option<&'a mut Callback<O::Param>>,
particles: Vec<Particle<O::Param>>,
best_position: O::Param,
best_cost: f64,
weight_momentum: f64,
weight_particle: f64,
weight_swarm: f64,
search_region: (O::Param, O::Param),
}
impl<'a, O> ParticleSwarm<'a, O>
where
O: ArgminOp<Output = f64>,
<O as ArgminOp>::Param: Position,
{
pub fn new(
cost_function: O,
search_region: (O::Param, O::Param),
num_particles: usize,
weight_momentum: f64,
weight_particle: f64,
weight_swarm: f64,
) -> Result<Self, Error> {
let mut particle_swarm = ParticleSwarm {
cost_function: cost_function.clone(),
iter_callback: None,
particles: vec![],
best_position: O::Param::rand_from_range(
&search_region.0,
&search_region.1,
),
best_cost: f64::INFINITY,
weight_momentum,
weight_particle,
weight_swarm,
search_region,
};
let mut op = OpWrapper::new(&cost_function);
particle_swarm.initialize_particles(&mut op, num_particles);
Ok(particle_swarm)
}
pub fn set_iter_callback(&mut self, callback: &'a mut Callback<O::Param>) {
self.iter_callback = Some(callback);
}
fn initialize_particles(&mut self, op: &mut OpWrapper<O>, num_particles: usize) {
self.particles = (0..num_particles)
.map(|_| self.initialize_particle(op))
.collect();
self.best_position = self.get_best_position();
self.best_cost = self.cost_function.apply(&self.best_position).unwrap();
}
fn initialize_particle(&mut self, op: &mut OpWrapper<O>) -> Particle<O::Param> {
let (min, max) = &self.search_region;
let delta = max.sub(min);
let delta_neg = delta.mul(&-1.0);
let initial_position = O::Param::rand_from_range(min, max);
let initial_cost = op.apply(&initial_position).unwrap();
Particle {
position: initial_position.clone(),
velocity: O::Param::rand_from_range(&delta_neg, &delta),
cost: initial_cost,
best_position: initial_position,
best_cost: initial_cost,
}
}
fn get_best_position(&self) -> O::Param {
let mut best: Option<(&O::Param, f64)> = None;
for p in &self.particles {
match best {
Some(best_sofar) => {
if p.cost < best_sofar.1 {
best = Some((&p.position, p.cost))
}
}
None => best = Some((&p.position, p.cost)),
}
}
match best {
Some(best_sofar) => best_sofar.0.clone(),
None => panic!("Particles not initialized"),
}
}
}
impl<'a, O> Solver<O> for ParticleSwarm<'a, O>
where
O: ArgminOp<Output = f64>,
<O as ArgminOp>::Param: Position,
<O as ArgminOp>::Hessian: Clone + Default,
{
const NAME: &'static str = "Particle Swarm Optimization";
fn next_iter(
&mut self,
_op: &mut OpWrapper<O>,
_state: &IterState<O>,
) -> Result<ArgminIterData<O>, Error> {
let zero = O::Param::zero_like(&self.best_position);
for p in self.particles.iter_mut() {
let momentum = p.velocity.mul(&self.weight_momentum);
let to_optimum = p.best_position.sub(&p.position);
let pull_to_optimum = O::Param::rand_from_range(&zero, &to_optimum);
let pull_to_optimum = pull_to_optimum.mul(&self.weight_particle);
let to_global_optimum = self.best_position.sub(&p.position);
let pull_to_global_optimum =
O::Param::rand_from_range(&zero, &to_global_optimum).mul(&self.weight_swarm);
p.velocity = momentum.add(&pull_to_optimum).add(&pull_to_global_optimum);
let new_position = p.position.add(&p.velocity);
p.position = O::Param::min(
&O::Param::max(&new_position, &self.search_region.0),
&self.search_region.1,
);
p.cost = self.cost_function.apply(&p.position)?;
if p.cost < p.best_cost {
p.best_position = p.position.clone();
p.best_cost = p.cost;
if p.cost < self.best_cost {
self.best_position = p.position.clone();
self.best_cost = p.cost;
}
}
}
match &mut self.iter_callback {
Some(callback) => (*callback)(&self.best_position, self.best_cost, &self.particles),
None => (),
};
let out = ArgminIterData::new()
.param(self.best_position.clone())
.cost(self.best_cost);
Ok(out)
}
}
trait_bound!(Position
; Clone
, Default
, ArgminAdd<Self, Self>
, ArgminSub<Self, Self>
, ArgminMul<f64, Self>
, ArgminZeroLike
, ArgminRandom
, ArgminMinMax
, std::fmt::Debug
);
#[derive(Serialize, Deserialize)]
pub struct Particle<T: Position> {
pub position: T,
velocity: T,
pub cost: f64,
best_position: T,
best_cost: f64,
}