optimal-pbil 0.0.0

Implementation of population-based incremental learning (PBIL)
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
#![allow(clippy::needless_doctest_main)]
#![warn(missing_debug_implementations)]
// `missing_docs` does not work with `IsVariant`,
// see <https://github.com/JelteF/derive_more/issues/215>.
// #![warn(missing_docs)]

//! Population-based incremental learning (PBIL).
//!
//! # Examples
//!
//! ```
//! use optimal_pbil::*;
//!
//! println!(
//!     "{:?}",
//!     UntilProbabilitiesConvergedConfig::default()
//!         .start(Config::start_default_for(16, |point| point.iter().filter(|x| **x).count()))
//!         .argmin()
//! );
//! ```

mod state_machine;
mod types;
mod until_probabilities_converged;

use derive_getters::{Dissolve, Getters};
use derive_more::IsVariant;
pub use optimal_core::prelude::*;
use rand::prelude::*;
use rand_xoshiro::{SplitMix64, Xoshiro256PlusPlus};

use self::state_machine::DynState;
pub use self::{types::*, until_probabilities_converged::*};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Error returned when
/// problem length does not match state length.
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq)]
#[error("problem length does not match state length")]
pub struct MismatchedLengthError;

/// A running PBIL optimizer.
#[derive(Clone, Debug, Getters, Dissolve)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[dissolve(rename = "into_parts")]
pub struct Pbil<B, F> {
    /// Optimizer configuration.
    config: Config,

    /// State of optimizer.
    state: State<B>,

    /// Objective function to minimize.
    obj_func: F,
}

/// PBIL configuration parameters.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Config {
    /// Number of samples generated
    /// during steps.
    pub num_samples: NumSamples,
    /// Degree to adjust probabilities towards best point
    /// during steps.
    pub adjust_rate: AdjustRate,
    /// Probability for each probability to mutate,
    /// independently.
    pub mutation_chance: MutationChance,
    /// Degree to adjust probability towards random value
    /// when mutating.
    pub mutation_adjust_rate: MutationAdjustRate,
}

/// PBIL state.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct State<B>(DynState<B>);

/// PBIL state kind.
#[derive(Clone, Debug, PartialEq, IsVariant)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum StateKind {
    /// Iteration started.
    Started,
    /// Sample generated.
    Sampled,
    /// Sample evaluated.
    Evaluated,
    /// Samples compared.
    Compared,
    /// Probabilities adjusted.
    Adjusted,
    /// Probabilities mutated.
    Mutated,
    /// Iteration finished.
    Finished,
}

impl<B, F> Pbil<B, F> {
    fn new(state: State<B>, config: Config, obj_func: F) -> Self {
        Self {
            config,
            obj_func,
            state,
        }
    }
}

impl<B, F> Pbil<B, F>
where
    F: Fn(&[bool]) -> B,
{
    /// Return value of the best point discovered.
    pub fn best_point_value(&self) -> B {
        (self.obj_func)(&self.best_point())
    }
}

impl<B, F> StreamingIterator for Pbil<B, F>
where
    B: PartialOrd,
    F: Fn(&[bool]) -> B,
{
    type Item = Self;

    fn advance(&mut self) {
        replace_with::replace_with_or_abort(&mut self.state.0, |state| match state {
            DynState::Started(x) => {
                DynState::SampledFirst(x.into_initialized_sampling().into_sampled_first())
            }
            DynState::SampledFirst(x) => {
                DynState::EvaluatedFirst(x.into_evaluated_first(&self.obj_func))
            }
            DynState::EvaluatedFirst(x) => DynState::Sampled(x.into_sampled()),
            DynState::Sampled(x) => DynState::Evaluated(x.into_evaluated(&self.obj_func)),
            DynState::Evaluated(x) => DynState::Compared(x.into_compared()),
            DynState::Compared(x) => {
                if x.samples_generated < self.config.num_samples.into_inner() {
                    DynState::Sampled(x.into_sampled())
                } else {
                    DynState::Adjusted(x.into_adjusted(self.config.adjust_rate))
                }
            }
            DynState::Adjusted(x) => {
                if self.config.mutation_chance.into_inner() > 0.0 {
                    DynState::Mutated(x.into_mutated(
                        self.config.mutation_chance,
                        self.config.mutation_adjust_rate,
                    ))
                } else {
                    DynState::Finished(x.into_finished())
                }
            }
            DynState::Mutated(x) => DynState::Finished(x.into_finished()),
            DynState::Finished(x) => DynState::Started(x.into_started()),
        });
    }

    fn get(&self) -> Option<&Self::Item> {
        Some(self)
    }
}

impl<B, F> Optimizer for Pbil<B, F> {
    type Point = Vec<bool>;

    fn best_point(&self) -> Self::Point {
        self.state.best_point()
    }
}

impl Config {
    /// Return a new PBIL configuration.
    pub fn new(
        num_samples: NumSamples,
        adjust_rate: AdjustRate,
        mutation_chance: MutationChance,
        mutation_adjust_rate: MutationAdjustRate,
    ) -> Self {
        Self {
            num_samples,
            adjust_rate,
            mutation_chance,
            mutation_adjust_rate,
        }
    }
}

impl Config {
    /// Return default 'Config'.
    pub fn default_for(num_bits: usize) -> Self {
        Self {
            num_samples: NumSamples::default(),
            adjust_rate: AdjustRate::default(),
            mutation_chance: MutationChance::default_for(num_bits),
            mutation_adjust_rate: MutationAdjustRate::default(),
        }
    }

    /// Return this optimizer default
    /// running on the given problem.
    ///
    /// # Arguments
    ///
    /// - `len`: number of bits in each point
    /// - `obj_func`: objective function to minimize
    pub fn start_default_for<B, F>(len: usize, obj_func: F) -> Pbil<B, F>
    where
        F: Fn(&[bool]) -> B,
    {
        Self::default_for(len).start(len, obj_func)
    }

    /// Return this optimizer
    /// running on the given problem.
    ///
    /// This may be nondeterministic.
    ///
    /// # Arguments
    ///
    /// - `len`: number of bits in each point
    /// - `obj_func`: objective function to minimize
    pub fn start<B, F>(self, len: usize, obj_func: F) -> Pbil<B, F>
    where
        F: Fn(&[bool]) -> B,
    {
        Pbil::new(State::initial(len), self, obj_func)
    }

    /// Return this optimizer
    /// running on the given problem
    /// initialized using `rng`.
    ///
    /// # Arguments
    ///
    /// - `len`: number of bits in each point
    /// - `obj_func`: objective function to minimize
    /// - `rng`: source of randomness
    pub fn start_using<B, F>(self, len: usize, obj_func: F, rng: &mut SplitMix64) -> Pbil<B, F>
    where
        F: Fn(&[bool]) -> B,
    {
        Pbil::new(State::initial_using(len, rng), self, obj_func)
    }

    /// Return this optimizer
    /// running on the given problem.
    /// if the given `state` is valid.
    ///
    /// # Arguments
    ///
    /// - `obj_func`: objective function to minimize
    /// - `state`: PBIL state to start from
    pub fn start_from<B, F>(self, obj_func: F, state: State<B>) -> Pbil<B, F>
    where
        F: Fn(&[bool]) -> B,
    {
        Pbil::new(state, self, obj_func)
    }
}

impl<B> State<B> {
    /// Return recommended initial state.
    ///
    /// # Arguments
    ///
    /// - `len`: number of bits in each sample
    fn initial(len: usize) -> Self {
        Self::new(
            [Probability::default()].repeat(len),
            Xoshiro256PlusPlus::from_entropy(),
        )
    }

    /// Return recommended initial state.
    ///
    /// # Arguments
    ///
    /// - `len`: number of bits in each sample
    /// - `rng`: source of randomness
    fn initial_using<R>(len: usize, rng: R) -> Self
    where
        R: Rng,
    {
        Self::new(
            [Probability::default()].repeat(len),
            Xoshiro256PlusPlus::from_rng(rng).expect("RNG should initialize"),
        )
    }

    /// Return custom initial state.
    pub fn new(probabilities: Vec<Probability>, rng: Xoshiro256PlusPlus) -> Self {
        Self(DynState::new(probabilities, rng))
    }

    /// Return number of bits being optimized.
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> usize {
        self.probabilities().len()
    }

    /// Return data to be evaluated.
    pub fn evaluatee(&self) -> Option<&[bool]> {
        match &self.0 {
            DynState::Started(_) => None,
            DynState::SampledFirst(x) => Some(&x.sample),
            DynState::EvaluatedFirst(_) => None,
            DynState::Sampled(x) => Some(&x.sample),
            DynState::Evaluated(_) => None,
            DynState::Compared(_) => None,
            DynState::Adjusted(_) => None,
            DynState::Mutated(_) => None,
            DynState::Finished(_) => None,
        }
    }

    /// Return result of evaluation.
    pub fn evaluation(&self) -> Option<&B> {
        match &self.0 {
            DynState::Started(_) => None,
            DynState::SampledFirst(_) => None,
            DynState::EvaluatedFirst(x) => Some(x.sample.value()),
            DynState::Sampled(_) => None,
            DynState::Evaluated(x) => Some(x.sample.value()),
            DynState::Compared(_) => None,
            DynState::Adjusted(_) => None,
            DynState::Mutated(_) => None,
            DynState::Finished(_) => None,
        }
    }

    /// Return sample if stored.
    pub fn sample(&self) -> Option<&[bool]> {
        match &self.0 {
            DynState::Started(_) => None,
            DynState::SampledFirst(x) => Some(&x.sample),
            DynState::EvaluatedFirst(x) => Some(x.sample.x()),
            DynState::Sampled(x) => Some(&x.sample),
            DynState::Evaluated(x) => Some(x.sample.x()),
            DynState::Compared(_) => None,
            DynState::Adjusted(_) => None,
            DynState::Mutated(_) => None,
            DynState::Finished(_) => None,
        }
    }

    /// Return the best point discovered.
    pub fn best_point(&self) -> Vec<bool> {
        self.probabilities()
            .iter()
            .map(|p| f64::from(*p) >= 0.5)
            .collect()
    }

    /// Return kind of state of inner state-machine.
    pub fn kind(&self) -> StateKind {
        match self.0 {
            DynState::Started(_) => StateKind::Started,
            DynState::SampledFirst(_) => StateKind::Sampled,
            DynState::EvaluatedFirst(_) => StateKind::Evaluated,
            DynState::Sampled(_) => StateKind::Sampled,
            DynState::Evaluated(_) => StateKind::Evaluated,
            DynState::Compared(_) => StateKind::Compared,
            DynState::Adjusted(_) => StateKind::Adjusted,
            DynState::Mutated(_) => StateKind::Mutated,
            DynState::Finished(_) => StateKind::Finished,
        }
    }
}

impl<B> Probabilities for State<B> {
    fn probabilities(&self) -> &[Probability] {
        match &self.0 {
            DynState::Started(x) => &x.probabilities,
            DynState::SampledFirst(x) => x.probabilities.probabilities(),
            DynState::EvaluatedFirst(x) => x.probabilities.probabilities(),
            DynState::Sampled(x) => x.probabilities.probabilities(),
            DynState::Evaluated(x) => x.probabilities.probabilities(),
            DynState::Compared(x) => x.probabilities.probabilities(),
            DynState::Adjusted(x) => &x.probabilities,
            DynState::Mutated(x) => &x.probabilities,
            DynState::Finished(x) => &x.probabilities,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pbil_should_not_mutate_if_chance_is_zero() {
        Config {
            num_samples: NumSamples::default(),
            adjust_rate: AdjustRate::default(),
            mutation_chance: MutationChance::new(0.0).unwrap(),
            mutation_adjust_rate: MutationAdjustRate::default(),
        }
        .start(16, |point| point.iter().filter(|x| **x).count())
        .inspect(|x| assert!(!x.state().kind().is_mutated()))
        .nth(100);
    }
}