genhdc 0.1.0

Hyperdimensional Computing (HDC/VSA) engine with genetic operators — extracted from the production Mimer agent
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
//! Core genome types and genetic operators for GenHDC.
//!
//! This module provides the `ConceptGenome` — a genetic representation that
//! can be attached to any HDC hypervector to give it inheritance, mutation,
//! and evolutionary dynamics.

use rand::Rng;

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

/// A single inheritable feature within a concept's genome.
///
/// Features represent the "genes" that compose a concept. Each feature has
/// a dominance level (1.0 = always expressed, 0.0 = recessive/silenced)
/// and an origin tracing where it came from.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct GenomeFeature {
    /// The name of this feature (e.g., "color", "shape", "behavior_trait").
    pub name: String,
    /// Dominance — 1.0 = always expressed, 0.0 = fully recessive.
    pub dominance: f32,
    /// Origin — which concept or process created this feature.
    /// Common values: "seed_garden", "mutation", "crispr", or a parent concept name.
    pub origin: String,
}

/// A concept's genome — inheritable traits that track lineage and evolution.
///
/// `ConceptGenome` is the core type of GenHDC. It wraps a set of features
/// (genes) with metadata about parentage, generation, mutation rate, and
/// fitness. Genomes can be attached to HDC hypervectors to give them
/// evolutionary dynamics — they evolve independently of the vector
/// representation, governing *which* vectors survive and how they change.
///
/// # Lifecycle
///
/// 1. **Genesis** — `primordial()` creates a genome without parents (generation 0).
/// 2. **Inheritance** — `inherit()` blends features from two parents with mutation.
/// 3. **Mutation** — `mutate()` randomly perturbs features based on mutation_rate.
/// 4. **CRISPR** — `crispr_edit()` performs targeted mutation guided by error signals.
/// 5. **Expression** — `toggle_expression()` changes phenotype without genotype change.
/// 6. **Selection** — the `fitness` field is adjusted externally; high-fitness
///    genomes are more likely to be chosen as parents.
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct ConceptGenome {
    /// Unique genome ID (generated at birth).
    pub id: String,
    /// Parent genome IDs — empty if primordial (directly from seed garden).
    pub parent_ids: Vec<String>,
    /// Dominant features inherited from parents.
    pub features: Vec<GenomeFeature>,
    /// Generation number — how many inheritance steps from the primordial concept.
    pub generation: u32,
    /// Probability per feature to mutate during inheritance (0.0–1.0).
    pub mutation_rate: f32,
    /// Tick when this genome was created.
    pub tick_born: u64,
    /// Fitness — survival strength. Starts at 0.5, adjusted by external selection
    /// pressure (e.g., surprise signal, reward, prediction error).
    pub fitness: f32,
}

impl ConceptGenome {
    /// Create a primordial genome — a seed concept with no parents.
    ///
    /// Primordial concepts are the "first generation" — they come directly
    /// from the seed garden or domain knowledge, not from inheritance.
    ///
    /// # Example
    ///
    /// ```rust
    /// use genhdc::ConceptGenome;
    ///
    /// let apple = ConceptGenome::primordial("apple", 42);
    /// assert_eq!(apple.generation, 0);
    /// assert!(apple.parent_ids.is_empty());
    /// assert_eq!(apple.features[0].name, "apple");
    /// ```
    pub fn primordial(name: &str, tick: u64) -> Self {
        let mut rng = rand::thread_rng();
        let id = format!("genome-{}", rng.gen_range(1000..9999));
        Self {
            id,
            parent_ids: vec![],
            features: vec![GenomeFeature {
                name: name.to_string(),
                dominance: 1.0,
                origin: "seed_garden".to_string(),
            }],
            generation: 0,
            mutation_rate: 0.1,
            tick_born: tick,
            fitness: 0.5,
        }
    }

    /// Inherit from two parents — blend features with mutation.
    ///
    /// `parent_a` is the dominant parent (features inherited at 90% dominance).
    /// `parent_b` is the recessive parent (features inherited at 70% dominance).
    ///
    /// The child receives:
    /// - All features from parent_a (dominance × 0.9)
    /// - Unique features from parent_b not already present (dominance × 0.7)
    /// - Then `mutate()` is called to introduce random variation
    ///
    /// Mutation rate is the average of both parents + 0.01 (drift toward novelty).
    ///
    /// # Example
    ///
    /// ```rust
    /// use genhdc::ConceptGenome;
    ///
    /// let a = ConceptGenome::primordial("snake", 0);
    /// let b = ConceptGenome::primordial("apple", 0);
    /// let child = ConceptGenome::inherit(&a, &b, "eats", 1);
    ///
    /// assert_eq!(child.generation, 1);
    /// assert_eq!(child.parent_ids.len(), 2);
    /// ```
    pub fn inherit(
        parent_a: &ConceptGenome,
        parent_b: &ConceptGenome,
        _name: &str,
        tick: u64,
    ) -> Self {
        let mut rng = rand::thread_rng();
        let id = format!("genome-{}", rng.gen_range(1000..9999));
        let mut features = Vec::new();

        // Inherit from dominant parent (parent_a) — strong expression.
        for f in &parent_a.features {
            features.push(GenomeFeature {
                name: f.name.clone(),
                dominance: f.dominance * 0.9,
                origin: f.origin.clone(),
            });
        }

        // Inherit unique features from recessive parent (parent_b) — weaker.
        for f in &parent_b.features {
            if !features.iter().any(|x| x.name == f.name) {
                features.push(GenomeFeature {
                    name: f.name.clone(),
                    dominance: f.dominance * 0.7,
                    origin: f.origin.clone(),
                });
            }
        }

        let mut genome = Self {
            id,
            parent_ids: vec![parent_a.id.clone(), parent_b.id.clone()],
            features,
            generation: parent_a.generation.max(parent_b.generation) + 1,
            mutation_rate: (parent_a.mutation_rate + parent_b.mutation_rate) / 2.0 + 0.01,
            tick_born: tick,
            fitness: (parent_a.fitness + parent_b.fitness) / 2.0,
        };

        // Apply random mutation as the final step.
        genome.mutate(tick);
        genome
    }

    /// Random mutation — perturb features based on `mutation_rate`.
    ///
    /// Three types of mutation occur:
    /// 1. **Feature drift** — each feature has `mutation_rate` chance of
    ///    having its dominance shifted by ±0.3 (clamped to [0, 1]).
    /// 2. **Novel feature** — `mutation_rate × 0.3` chance of adding a new
    ///    feature with low dominance (0.3), origin = "mutation".
    /// 3. **Feature deletion** — `mutation_rate × 0.2` chance of removing
    ///    a random feature (only if > 1 feature exists).
    ///
    /// Fitness is also slightly perturbed (±0.05) per mutation call.
    pub fn mutate(&mut self, tick: u64) {
        let mut rng = rand::thread_rng();

        // 1. Feature drift — shift dominance on random features.
        for f in &mut self.features {
            if rng.gen_bool(self.mutation_rate as f64) {
                f.dominance = (f.dominance + rng.gen_range(-0.3..0.3)).clamp(0.0, 1.0);
            }
        }

        // 2. Novel feature — spontaneous new gene.
        if rng.gen_bool((self.mutation_rate * 0.3) as f64) {
            let new_feature = GenomeFeature {
                name: format!("nova_{}", tick),
                dominance: 0.3,
                origin: "mutation".to_string(),
            };
            self.features.push(new_feature);
        }

        // 3. Feature deletion — lose a random gene.
        if self.features.len() > 1 && rng.gen_bool((self.mutation_rate * 0.2) as f64) {
            let idx = rng.gen_range(0..self.features.len());
            self.features.remove(idx);
        }

        // Slight fitness drift.
        self.fitness = (self.fitness + rng.gen_range(-0.05..0.05)).clamp(0.0, 1.0);
    }

    /// CRISPR-like targeted mutation — edit features correlated with a
    /// surprise/error signal.
    ///
    /// Unlike random mutation, CRISPR editing is **guided**: only features
    /// whose names contain one of the `culprits` strings are edited. This
    /// mimics how CRISPR/Cas9 targets specific DNA sequences.
    ///
    /// For each culprit:
    /// - The matching feature's dominance is reduced by 30% (×0.7).
    /// - A compensating "fix" feature is added with medium dominance (0.5).
    /// - Overall fitness drops slightly (−0.05) to reflect the cost of editing.
    ///
    /// # Example
    ///
    /// ```rust
    /// use genhdc::ConceptGenome;
    ///
    /// let mut genome = ConceptGenome::primordial("risky_move", 0);
    /// genome.crispr_edit(&["risk".to_string(), "overcommit".to_string()], 100);
    ///
    /// // Features matching "risk" or "overcommit" were weakened.
    /// // Compensating "fix_risk_100" / "fix_overcommit_100" features were added.
    /// ```
    pub fn crispr_edit(&mut self, culprits: &[String], tick: u64) {
        for culprit in culprits {
            if let Some(f) = self.features.iter_mut().find(|f| f.name.contains(culprit)) {
                // Weaken the problematic feature.
                f.dominance *= 0.7;
                // Add a compensating fix.
                self.features.push(GenomeFeature {
                    name: format!("fix_{}_{}", culprit, tick),
                    dominance: 0.5,
                    origin: "crispr".to_string(),
                });
            }
        }
        self.fitness = (self.fitness - 0.05).max(0.0);
    }

    /// Epigenetic toggle — change a feature's expression without altering
    /// the genome itself.
    ///
    /// This models epigenetic regulation: the DNA (feature set) stays the
    /// same, but gene expression changes. Setting `active = true` sets the
    /// feature's dominance to 1.0 (fully expressed); `false` sets it to
    /// 0.1 (effectively silenced).
    ///
    /// Returns `true` if the feature was found and toggled, `false` if
    /// no feature with that name exists.
    ///
    /// # Example
    ///
    /// ```rust
    /// use genhdc::ConceptGenome;
    ///
    /// let mut risk = ConceptGenome::primordial("risk", 0);
    ///
    /// // In a bull market, silence risk aversion.
    /// risk.toggle_expression("risk", false);
    /// assert_eq!(risk.features[0].dominance, 0.1);
    ///
    /// // In a bear market, re-activate risk awareness.
    /// risk.toggle_expression("risk", true);
    /// assert_eq!(risk.features[0].dominance, 1.0);
    /// ```
    pub fn toggle_expression(&mut self, feature_name: &str, active: bool) -> bool {
        if let Some(f) = self.features.iter_mut().find(|f| f.name == feature_name) {
            f.dominance = if active { 1.0 } else { 0.1 };
            true
        } else {
            false
        }
    }

    /// Return all features with dominance > 0.5 (actively expressed).
    ///
    /// This is the "phenotype" — the visible traits, as opposed to the
    /// full genotype (all features including recessive ones).
    pub fn active_features(&self) -> Vec<&GenomeFeature> {
        self.features.iter().filter(|f| f.dominance > 0.5).collect()
    }

    /// Return the total number of features (including recessive).
    pub fn feature_count(&self) -> usize {
        self.features.len()
    }

    /// Return the number of active (dominant) features.
    pub fn active_count(&self) -> usize {
        self.active_features().len()
    }

    /// True if this genome is primordial (has no parents).
    pub fn is_primordial(&self) -> bool {
        self.parent_ids.is_empty()
    }

    /// Adjust fitness by a delta and clamp to [0, 1].
    ///
    /// Positive delta = reward / successful prediction / low surprise.
    /// Negative delta = penalty / prediction error / high surprise.
    pub fn adjust_fitness(&mut self, delta: f32) {
        self.fitness = (self.fitness + delta).clamp(0.0, 1.0);
    }

    /// Create a lineage trace string for debugging/visualization.
    ///
    /// Format: `gen{N} ← {parent_a_id} + {parent_b_id}` or
    /// `gen{0} (primordial)`.
    pub fn lineage(&self) -> String {
        if self.parent_ids.is_empty() {
            format!("gen{} (primordial)", self.generation)
        } else if self.parent_ids.len() == 1 {
            format!("gen{} ← {}", self.generation, self.parent_ids[0])
        } else {
            format!(
                "gen{} ← {} + {}",
                self.generation, self.parent_ids[0], self.parent_ids[1]
            )
        }
    }
}

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

    #[test]
    fn primordial_has_no_parents() {
        let g = ConceptGenome::primordial("test", 0);
        assert!(g.is_primordial());
        assert_eq!(g.generation, 0);
        assert!(g.parent_ids.is_empty());
        assert_eq!(g.features.len(), 1);
        assert_eq!(g.features[0].name, "test");
        assert_eq!(g.features[0].dominance, 1.0);
    }

    #[test]
    fn inherit_produces_child_with_lineage() {
        let a = ConceptGenome::primordial("a", 0);
        let b = ConceptGenome::primordial("b", 0);
        let child = ConceptGenome::inherit(&a, &b, "child", 1);

        assert_eq!(child.generation, 1);
        assert_eq!(child.parent_ids.len(), 2);
        assert!(child.parent_ids.contains(&a.id));
        assert!(child.parent_ids.contains(&b.id));
        assert!(child.feature_count() >= 1);
    }

    #[test]
    fn mutation_adds_or_removes_features() {
        let mut g = ConceptGenome::primordial("test", 0);
        g.mutation_rate = 1.0; // Force mutation every time.
        let _before = g.feature_count();
        g.mutate(42);

        // With rate 1.0, something should change (add, remove, or drift).
        // Features may increase (nova added) or decrease (removed), or both.
        // We just verify the genome is still valid.
        assert!(g.feature_count() >= 1);
        assert!((0.0..=1.0).contains(&g.fitness));
    }

    #[test]
    fn crispr_edits_targeted_features() {
        let mut g = ConceptGenome::primordial("risky_concept", 0);
        // Add a specific feature to target.
        g.features.push(GenomeFeature {
            name: "overcommit".to_string(),
            dominance: 0.8,
            origin: "learning".to_string(),
        });

        g.crispr_edit(&["overcommit".to_string()], 100);

        // The targeted feature should be weakened.
        let overcommit = g.features.iter().find(|f| f.name == "overcommit").unwrap();
        assert!(overcommit.dominance < 0.8);

        // A fix feature should have been added.
        let has_fix = g.features.iter().any(|f| f.name.contains("fix_overcommit"));
        assert!(has_fix);

        // Fitness should have dropped slightly.
        assert!(g.fitness < 0.5);
    }

    #[test]
    fn epigenetic_toggle_changes_expression() {
        let mut g = ConceptGenome::primordial("test", 0);
        let feat_name = g.features[0].name.clone();

        // Toggle off.
        assert!(g.toggle_expression(&feat_name, false));
        assert_eq!(g.features[0].dominance, 0.1);

        // Toggle on.
        assert!(g.toggle_expression(&feat_name, true));
        assert_eq!(g.features[0].dominance, 1.0);

        // Non-existent feature.
        assert!(!g.toggle_expression("nonexistent", true));
    }

    #[test]
    fn active_features_filter_by_dominance() {
        let mut g = ConceptGenome::primordial("test", 0);
        // Add a recessive feature.
        g.features.push(GenomeFeature {
            name: "recessive".to_string(),
            dominance: 0.2,
            origin: "mutation".to_string(),
        });

        let active = g.active_features();
        assert_eq!(active.len(), 1); // Only the primordial feature (dominance 1.0).
        assert_eq!(g.active_count(), 1);
        assert_eq!(g.feature_count(), 2);
    }

    #[test]
    fn lineage_format() {
        let g = ConceptGenome::primordial("test", 0);
        assert!(g.lineage().contains("primordial"));

        let a = ConceptGenome::primordial("a", 0);
        let b = ConceptGenome::primordial("b", 0);
        let child = ConceptGenome::inherit(&a, &b, "child", 1);
        let lineage = child.lineage();
        assert!(lineage.contains("gen1"));
        assert!(lineage.contains(&a.id));
        assert!(lineage.contains(&b.id));
    }

    #[test]
    fn fitness_stays_in_range() {
        let mut g = ConceptGenome::primordial("test", 0);

        // Push fitness way up — should clamp.
        g.adjust_fitness(10.0);
        assert_eq!(g.fitness, 1.0);

        // Push fitness way down — should clamp.
        g.adjust_fitness(-20.0);
        assert_eq!(g.fitness, 0.0);
    }

    #[test]
    fn multiple_generations_accumulate() {
        let g0 = ConceptGenome::primordial("root", 0);
        let g1a = ConceptGenome::primordial("branch_a", 0);
        let g1 = ConceptGenome::inherit(&g0, &g1a, "gen1", 1);
        assert_eq!(g1.generation, 1);

        let g2 = ConceptGenome::inherit(&g1, &g0, "gen2", 2);
        assert_eq!(g2.generation, 2);

        let g3 = ConceptGenome::inherit(&g2, &g1, "gen3", 3);
        assert_eq!(g3.generation, 3);

        // Mutation rate should drift upward over generations.
        assert!(g3.mutation_rate > g0.mutation_rate);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_roundtrip() {
        let g = ConceptGenome::primordial("test", 42);
        let json = serde_json::to_string(&g).unwrap();
        let g2: ConceptGenome = serde_json::from_str(&json).unwrap();
        assert_eq!(g.id, g2.id);
        assert_eq!(g.generation, g2.generation);
        assert_eq!(g.features.len(), g2.features.len());
    }
}