gemla 0.1.32

Using evolutionary computation to generate machine learning algorithms
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! This module defines the [`GeneticNode`] trait and related types for managing the state and behavior of nodes within a [`Gemla`] simulation.
//!
//! - [`GeneticNode`]: A trait for interacting with the internal state of nodes, supporting asynchronous initialization, simulation, mutation, and merging.
//! - [`GeneticState`]: Enum representing the current state of a node in the simulation lifecycle.
//! - [`GeneticNodeContext`]: Context struct passed to node methods, containing generation, node ID, and simulation context.
//! - [`GeneticNodeWrapper`]: Wrapper struct for managing state transitions and node lifecycle.
//!
//! [`Gemla`]: crate::core::Gemla

use crate::error::Error;

use anyhow::Context;
use async_trait::async_trait;
use log::info;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use std::fmt::Debug;
use uuid::Uuid;

/// An enum representing the current state of a [`GeneticNode`] in the simulation lifecycle.
///
/// Used to control the processing flow of a node, such as initialization, simulation, mutation, and completion.
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Copy)]
pub enum GeneticState {
    /// The node and its data have not finished initializing.
    Initialize,
    /// The node is currently simulating a round against target data to determine the fitness of the population.
    Simulate,
    /// The node is currently mutating members of its population and breeding new members.
    Mutate,
    /// The node has finished processing for a given number of iterations.
    Finish,
}

/// Context information passed to [`GeneticNode`] trait methods. Most of the data originates from the [`GeneticNodeWrapper`].
///
/// Contains the current generation, node ID, and simulation context.
#[derive(Clone, Debug)]
pub struct GeneticNodeContext<S> {
    /// The current generation number. Generations start at 0 and increment after each mutation phase.
    pub generation: u64,

    /// The unique identifier for the node.
    pub id: Uuid,

    /// The user defined context specific to the simulation, such as parameters or environment data.
    pub gemla_context: S,
}

/// Trait for managing the state and behavior of nodes within a [`Gemla`] simulation
///
/// Implementors define how nodes are initialized, simulated, mutated, and merged asynchronously.
///
/// # Associated Types
/// - `Context`: The type of context data passed to node methods.
///
/// # Example
/// ```ignore
/// // Example implementation for a custom node type
/// #[async_trait]
/// impl GeneticNode for MyNode {
///     type Context = MyContext;
///     // ...
/// }
/// ```
///
/// [`Gemla`]: crate::core::Gemla
#[async_trait]
pub trait GeneticNode: Send {
    /// Custom type that provides a shared context across different nodes and simulations. Useful if you want to manage
    /// conncurrency or share data between nodes.
    ///
    /// # Example
    /// ```ignore
    /// pub struct SharedContext {
    ///     pub shared_semaphore: Arc<Semaphore>,
    ///     pub visible_simulations: Arc<Semaphore>,
    /// }
    /// ```
    /// In this example, `SharedContext` could be used to limit the number of concurrent simulations
    /// and control visibility of simulations to users.
    type Context;

    /// Initializes a new instance of a node implementing [`GeneticNode`].
    ///
    /// # Arguments
    /// * `context` - The context for initialization, including generation and node ID.
    ///
    /// # Returns
    /// * A boxed instance of the initialized node.
    ///
    /// # Example
    /// ```rust,ignore
    /// # use gemla::core::genetic_node::{GeneticNode, GeneticNodeContext};
    /// # use async_trait::async_trait;
    /// # use serde::{Serialize, Deserialize};
    /// # use rand::prelude::*;
    /// # use uuid::Uuid;
    /// #[derive(Serialize, Deserialize, Debug, Clone)]
    /// struct TestState {
    ///     population: Vec<i64>,
    ///     max_generations: u64,
    /// }
    ///
    /// #[async_trait]
    /// impl GeneticNode for TestState {
    ///     type Context = ();
    ///     async fn initialize(_context: GeneticNodeContext<Self::Context>) -> Result<Box<Self>, gemla::error::Error> {
    ///         let mut population = vec![];
    ///         for _ in 0..5 {
    ///             population.push(thread_rng().gen_range(0..100));
    ///         }
    ///         Ok(Box::new(TestState { population, max_generations: 10 }))
    ///     }
    ///     // ...
    /// }
    /// ```
    async fn initialize(context: GeneticNodeContext<Self::Context>) -> Result<Box<Self>, Error>;

    /// Simulates a round for the node, updating its state and returning whether to continue.
    ///
    /// # Arguments
    /// * `context` - The context for simulation, including generation and node ID.
    ///
    /// # Returns
    /// * `Ok(true)` if the node should continue to the next phase, `Ok(false)` if finished.
    ///
    /// # Example
    /// ```rust,ignore
    /// # use gemla::core::genetic_node::{GeneticNode, GeneticNodeContext};
    /// # use async_trait::async_trait;
    /// # use serde::{Serialize, Deserialize};
    /// # use rand::prelude::*;
    /// # use uuid::Uuid;
    /// #[derive(Serialize, Deserialize, Debug, Clone)]
    /// struct TestState {
    ///     population: Vec<i64>,
    ///     max_generations: u64,
    /// }
    ///
    /// #[async_trait]
    /// impl GeneticNode for TestState {
    ///     type Context = ();
    ///     async fn simulate(&mut self, context: GeneticNodeContext<Self::Context>) -> Result<bool, gemla::error::Error> {
    ///         let mut rng = thread_rng();
    ///         self.population = self.population.iter().map(|p| p.saturating_add(rng.gen_range(-1..2))).collect();
    ///         if context.generation >= self.max_generations {
    ///             Ok(false)
    ///         } else {
    ///             Ok(true)
    ///         }
    ///     }
    ///     // ...
    /// }
    /// ```
    async fn simulate(&mut self, context: GeneticNodeContext<Self::Context>)
        -> Result<bool, Error>;

    /// Mutates members in a population and/or crossbreeds them to produce new offspring.
    ///
    /// # Arguments
    /// * `context` - The context for mutation, including generation and node ID.
    ///
    /// # Returns
    /// * `Ok(())` if mutation was successful.
    /// * `Err(Error)` if an error occurred during mutation.
    ///
    /// # Example
    /// ```rust,ignore
    /// # use gemla::core::genetic_node::{GeneticNode, GeneticNodeContext};
    /// # use async_trait::async_trait;
    /// # use serde::{Serialize, Deserialize};
    /// # use rand::prelude::*;
    /// # use uuid::Uuid;
    /// #[derive(Serialize, Deserialize, Debug, Clone)]
    /// struct TestState {
    ///     population: Vec<i64>,
    ///     max_generations: u64,
    /// }
    ///
    /// #[async_trait]
    /// impl GeneticNode for TestState {
    ///     type Context = ();
    ///     async fn mutate(&mut self, _context: GeneticNodeContext<Self::Context>) -> Result<(), gemla::error::Error> {
    ///         let mut rng = thread_rng();
    ///         let mut v = self.population.clone();
    ///         v.sort_unstable();
    ///         v.reverse();
    ///         self.population = v[0..3].to_vec();
    ///         while self.population.len() < 5 {
    ///             let i = rng.gen_range(0..self.population.len());
    ///             let j = loop {
    ///                 let idx = rng.gen_range(0..self.population.len());
    ///                 if idx != i { break idx; }
    ///             };
    ///             let mut new_ind = self.population[i];
    ///             let cross = self.population[j];
    ///             new_ind = (new_ind.saturating_add(cross) / 2).saturating_add(rng.gen_range(-1..2));
    ///             self.population.push(new_ind);
    ///         }
    ///         Ok(())
    ///     }
    ///     // ...
    /// }
    /// ```
    async fn mutate(&mut self, context: GeneticNodeContext<Self::Context>) -> Result<(), Error>;

    /// Merges two nodes into a new node, using the provided context and ID. This occurs after
    /// two nodes have finished simulating and the populations need to be combined.
    ///
    /// # Arguments
    /// * `left` - The left node to merge.
    /// * `right` - The right node to merge.
    /// * `id` - The ID for the new merged node.
    /// * `context` - The context for merging.
    ///
    /// # Example
    /// ```rust,ignore
    /// # use gemla::core::genetic_node::{GeneticNode, GeneticNodeContext};
    /// # use async_trait::async_trait;
    /// # use serde::{Serialize, Deserialize};
    /// # use uuid::Uuid;
    /// #[derive(Serialize, Deserialize, Debug, Clone)]
    /// struct TestState {
    ///     population: Vec<i64>,
    ///     max_generations: u64,
    /// }
    ///
    /// #[async_trait]
    /// impl GeneticNode for TestState {
    ///     type Context = ();
    ///     async fn merge(left: &TestState, right: &TestState, id: &Uuid, gemla_context: Self::Context) -> Result<Box<TestState>, gemla::error::Error> {
    ///         let mut v = left.population.clone();
    ///         v.append(&mut right.population.clone());
    ///         v.sort_by(|a, b| a.partial_cmp(b).unwrap());
    ///         v.reverse();
    ///         v = v[..3].to_vec();
    ///         let mut result = TestState { population: v, max_generations: 10 };
    ///         result.mutate(GeneticNodeContext { id: *id, generation: 0, gemla_context }).await?;
    ///         Ok(Box::new(result))
    ///     }
    ///     // ...
    /// }
    /// ```
    async fn merge(
        left: &Self,
        right: &Self,
        id: &Uuid,
        context: Self::Context,
    ) -> Result<Box<Self>, Error>;
}

/// Wrapper for a node implementing [`GeneticNode`], managing state transitions and lifecycle.
///
/// Used externally to process state transitions and signal recovery. State transitions are managed using [`GeneticState`].
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub struct GeneticNodeWrapper<T>
where
    T: Clone,
{
    /// The wrapped node instance, if initialized.
    node: Option<T>,

    /// The current state of the node in the simulation lifecycle.
    state: GeneticState,

    /// The current generation number. Generations start at 0 and increment after each mutation phase.
    generation: u64,

    /// The unique identifier for the node.
    id: Uuid,
}

impl<T> Default for GeneticNodeWrapper<T>
where
    T: Clone,
{
    fn default() -> Self {
        GeneticNodeWrapper {
            node: None,
            state: GeneticState::Initialize,
            generation: 1,
            id: Uuid::new_v4(),
        }
    }
}

impl<T> GeneticNodeWrapper<T>
where
    T: GeneticNode + Debug + Send + Clone,
    T::Context: Send + Sync + Clone + Debug + Serialize + DeserializeOwned + 'static + Default,
{
    /// Creates a new instance of [`GeneticNodeWrapper`]. Calls [`Default::default()`] of the inner type.
    pub fn new() -> Self {
        GeneticNodeWrapper::<T> {
            ..Default::default()
        }
    }

    /// Creates a new instance from the given node data and ID.
    pub fn from(data: T, id: Uuid) -> Self {
        GeneticNodeWrapper {
            node: Some(data),
            state: GeneticState::Simulate,
            generation: 1,
            id,
        }
    }

    /// Returns a reference to the wrapped node, if available.
    pub fn as_ref(&self) -> Option<&T> {
        self.node.as_ref()
    }

    /// Takes the wrapped node, consuming the wrapper.
    pub fn take(&mut self) -> Option<T> {
        self.node.take()
    }

    /// Returns the ID of the node.
    pub fn id(&self) -> Uuid {
        self.id
    }

    /// Returns the current generation number.
    pub fn generation(&self) -> u64 {
        self.generation
    }

    /// Returns the current state of the node.
    pub fn state(&self) -> GeneticState {
        self.state
    }

    /// Processes the node for the current generation, updating its state and transitioning to the next phase as needed.
    ///
    /// # Arguments
    /// * `gemla_context` - The user-defined context for the simulation, passed to node methods.
    ///
    /// # Returns
    /// * The updated state of the node after processing.
    pub async fn process_node(&mut self, gemla_context: T::Context) -> Result<GeneticState, Error> {
        let context = GeneticNodeContext {
            generation: self.generation,
            id: self.id,
            gemla_context,
        };

        match (self.state, &mut self.node) {
            (GeneticState::Initialize, _) => {
                self.node = Some(*T::initialize(context.clone()).await?);
                self.state = GeneticState::Simulate;
            }
            (GeneticState::Simulate, Some(n)) => {
                let next_generation = n
                    .simulate(context.clone())
                    .await
                    .with_context(|| format!("Error simulating node: {:?}", self))?;

                info!("Simulation complete and continuing: {:?}", next_generation);

                self.state = if next_generation {
                    GeneticState::Mutate
                } else {
                    GeneticState::Finish
                };
            }
            (GeneticState::Mutate, Some(n)) => {
                n.mutate(context.clone())
                    .await
                    .with_context(|| format!("Error mutating node: {:?}", self))?;

                self.generation += 1;
                self.state = GeneticState::Simulate;
            }
            (GeneticState::Finish, Some(_)) => (),
            _ => panic!("Error processing node {:?}", self.node),
        }

        Ok(self.state)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::Error;
    use anyhow::anyhow;
    use async_trait::async_trait;

    #[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
    struct TestState {
        pub score: f64,
        pub max_generations: u64,
    }

    #[async_trait]
    impl GeneticNode for TestState {
        type Context = ();

        async fn simulate(
            &mut self,
            context: GeneticNodeContext<Self::Context>,
        ) -> Result<bool, Error> {
            self.score += 1.0;
            if context.generation >= self.max_generations {
                Ok(false)
            } else {
                Ok(true)
            }
        }

        async fn mutate(
            &mut self,
            _context: GeneticNodeContext<Self::Context>,
        ) -> Result<(), Error> {
            Ok(())
        }

        async fn initialize(
            _context: GeneticNodeContext<Self::Context>,
        ) -> Result<Box<TestState>, Error> {
            Ok(Box::new(TestState {
                score: 0.0,
                max_generations: 2,
            }))
        }

        async fn merge(
            _l: &TestState,
            _r: &TestState,
            _id: &Uuid,
            _: Self::Context,
        ) -> Result<Box<TestState>, Error> {
            Err(Error::Other(anyhow!("Unable to merge")))
        }
    }

    #[test]
    fn test_new() -> Result<(), Error> {
        let genetic_node = GeneticNodeWrapper::<TestState>::new();

        let other_genetic_node = GeneticNodeWrapper::<TestState> {
            node: None,
            state: GeneticState::Initialize,
            generation: 1,
            id: genetic_node.id(),
        };

        assert_eq!(genetic_node, other_genetic_node);

        Ok(())
    }

    #[test]
    fn test_from() -> Result<(), Error> {
        let val = TestState {
            score: 0.0,
            max_generations: 10,
        };
        let uuid = Uuid::new_v4();
        let genetic_node = GeneticNodeWrapper::from(val.clone(), uuid);

        let other_genetic_node = GeneticNodeWrapper::<TestState> {
            node: Some(val),
            state: GeneticState::Simulate,
            generation: 1,
            id: genetic_node.id(),
        };

        assert_eq!(genetic_node, other_genetic_node);

        Ok(())
    }

    #[test]
    fn test_as_ref() -> Result<(), Error> {
        let val = TestState {
            score: 3.0,
            max_generations: 10,
        };
        let uuid = Uuid::new_v4();
        let genetic_node = GeneticNodeWrapper::from(val.clone(), uuid);

        let ref_value = genetic_node.as_ref().unwrap();

        assert_eq!(*ref_value, val);

        Ok(())
    }

    #[test]
    fn test_id() -> Result<(), Error> {
        let val = TestState {
            score: 3.0,
            max_generations: 10,
        };
        let uuid = Uuid::new_v4();
        let genetic_node = GeneticNodeWrapper::from(val.clone(), uuid);

        let id_value = genetic_node.id();

        assert_eq!(id_value, uuid);

        Ok(())
    }

    #[test]
    fn test_state() -> Result<(), Error> {
        let val = TestState {
            score: 3.0,
            max_generations: 10,
        };
        let uuid = Uuid::new_v4();
        let genetic_node = GeneticNodeWrapper::from(val.clone(), uuid);

        let state = genetic_node.state();

        assert_eq!(state, GeneticState::Simulate);

        Ok(())
    }

    #[tokio::test]
    async fn test_process_node() -> Result<(), Error> {
        let mut genetic_node = GeneticNodeWrapper::<TestState>::new();

        assert_eq!(genetic_node.state(), GeneticState::Initialize);
        assert_eq!(genetic_node.process_node(()).await?, GeneticState::Simulate);
        assert_eq!(genetic_node.process_node(()).await?, GeneticState::Mutate);
        assert_eq!(genetic_node.process_node(()).await?, GeneticState::Simulate);
        assert_eq!(genetic_node.process_node(()).await?, GeneticState::Finish);
        assert_eq!(genetic_node.process_node(()).await?, GeneticState::Finish);

        Ok(())
    }
}