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
//! # Symbios Genetics
//!
//! A high-performance evolutionary computation library for Rust with deterministic
//! execution and serializable state.
//!
//! ## Features
//!
//! - **Deterministic Execution**: Bit-perfect reproducibility across runs with seeded RNG
//! - **Serializable State**: Save and restore evolution state via Serde
//! - **Parallel Evaluation**: Optional parallel fitness evaluation via Rayon
//! - **Multiple Algorithms**: Simple GA, NSGA-II, MAP-Elites, CVT-MAP-Elites, Novelty Search
//! - **Composable Scorers**: Pre-made fitness building blocks for locomotion / robotics
//! (see [`scorers`])
//! - **Speciation**: Generic NEAT-style fitness sharing with a dynamic compatibility
//! threshold (see [`speciation`])
//!
//! ## Quick Start
//!
//! ```rust
//! use rand::Rng;
//! use serde::{Deserialize, Serialize};
//! use symbios_genetics::{Evaluator, Evolver, Genotype, algorithms::simple::SimpleGA};
//!
//! // Define your genome
//! #[derive(Clone, Serialize, Deserialize)]
//! struct MyGenome(f32);
//!
//! impl Genotype for MyGenome {
//! fn mutate<R: Rng>(&mut self, rng: &mut R, rate: f32) {
//! if rng.random::<f32>() < rate {
//! self.0 += rng.random::<f32>() - 0.5;
//! }
//! }
//! fn crossover<R: Rng>(&self, other: &Self, _rng: &mut R) -> Self {
//! MyGenome((self.0 + other.0) / 2.0)
//! }
//! }
//!
//! // Define your fitness function
//! struct MaximizeFitness;
//! impl Evaluator<MyGenome> for MaximizeFitness {
//! fn evaluate(&self, g: &MyGenome) -> (f32, Vec<f32>, Vec<f32>) {
//! let fitness = -g.0.powi(2); // Minimize x^2 (maximize -x^2)
//! (fitness, vec![fitness], vec![])
//! }
//! }
//!
//! // Run evolution
//! let initial: Vec<MyGenome> = (0..50).map(|i| MyGenome(i as f32 - 25.0)).collect();
//! let mut ga = SimpleGA::new(initial, 0.1, 5, 42);
//!
//! for _ in 0..100 {
//! ga.step(&MaximizeFitness);
//! }
//!
//! let best = ga.population().iter().max_by(|a, b| {
//! a.fitness.partial_cmp(&b.fitness).unwrap()
//! }).unwrap();
//! println!("Best fitness: {}", best.fitness);
//! ```
//!
//! ## Algorithms
//!
//! | Algorithm | Use Case | Key Feature |
//! |-----------|----------|-------------|
//! | [`SimpleGA`](algorithms::simple::SimpleGA) | Single-objective optimization | Fast, simple, elitism support |
//! | [`Nsga2`](algorithms::nsga2::Nsga2) | Multi-objective optimization | Pareto front discovery |
//! | [`MapElites`](algorithms::map_elites::MapElites) | Quality-diversity | Grid-based behavioural archive |
//! | [`CvtMapElites`](algorithms::cvt_map_elites::CvtMapElites) | Quality-diversity | Voronoi tessellation; decouples archive size from descriptor dimensionality |
//! | [`NoveltySearch`](algorithms::novelty_search::NoveltySearch) | Open-ended exploration | kNN behavioural distance; escapes deceptive optima |
//!
//! ## Feature Flags
//!
//! - `parallel` (default): Enable parallel fitness evaluation using Rayon
//! - `export`: Enable archive CSV export
//! ([`MapElites::export_csv`](algorithms::map_elites::MapElites::export_csv),
//! [`CvtMapElites::export_csv`](algorithms::cvt_map_elites::CvtMapElites::export_csv));
//! pulls in `bincode` and `seahash` for stable genotype hashes.
//!
//! ## Serialization
//!
//! All algorithm state is serializable, enabling checkpointing and resumption:
//!
//! ```rust,ignore
//! // Save state
//! let json = serde_json::to_string(&ga)?;
//!
//! // Restore and continue
//! let mut ga: SimpleGA<MyGenome> = serde_json::from_str(&json)?;
//! ga.step(&evaluator);
//! ```
use Rng;
use ;
/// A genotype represents the genetic encoding of an individual.
///
/// Implement this trait for your custom genome type to use it with the
/// evolutionary algorithms in this crate.
///
/// # Requirements
///
/// - Must be [`Clone`], [`Serialize`], [`Deserialize`], [`Send`], and [`Sync`]
/// - Must implement mutation and crossover operators
///
/// # Example
///
/// ```rust
/// use rand::Rng;
/// use serde::{Deserialize, Serialize};
/// use symbios_genetics::Genotype;
///
/// #[derive(Clone, Serialize, Deserialize)]
/// struct BitVec(Vec<bool>);
///
/// impl Genotype for BitVec {
/// fn mutate<R: Rng>(&mut self, rng: &mut R, rate: f32) {
/// for bit in &mut self.0 {
/// if rng.random::<f32>() < rate {
/// *bit = !*bit;
/// }
/// }
/// }
///
/// fn crossover<R: Rng>(&self, other: &Self, rng: &mut R) -> Self {
/// let point = rng.random_range(0..self.0.len());
/// let mut child = self.0[..point].to_vec();
/// child.extend_from_slice(&other.0[point..]);
/// BitVec(child)
/// }
/// }
/// ```
/// A phenotype represents an evaluated individual with fitness information.
///
/// The phenotype contains both the genetic encoding ([`genotype`](Phenotype::genotype))
/// and the results of fitness evaluation.
///
/// # Fields
///
/// * `genotype` - The genetic encoding
/// * `fitness` - Single scalar fitness value (for single-objective algorithms)
/// * `objectives` - Multiple objective values (for multi-objective algorithms like NSGA-II)
/// * `descriptor` - Behavioral descriptor (for quality-diversity algorithms like MAP-Elites)
/// Evaluates genotypes to produce fitness scores.
///
/// Implement this trait to define your optimization problem's fitness function.
///
/// # Thread Safety
///
/// Evaluators must be [`Send`] and [`Sync`] to support parallel evaluation.
/// If your evaluator has mutable state, wrap it in appropriate synchronization
/// primitives (e.g., `Arc<Mutex<T>>`).
///
/// # Example
///
/// ```rust
/// use symbios_genetics::{Evaluator, Genotype};
/// use serde::{Deserialize, Serialize};
/// use rand::Rng;
///
/// #[derive(Clone, Serialize, Deserialize)]
/// struct Point(f32, f32);
///
/// impl Genotype for Point {
/// fn mutate<R: Rng>(&mut self, rng: &mut R, rate: f32) {
/// if rng.random::<f32>() < rate {
/// self.0 += rng.random::<f32>() - 0.5;
/// self.1 += rng.random::<f32>() - 0.5;
/// }
/// }
/// fn crossover<R: Rng>(&self, other: &Self, _rng: &mut R) -> Self {
/// Point((self.0 + other.0) / 2.0, (self.1 + other.1) / 2.0)
/// }
/// }
///
/// // Minimize distance to origin
/// struct DistanceToOrigin;
///
/// impl Evaluator<Point> for DistanceToOrigin {
/// fn evaluate(&self, g: &Point) -> (f32, Vec<f32>, Vec<f32>) {
/// let dist = (g.0.powi(2) + g.1.powi(2)).sqrt();
/// let fitness = -dist; // Negate because higher fitness is better
/// (fitness, vec![fitness], vec![])
/// }
/// }
/// ```
/// The core evolutionary algorithm trait.
///
/// All evolutionary algorithms implement this trait, providing a uniform
/// interface for running evolution steps and accessing the population.
///
/// # Example
///
/// ```rust,ignore
/// use symbios_genetics::{Evolver, Evaluator};
///
/// fn run_evolution<G, E, Ev>(mut evolver: Ev, evaluator: &E, generations: usize)
/// where
/// G: Genotype,
/// E: Evaluator<G>,
/// Ev: Evolver<G>,
/// {
/// for _ in 0..generations {
/// evolver.step(evaluator);
/// }
/// let best = evolver.population()
/// .iter()
/// .max_by(|a, b| a.fitness.partial_cmp(&b.fitness).unwrap());
/// println!("Best fitness: {:?}", best.map(|p| p.fitness));
/// }
/// ```
/// Evolutionary algorithm implementations.
///
/// This module contains the following evolutionary algorithms:
///
/// - [`simple::SimpleGA`](algorithms::simple::SimpleGA) — Generational GA with elitism (single-objective)
/// - [`nsga2::Nsga2`](algorithms::nsga2::Nsga2) — NSGA-II for multi-objective optimisation
/// - [`map_elites::MapElites`](algorithms::map_elites::MapElites) — Grid-based MAP-Elites quality-diversity
/// - [`cvt_map_elites::CvtMapElites`](algorithms::cvt_map_elites::CvtMapElites) — MAP-Elites variant using a Centroidal Voronoi Tessellation
/// - [`novelty_search::NoveltySearch`](algorithms::novelty_search::NoveltySearch) — Lehman & Stanley novelty-driven search
/// Pre-made composable scorers for locomotion / robotics evolution.
/// Speciation primitives: cluster a population by user-supplied compatibility
/// distance, share fitness within species, dynamically tune the threshold.