mahf 0.1.0

A framework for modular construction and evaluation of metaheuristics.
Documentation
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Components for Chemical Reaction Optimization (CRO).

use better_any::{Tid, TidAble};
use derive_more::{Deref, DerefMut};
use eyre::{ensure, eyre, ContextCompat, WrapErr};
use rand::{distributions::Uniform, Rng};
use rand_distr::Distribution;
use serde::Serialize;

use crate::{
    component::ExecResult, components::Component, population::IntoSingle,
    problems::SingleObjectiveProblem, state::StateReq, CustomState, Individual, Problem, State,
};

/// A molecule with metadata.
#[derive(Clone)]
pub struct Molecule<P: Problem> {
    pub kinetic_energy: f64,
    pub num_hit: u32,
    pub min_hit: u32,
    pub best: Individual<P>,
}

impl<P: Problem> Molecule<P> {
    pub fn new(initial_kinetic_energy: f64, individual: Individual<P>) -> Self {
        Self {
            kinetic_energy: initial_kinetic_energy,
            num_hit: 0,
            min_hit: 0,
            best: individual,
        }
    }
}

impl<P: SingleObjectiveProblem> Molecule<P> {
    pub fn update_best(&mut self, individual: &Individual<P>) -> bool {
        if individual.objective() < self.best.objective() {
            self.best = individual.clone();
            self.min_hit = self.num_hit;
            true
        } else {
            false
        }
    }
}

/// A chemical reaction with multiple molecules.
#[derive(Deref, DerefMut, Tid)]
pub struct ChemicalReaction<P: Problem + 'static>(pub Vec<Molecule<P>>);

impl<P: Problem> Default for ChemicalReaction<P> {
    fn default() -> Self {
        Self(Vec::new())
    }
}

impl<P: Problem> CustomState<'_> for ChemicalReaction<P> {}

/// The energy of the [`ChemicalReaction`].
#[derive(Deref, DerefMut, Tid)]
pub struct EnergyBuffer(pub f64);

impl CustomState<'_> for EnergyBuffer {}

/// Initializes the [`ChemicalReaction`] using the population and `kinetic_energy`.
///
/// The `buffer` is used as [`EnergyBuffer`] for the reaction.
#[derive(Clone, Serialize)]
pub struct ChemicalReactionInit {
    kinetic_energy: f64,
    buffer: f64,
}

impl ChemicalReactionInit {
    pub fn from_params(kinetic_energy: f64, buffer: f64) -> Self {
        Self {
            kinetic_energy,
            buffer,
        }
    }

    pub fn new<P: SingleObjectiveProblem>(
        kinetic_energy: f64,
        buffer: f64,
    ) -> Box<dyn Component<P>> {
        Box::new(Self::from_params(kinetic_energy, buffer))
    }
}

impl<P> Component<P> for ChemicalReactionInit
where
    P: SingleObjectiveProblem,
{
    fn init(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        state.insert(ChemicalReaction::<P>::default());
        state.insert(EnergyBuffer(self.buffer));
        Ok(())
    }

    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        *state.borrow_value_mut::<ChemicalReaction<P>>() = state
            .populations()
            .current()
            .iter()
            .map(|i| Molecule::new(self.kinetic_energy, i.clone()))
            .collect();
        Ok(())
    }
}

/// Updates state after an OnWallIneffectiveCollision.
///
/// Originally proposed for, and used as operator in [`cro`].
///
/// [`cro`]: crate::heuristics::cro
///
/// Updates the [`EnergyBuffer`] and molecule data in [`ChemicalReaction`].
///
/// # Population stack
///
/// It assumes the following [`Populations`] structure:
/// - One mutated individual i'
/// - One selected individual i
/// - Population
///
/// Note that this component does **not** perform the operation, but only updates state afterwards.
///
/// [`Populations`]: crate::state::common::Populations
#[derive(Clone, Serialize)]
pub struct OnWallIneffectiveCollisionUpdate {
    /// The kinetic energy loss rate.
    pub kinetic_energy_lr: f64,
}

impl OnWallIneffectiveCollisionUpdate {
    pub fn from_params(kinetic_energy_lr: f64) -> Self {
        Self { kinetic_energy_lr }
    }

    pub fn new<P: SingleObjectiveProblem>(kinetic_energy_lr: f64) -> Box<dyn Component<P>> {
        Box::new(Self::from_params(kinetic_energy_lr))
    }
}

impl<P> Component<P> for OnWallIneffectiveCollisionUpdate
where
    P: SingleObjectiveProblem,
{
    fn require(&self, _problem: &P, state_req: &StateReq<P>) -> ExecResult<()> {
        state_req.require::<Self, ChemicalReaction<P>>()?;
        state_req.require::<Self, EnergyBuffer>()?;
        Ok(())
    }

    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        let mut reaction = state.borrow_mut::<ChemicalReaction<P>>();
        let mut buffer = state.borrow_value_mut::<EnergyBuffer>();

        // Get reaction reactant `r` and product `p`
        ensure!(
            populations.len() >= 3,
            "invalid population stack layout for this component"
        );
        let p = populations
            .pop()
            .into_single()
            .wrap_err("expected a single individual as product")?;
        let r = populations
            .pop()
            .into_single()
            .wrap_err("expected a single individual as reactant")?;

        let r_idx = populations
            .current()
            .iter()
            .position(|i| i == &r)
            .wrap_err("couldn't find reactant in population")?;
        reaction[r_idx].num_hit += 1;

        let total_reactant_energy = r.objective().value() + reaction[r_idx].kinetic_energy;
        let product_energy = p.objective().value();

        // Reaction is possible
        if total_reactant_energy >= product_energy {
            let alpha = rng.gen_range(self.kinetic_energy_lr..1.0);

            // Update buffer
            *buffer += (total_reactant_energy - product_energy) * (1. - alpha);

            // Update best with new
            reaction[r_idx].update_best(&p);

            // Replace individual
            reaction[r_idx].kinetic_energy = (total_reactant_energy - product_energy) * alpha;
            populations.current_mut()[r_idx] = p;
        }
        Ok(())
    }
}

/// Updates state after a Decomposition.
///
/// Originally proposed for, and used as operator in [`cro`].
///
/// [`cro`]: crate::heuristics::cro
///
/// Updates the [`EnergyBuffer`] and molecule data in [`ChemicalReaction`].
///
/// # Population stack
///
/// It assumes the following [`Populations`] structure:
/// - Two mutated individuals i' and i''
/// - One selected individual i
/// - Population
///
/// Note that this component does **not** perform the operation, but only updates state afterwards.
///
/// [`Populations`]: crate::state::common::Populations
#[derive(Clone, Serialize)]
pub struct DecompositionUpdate;

impl DecompositionUpdate {
    pub fn from_params() -> Self {
        Self
    }

    pub fn new<P: SingleObjectiveProblem>() -> Box<dyn Component<P>> {
        Box::new(Self::from_params())
    }
}

impl<P> Component<P> for DecompositionUpdate
where
    P: SingleObjectiveProblem,
{
    fn require(&self, _problem: &P, state_req: &StateReq<P>) -> ExecResult<()> {
        state_req.require::<Self, ChemicalReaction<P>>()?;
        state_req.require::<Self, EnergyBuffer>()?;
        Ok(())
    }

    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        let mut reaction = state.borrow_mut::<ChemicalReaction<P>>();
        let mut buffer = state.borrow_value_mut::<EnergyBuffer>();

        // Get reaction reactant `r` and products `p1`, `p2`
        ensure!(
            populations.len() >= 3,
            "invalid population stack layout for this component"
        );
        let [p1, p2]: [_; 2] = populations
            .pop()
            .try_into()
            .map_err(|_| eyre!("expected two individuals as products"))?;
        let r = populations
            .pop()
            .into_single()
            .wrap_err("expected a single individual as reactant")?;

        let r_idx = populations
            .current()
            .iter()
            .position(|i| i == &r)
            .wrap_err("couldn't find reactant in population")?;

        let total_reactant_energy = r.objective().value() + reaction[r_idx].kinetic_energy;
        let products_energy = p1.objective().value() + p2.objective().value();

        let decomposition_energy = if total_reactant_energy >= products_energy {
            total_reactant_energy - products_energy
        } else {
            let deltas: f64 = Uniform::new(0., 1.)
                .sample_iter(&mut *rng)
                .take(2)
                .product();
            let decomposition_energy = total_reactant_energy + deltas * *buffer - products_energy;

            // Not enough energy for reaction even with buffer, so abort
            if decomposition_energy < 0. {
                reaction[r_idx].num_hit += 1;
                return Ok(());
            }

            *buffer *= 1. - deltas;
            decomposition_energy
        };

        // Initialize molecule data and insert new individuals
        let d3 = rng.gen_range(0.0..=1.0);

        reaction[r_idx] = Molecule::new(decomposition_energy * d3, p1.clone());
        reaction.push(Molecule::new(decomposition_energy * (1. - d3), p2.clone()));

        let population = populations.current_mut();
        population[r_idx] = p1;
        population.push(p2);
        Ok(())
    }
}

/// Updates state after an IntermolecularIneffectiveCollision.
///
/// Originally proposed for, and used as operator in [`cro`].
///
/// [`cro`]: crate::heuristics::cro
///
/// Updates the [`EnergyBuffer`] and molecule data in [`ChemicalReaction`].
///
/// # Population stack
///
/// It assumes the following [`Populations`] structure:
/// - Two mutated individuals i' and j'
/// - Two selected individuals i and j
/// - Population
///
/// Note that this component does **not** perform the operation, but only updates state afterwards.
///
/// [`Populations`]: crate::state::common::Populations
#[derive(Debug, serde::Serialize, Clone)]
pub struct IntermolecularIneffectiveCollisionUpdate;

impl IntermolecularIneffectiveCollisionUpdate {
    pub fn from_params() -> Self {
        Self
    }

    pub fn new<P: SingleObjectiveProblem>() -> Box<dyn Component<P>> {
        Box::new(Self::from_params())
    }
}

impl<P> Component<P> for IntermolecularIneffectiveCollisionUpdate
where
    P: SingleObjectiveProblem,
{
    fn require(&self, _problem: &P, state_req: &StateReq<P>) -> ExecResult<()> {
        state_req.require::<Self, ChemicalReaction<P>>()?;
        state_req.require::<Self, EnergyBuffer>()?;
        Ok(())
    }

    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();
        let mut rng = state.random_mut();

        let mut reaction = state.borrow_mut::<ChemicalReaction<P>>();

        // Get reaction reactants `r1`, `r2` and products `p1`, `p2`
        ensure!(
            populations.len() >= 3,
            "invalid population stack layout for this component"
        );

        let [p1, p2]: [_; 2] = populations
            .pop()
            .try_into()
            .map_err(|_| eyre!("expected two individuals as products"))?;
        let [r1, r2]: [_; 2] = populations
            .pop()
            .try_into()
            .map_err(|_| eyre!("expected two individuals as reactants"))?;

        let r1_idx = populations
            .current()
            .iter()
            .position(|i| i == &r1)
            .wrap_err("couldn't find reactant in population")?;
        let r2_idx = populations
            .current()
            .iter()
            .position(|i| i == &r2)
            .wrap_err("couldn't find reactant in population")?;
        ensure!(
            r1_idx != r2_idx,
            "the same molecule can't be used as two reactants"
        );

        reaction[r1_idx].num_hit += 1;
        reaction[r2_idx].num_hit += 1;

        let total_r1_energy = r1.objective().value() + reaction[r1_idx].kinetic_energy;
        let total_r2_energy = r2.objective().value() + reaction[r2_idx].kinetic_energy;
        let total_reactants_energy = total_r1_energy + total_r2_energy;

        let p1_energy = p1.objective().value();
        let p2_energy = p2.objective().value();
        let products_energy = p1_energy + p2_energy;

        let collision_energy = total_reactants_energy - products_energy;

        // Reaction is possible
        if collision_energy >= 0. {
            let d4 = rng.gen_range(0.0..=1.0);

            // Update kinetic energies
            reaction[r1_idx].kinetic_energy = collision_energy * d4;
            reaction[r2_idx].kinetic_energy = collision_energy * (1. - d4);

            // Update best with new
            reaction[r1_idx].update_best(&p1);
            reaction[r2_idx].update_best(&p2);

            // Replace individual
            let population = populations.current_mut();
            population[r1_idx] = p1;
            population[r2_idx] = p2;
        }

        Ok(())
    }
}

/// Updates state after a Synthesis.
///
/// Originally proposed for, and used as operator in [`cro`].
///
/// [`cro`]: crate::heuristics::cro
///
/// Updates the [`EnergyBuffer`] and molecule data in [`ChemicalReaction`].
///
/// # Population stack
///
/// It assumes the following [`Populations`] structure:
/// - One combined individual k
/// - Two selected individuals i and j
/// - Population
///
/// Note that this component does **not** perform the operation, but only updates state afterwards.
///
/// [`Populations`]: crate::state::common::Populations
#[derive(Clone, Serialize)]
pub struct SynthesisUpdate;

impl SynthesisUpdate {
    pub fn from_params() -> Self {
        Self
    }

    pub fn new<P: SingleObjectiveProblem>() -> Box<dyn Component<P>> {
        Box::new(Self::from_params())
    }
}

impl<P> Component<P> for SynthesisUpdate
where
    P: SingleObjectiveProblem,
{
    fn require(&self, _problem: &P, state_req: &StateReq<P>) -> ExecResult<()> {
        state_req.require::<Self, ChemicalReaction<P>>()?;
        state_req.require::<Self, EnergyBuffer>()?;
        Ok(())
    }

    fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
        let mut populations = state.populations_mut();

        let mut reaction = state.borrow_mut::<ChemicalReaction<P>>();

        // Get reaction reactants r1, r2 and product
        ensure!(
            populations.len() >= 3,
            "invalid population stack layout for this component"
        );

        let p = populations
            .pop()
            .into_single()
            .wrap_err("expected a single individual as product")?;
        let [r1, r2]: [_; 2] = populations
            .pop()
            .try_into()
            .map_err(|_| eyre!("expected two individuals as products"))?;

        let r1_idx = populations.current().iter().position(|i| i == &r1).unwrap();
        let r2_idx = populations.current().iter().position(|i| i == &r2).unwrap();
        ensure!(
            r1_idx != r2_idx,
            "the same molecule can't be used as two reactants"
        );

        let total_r1_energy = r1.objective().value() + reaction[r1_idx].kinetic_energy;
        let total_r2_energy = r2.objective().value() + reaction[r2_idx].kinetic_energy;
        let total_reactants_energy = total_r1_energy + total_r2_energy;

        let product_energy = p.objective().value();

        // Reaction is possible
        if total_reactants_energy >= product_energy {
            // Replace one molecule and remove other
            reaction[r1_idx] = Molecule::new(total_reactants_energy - product_energy, p.clone());
            reaction.remove(r2_idx);

            // Replace one individual and remove other
            let population = populations.current_mut();
            population[r1_idx] = p;
            population.remove(r2_idx);
        }

        Ok(())
    }
}