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
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
//! Hyperdimensional Computing / Vector Symbolic Architecture engine.
//!
//! Extracted from the production Mimer agent (`jarnan`). Bipolar (±1)
//! hypervectors with bind (element-wise multiply), bundle (normalize-sum),
//! unbind (= bind for bipolar), and permutation for positional encoding.

use crate::seeds::{all_seed_tokens, SEED_POLES};
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};

/// Default dimensionality used in production Mimer (10 000).
pub const DIMENSIONS: usize = 10_000;

/// Placeholder tokens that must never enter the HDC concept field.
const HDC_SENTINELS: &[&str] = &[
    "okänd", "okand", "unknown", "unk", "<unk>", "n/a", "na", "none", "null", "?", "??", "...",
];

/// True for tokens that must never receive an HDC vector or be imprinted.
pub fn is_hdc_sentinel(concept: &str) -> bool {
    let key = concept.trim().to_lowercase();
    if key.is_empty() {
        return true;
    }
    HDC_SENTINELS.contains(&key.as_str())
}

/// Why a concept name was rejected from the HDC vocabulary.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VocabRejectReason {
    /// Named sentinel / empty token.
    Sentinel,
    /// Pattern like `0480_prem-…`.
    LeadingDigits,
    /// Contains `_hdc` junk suffix.
    HdcSuffix,
    /// Pure numeric token.
    PureNumber,
}

impl VocabRejectReason {
    /// Stable snake_case label for metrics / logs.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Sentinel => "sentinel",
            Self::LeadingDigits => "leading_digits",
            Self::HdcSuffix => "hdc_suffix",
            Self::PureNumber => "pure_number",
        }
    }
}

static VOCAB_REJECTED_SENTINEL: AtomicU64 = AtomicU64::new(0);
static VOCAB_REJECTED_LEADING_DIGITS: AtomicU64 = AtomicU64::new(0);
static VOCAB_REJECTED_HDC_SUFFIX: AtomicU64 = AtomicU64::new(0);
static VOCAB_REJECTED_PURE_NUMBER: AtomicU64 = AtomicU64::new(0);

fn bump_reject(reason: VocabRejectReason) {
    let c = match reason {
        VocabRejectReason::Sentinel => &VOCAB_REJECTED_SENTINEL,
        VocabRejectReason::LeadingDigits => &VOCAB_REJECTED_LEADING_DIGITS,
        VocabRejectReason::HdcSuffix => &VOCAB_REJECTED_HDC_SUFFIX,
        VocabRejectReason::PureNumber => &VOCAB_REJECTED_PURE_NUMBER,
    };
    c.fetch_add(1, Ordering::Relaxed);
}

/// Snapshot of vocabulary-rejection counters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VocabRejectTotals {
    /// Sentinel / empty rejects.
    pub sentinel: u64,
    /// Leading-digit junk rejects.
    pub leading_digits: u64,
    /// `_hdc` suffix rejects.
    pub hdc_suffix: u64,
    /// Pure-number rejects.
    pub pure_number: u64,
    /// Sum of all reject counters.
    pub total: u64,
}

/// Snapshot of `vocab_rejected_total` counters.
pub fn vocab_rejected_totals() -> VocabRejectTotals {
    let sentinel = VOCAB_REJECTED_SENTINEL.load(Ordering::Relaxed);
    let leading_digits = VOCAB_REJECTED_LEADING_DIGITS.load(Ordering::Relaxed);
    let hdc_suffix = VOCAB_REJECTED_HDC_SUFFIX.load(Ordering::Relaxed);
    let pure_number = VOCAB_REJECTED_PURE_NUMBER.load(Ordering::Relaxed);
    VocabRejectTotals {
        sentinel,
        leading_digits,
        hdc_suffix,
        pure_number,
        total: sentinel + leading_digits + hdc_suffix + pure_number,
    }
}

/// Structural junk: `^\d+_`, contains `_hdc`, pure digits, named sentinels.
pub fn vocab_reject_reason(concept: &str) -> Option<VocabRejectReason> {
    let key = concept.trim().to_lowercase();
    if key.is_empty() || HDC_SENTINELS.contains(&key.as_str()) {
        return Some(VocabRejectReason::Sentinel);
    }
    if key.chars().all(|c| c.is_ascii_digit()) {
        return Some(VocabRejectReason::PureNumber);
    }
    if key.contains("_hdc") {
        return Some(VocabRejectReason::HdcSuffix);
    }
    if key.chars().next().is_some_and(|c| c.is_ascii_digit()) {
        if let Some(rest) = key.split_once('_') {
            if rest.0.chars().all(|c| c.is_ascii_digit()) {
                return Some(VocabRejectReason::LeadingDigits);
            }
        }
    }
    None
}

/// True when [`vocab_reject_reason`] would reject the concept.
pub fn is_vocab_rejected(concept: &str) -> bool {
    vocab_reject_reason(concept).is_some()
}

fn fnv1a64(s: &str) -> u64 {
    let mut hash: u64 = 0xcbf29ce484222325;
    for b in s.as_bytes() {
        hash ^= u64::from(*b);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    hash
}

/// Bipolar (±1) hypervector memory with bind / bundle / unbind.
///
/// # Determinism
///
/// Prefer [`HdcEngine::with_seed`]. Concept vectors are derived from
/// `base_seed XOR hash(concept)`, so the same seed + name always yields the
/// same vector. [`HdcEngine::new`] picks a fresh OS seed (non-deterministic).
pub struct HdcEngine {
    dimensions: usize,
    base_seed: u64,
    concepts: HashMap<String, Vec<f32>>,
    context: Vec<f32>,
    perm: Vec<usize>,
    inv_perm: Vec<usize>,
}

impl HdcEngine {
    /// Create an engine with a random seed (non-deterministic across runs).
    pub fn new(dimensions: usize) -> Self {
        let seed = rand::thread_rng().gen();
        Self::with_seed(dimensions, seed)
    }

    /// Create an engine with a fixed seed (deterministic lexicon + permutation).
    pub fn with_seed(dimensions: usize, seed: u64) -> Self {
        let mut rng = StdRng::seed_from_u64(seed);
        let mut perm: Vec<usize> = (0..dimensions).collect();
        for i in (1..dimensions).rev() {
            let j = rng.gen_range(0..=i);
            perm.swap(i, j);
        }
        let mut inv_perm = vec![0usize; dimensions];
        for (i, &p) in perm.iter().enumerate() {
            inv_perm[p] = i;
        }
        let mut eng = Self {
            dimensions,
            base_seed: seed,
            concepts: HashMap::new(),
            context: vec![0.0; dimensions],
            perm,
            inv_perm,
        };
        eng.seed_from_poles();
        eng.scrub_sentinels();
        eng
    }

    /// Dimensionality of this engine.
    pub fn dimensions(&self) -> usize {
        self.dimensions
    }

    /// Base seed used for deterministic vector generation.
    pub fn seed(&self) -> u64 {
        self.base_seed
    }

    fn random_vector_for(&self, concept: &str) -> Vec<f32> {
        let mut rng = StdRng::seed_from_u64(self.base_seed ^ fnv1a64(concept));
        (0..self.dimensions)
            .map(|_| if rng.gen_bool(0.5) { 1.0 } else { -1.0 })
            .collect()
    }

    /// Load seed poles as bundled semantic attractors.
    pub fn seed_from_poles(&mut self) {
        for token in all_seed_tokens() {
            let _ = self.encode(token);
        }
        for (pole, assoc) in SEED_POLES {
            let mut names = vec![(*pole).to_string()];
            names.extend(assoc.iter().map(|s| (*s).to_string()));
            if let Some(bundle) = self.bundle_names(&names) {
                self.concepts.insert((*pole).to_string(), bundle);
            }
        }
        if let Some(warm) = self.bundle_names(&["system".into(), "jag".into(), "stillhet".into()]) {
            self.context = warm;
        }
    }

    /// Encode (or look up) a concept as a bipolar hypervector.
    ///
    /// Rejected vocabulary returns the zero vector and does not enter the lexicon.
    pub fn encode(&mut self, concept: &str) -> Vec<f32> {
        let key = concept.to_lowercase();
        if let Some(reason) = vocab_reject_reason(&key) {
            bump_reject(reason);
            return vec![0.0; self.dimensions];
        }
        if let Some(v) = self.concepts.get(&key) {
            return v.clone();
        }
        let v = self.random_vector_for(&key);
        self.concepts.insert(key, v.clone());
        v
    }

    /// Remove sentinel symbols and structural junk from the lexicon.
    pub fn scrub_sentinels(&mut self) -> usize {
        let before = self.concepts.len();
        self.concepts.retain(|k, _| vocab_reject_reason(k).is_none());
        let removed = before.saturating_sub(self.concepts.len());
        if removed > 0 {
            if let Some(warm) =
                self.bundle_names(&["system".into(), "jag".into(), "stillhet".into()])
            {
                self.context = warm;
            }
        }
        removed
    }

    /// Imprint a concept into working context.
    pub fn imprint(&mut self, concept: &str, alpha: f32) -> f32 {
        if let Some(reason) = vocab_reject_reason(concept) {
            bump_reject(reason);
            return 0.0;
        }
        self.stimulate_soft(concept, alpha)
    }

    /// Stimulate a concept (blend into context with α=0.1) and return similarity.
    pub fn stimulate(&mut self, concept: &str) -> f32 {
        if vocab_reject_reason(concept).is_some() {
            return 0.0;
        }
        let v = self.encode(concept);
        let sim = cosine_similarity(&v, &self.context);
        self.blend_vector(&v, 0.1);
        sim
    }

    /// Apply permutation `times` times (position encoding for sequences).
    pub fn permute_n(&self, v: &[f32], times: usize) -> Vec<f32> {
        let mut out = v.to_vec();
        for _ in 0..times {
            out = self.permute(&out);
        }
        out
    }

    /// N-gram sequence encode (Rahimi/Kanerva-style).
    ///
    /// Bundles: (1) full positional sequence Σ Π^i(t_i) and (2) each n-gram
    /// window bound as t0 ⊛ Π(t1) ⊛ Π²(t2) … then summed.
    pub fn encode_ngram_sequence(&mut self, tokens: &[&str], n: usize) -> Vec<f32> {
        let n = n.clamp(1, 5);
        if tokens.is_empty() {
            return self.encode("__empty_seq__");
        }
        let encoded: Vec<Vec<f32>> = tokens.iter().map(|t| self.encode(t)).collect();
        let mut parts: Vec<Vec<f32>> = Vec::new();

        let seq: Vec<Vec<f32>> = encoded
            .iter()
            .enumerate()
            .map(|(i, v)| self.permute_n(v, i))
            .collect();
        parts.push(self.bundle(&seq));

        if n >= 2 && encoded.len() >= n {
            for start in 0..=(encoded.len() - n) {
                let mut bound = encoded[start].clone();
                for k in 1..n {
                    let pk = self.permute_n(&encoded[start + k], k);
                    bound = self.bind(&bound, &pk);
                }
                parts.push(bound);
            }
        } else if encoded.len() == 1 {
            parts.push(encoded[0].clone());
        }
        self.bundle(&parts)
    }

    /// Tokenize lightly and encode as trigrams.
    pub fn encode_text_sequence(&mut self, text: &str) -> Vec<f32> {
        let toks: Vec<&str> = text
            .split_whitespace()
            .map(|w| w.trim_matches(|c: char| !c.is_alphanumeric() && c != '-'))
            .filter(|w| w.len() > 1)
            .take(48)
            .collect();
        self.encode_ngram_sequence(&toks, 3)
    }

    /// Bind two bipolar vectors (element-wise multiply). Self-inverse for ±1.
    pub fn bind(&self, a: &[f32], b: &[f32]) -> Vec<f32> {
        a.iter().zip(b.iter()).map(|(x, y)| x * y).collect()
    }

    /// Unbind: for bipolar vectors identical to [`Self::bind`].
    pub fn unbind(&self, bound: &[f32], b: &[f32]) -> Vec<f32> {
        self.bind(bound, b)
    }

    /// Bundle (superpose) vectors and L2-normalize.
    pub fn bundle(&self, vectors: &[Vec<f32>]) -> Vec<f32> {
        let mut acc = vec![0.0f32; self.dimensions];
        for v in vectors {
            for (a, x) in acc.iter_mut().zip(v.iter()) {
                *a += *x;
            }
        }
        normalize(&mut acc);
        acc
    }

    /// Apply the engine's random permutation (position encoding).
    pub fn permute(&self, v: &[f32]) -> Vec<f32> {
        let mut out = vec![0.0f32; self.dimensions];
        for (i, &p) in self.perm.iter().enumerate() {
            out[i] = v.get(p).copied().unwrap_or(0.0);
        }
        out
    }

    /// Inverse permutation — needed for sequence unbind.
    pub fn inverse_permute(&self, v: &[f32]) -> Vec<f32> {
        let mut out = vec![0.0f32; self.dimensions];
        for (i, &p) in self.inv_perm.iter().enumerate() {
            out[i] = v.get(p).copied().unwrap_or(0.0);
        }
        out
    }

    /// Cosine similarity in \[-1, 1\]. Zero vectors yield 0.0 (no NaN).
    pub fn similarity(&self, a: &[f32], b: &[f32]) -> f32 {
        cosine_similarity(a, b)
    }

    /// Snapshot of working context.
    pub fn context_vector(&self) -> &[f32] {
        &self.context
    }

    /// Blend an arbitrary vector into working context.
    pub fn blend_vector(&mut self, v: &[f32], alpha: f32) {
        let a = alpha.clamp(0.0, 1.0);
        let keep = 1.0 - a;
        for (c, x) in self.context.iter_mut().zip(v.iter()) {
            *c = keep * *c + a * *x;
        }
        normalize(&mut self.context);
    }

    /// Encode simple numeric sensor features into HDC context.
    pub fn integrate_sensors(&mut self, load: f64, temp: f64, hour_frac: f64, surprise_hint: f64) {
        if load > 4.0 {
            self.stimulate("rörelse");
            self.stimulate("system");
        } else {
            self.stimulate("stillhet");
        }
        if temp > 70.0 {
            self.stimulate("värme");
            self.stimulate("energi");
        }
        if !(0.2..=0.8).contains(&hour_frac) {
            self.stimulate("mörker");
        } else {
            self.stimulate("ljus");
        }
        if surprise_hint > 0.4 {
            self.stimulate("kaos");
            self.stimulate("överraskning");
        }
        self.stimulate("jag");
    }

    /// Top-k concepts by similarity to working context.
    pub fn dominant(&self, k: usize) -> Vec<(String, f32)> {
        let mut scored: Vec<(String, f32)> = self
            .concepts
            .iter()
            .filter(|(n, _)| vocab_reject_reason(n).is_none())
            .map(|(n, v)| (n.clone(), cosine_similarity(v, &self.context)))
            .collect();
        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        scored.truncate(k);
        scored
    }

    /// Dominant concepts excluding known noise poles.
    pub fn dominant_excluding(&self, k: usize, exclude: &[&str]) -> Vec<(String, f32)> {
        let mut scored: Vec<(String, f32)> = self
            .concepts
            .iter()
            .filter(|(n, _)| {
                vocab_reject_reason(n).is_none()
                    && !exclude
                        .iter()
                        .any(|e| e.eq_ignore_ascii_case(n.as_str()))
                    && !n.starts_with("__role_")
                    && !n.starts_with("__empty")
            })
            .map(|(n, v)| (n.clone(), cosine_similarity(v, &self.context)))
            .collect();
        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        scored.truncate(k);
        scored
    }

    /// Soft stimulate — smaller context blend.
    pub fn stimulate_soft(&mut self, concept: &str, alpha: f32) -> f32 {
        if vocab_reject_reason(concept).is_some() {
            return 0.0;
        }
        let v = self.encode(concept);
        let sim = cosine_similarity(&v, &self.context);
        self.blend_vector(&v, alpha.clamp(0.0, 1.0));
        sim
    }

    /// Strong imprint: bundle named concepts and pull context toward them.
    pub fn imprint_bundle(&mut self, names: &[String], alpha: f32) -> f32 {
        let clean: Vec<String> = names
            .iter()
            .filter(|n| {
                if let Some(reason) = vocab_reject_reason(n) {
                    bump_reject(reason);
                    false
                } else {
                    true
                }
            })
            .cloned()
            .collect();
        if clean.is_empty() {
            return 0.0;
        }
        let vecs: Vec<Vec<f32>> = clean.iter().map(|n| self.encode(n)).collect();
        let bundle = self.bundle(&vecs);
        let sim = cosine_similarity(&bundle, &self.context);
        self.blend_vector(&bundle, alpha.clamp(0.0, 1.0));
        sim
    }

    /// Score how present named concepts are in working context.
    pub fn score_named(&self, names: &[String]) -> Vec<(String, f32)> {
        let mut out = Vec::new();
        for n in names {
            let key = n.to_lowercase();
            if let Some(v) = self.concepts.get(&key) {
                out.push((key, cosine_similarity(v, &self.context)));
            }
        }
        out.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        out
    }

    /// Recover token probe at position `i` from a positional sequence vector.
    pub fn unbind_sequence_position(&self, sequence: &[f32], position: usize) -> Vec<f32> {
        let mut out = sequence.to_vec();
        for _ in 0..position {
            out = self.inverse_permute(&out);
        }
        out
    }

    /// Best lexicon match for a recovered sequence-position probe.
    pub fn recall_sequence_token(
        &mut self,
        sequence: &[f32],
        position: usize,
        candidates: &[&str],
    ) -> Option<(String, f32)> {
        let probe = self.unbind_sequence_position(sequence, position);
        let mut best: Option<(String, f32)> = None;
        for c in candidates {
            let v = self.encode(c);
            let sim = cosine_similarity(&probe, &v);
            if best.as_ref().map(|(_, s)| sim > *s).unwrap_or(true) {
                best = Some(((*c).to_string(), sim));
            }
        }
        best
    }

    /// Downsample context magnitude into `n` drive values in \[0, 1\].
    pub fn context_drive(&self, n: usize) -> Vec<f32> {
        if n == 0 || self.context.is_empty() {
            return vec![0.0; n];
        }
        let step = (self.dimensions / n).max(1);
        (0..n)
            .map(|i| (self.context[(i * step) % self.dimensions] + 1.0) * 0.5)
            .collect()
    }

    /// L2 magnitude of the context vector.
    pub fn context_magnitude(&self) -> f64 {
        let mag: f32 = self.context.iter().map(|x| x * x).sum::<f32>().sqrt();
        mag as f64
    }

    /// Number of concepts currently in the lexicon.
    pub fn concept_count(&self) -> usize {
        self.concepts.len()
    }

    /// Top-k concepts by cosine similarity to an arbitrary query vector.
    pub fn query_similar(&self, query: &[f32], k: usize) -> Vec<(String, f32)> {
        let mut scored: Vec<(String, f32)> = self
            .concepts
            .iter()
            .map(|(name, vec)| (name.clone(), cosine_similarity(query, vec)))
            .collect();
        scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
        scored.truncate(k);
        scored
    }

    /// Read-only view of all encoded concept names.
    pub fn concept_names(&self) -> Vec<&str> {
        self.concepts.keys().map(|s| s.as_str()).collect()
    }

    /// Absorb a harvested seed pole: encode associations as a bundled concept.
    pub fn harvest_seed(&mut self, name: &str, associations: &[String]) -> f32 {
        for w in associations {
            let _ = self.encode(w);
        }
        let mut names = associations.to_vec();
        if !names.iter().any(|n| n == name) {
            names.insert(0, name.to_string());
        }
        if let Some(bundle) = self.bundle_names(&names) {
            self.concepts.insert(name.to_lowercase(), bundle);
        }
        self.stimulate(name)
    }

    /// Subtract noise poles from working context.
    pub fn decay_poles(&mut self, names: &[&str], amount: f32) {
        let amount = amount.clamp(0.0, 0.8);
        if amount < 1e-6 || names.is_empty() {
            return;
        }
        let poles: Vec<Vec<f32>> = names
            .iter()
            .filter_map(|n| self.concepts.get(&n.to_lowercase()).cloned())
            .collect();
        for v in &poles {
            let sim = cosine_similarity(&self.context, v);
            if sim <= 0.02 {
                continue;
            }
            let a = (amount * sim).clamp(0.0, 0.55);
            for (c, x) in self.context.iter_mut().zip(v.iter()) {
                *c -= a * *x;
            }
        }
        normalize(&mut self.context);
    }

    /// Default noise poles that can drown claim subjects in dialogue trains.
    pub const NOISE_POLES: &'static [&'static str] = &[
        "relation",
        "du",
        "bro",
        "jag",
        "btc",
        "eth",
        "long",
        "short",
        "leverage",
        "bps",
        "kan",
        "common",
        "break",
        "history",
        "alert",
        "block",
        "content-filter",
        "shannon-hartley",
        "anmärkningsvärt",
    ];

    fn bundle_names(&mut self, names: &[String]) -> Option<Vec<f32>> {
        if names.is_empty() {
            return None;
        }
        let vecs: Vec<Vec<f32>> = names.iter().map(|n| self.encode(n)).collect();
        Some(self.bundle(&vecs))
    }
}

fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
    let mut dot = 0.0f32;
    let mut na = 0.0f32;
    let mut nb = 0.0f32;
    for (x, y) in a.iter().zip(b.iter()) {
        dot += x * y;
        na += x * x;
        nb += y * y;
    }
    let d = na.sqrt() * nb.sqrt();
    if d < 1e-12 {
        0.0
    } else {
        dot / d
    }
}

/// Pack bipolar vector to bits (sign ≥ 0 → 1). 10_000 dims → 1250 bytes.
pub fn pack_bipolar(v: &[f32]) -> Vec<u8> {
    let mut out = vec![0u8; v.len().div_ceil(8)];
    for (i, &x) in v.iter().enumerate() {
        if x >= 0.0 {
            out[i / 8] |= 1 << (i % 8);
        }
    }
    out
}

/// Unpack bit-packed bipolar vector to ±1.0 floats.
pub fn unpack_bipolar(packed: &[u8], dimensions: usize) -> Vec<f32> {
    let mut out = vec![-1.0f32; dimensions];
    for i in 0..dimensions {
        let byte = packed.get(i / 8).copied().unwrap_or(0);
        if byte & (1 << (i % 8)) != 0 {
            out[i] = 1.0;
        }
    }
    out
}

fn normalize(v: &mut [f32]) {
    let mag: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
    if mag > 1e-12 {
        for x in v.iter_mut() {
            *x /= mag;
        }
    }
}

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

    #[test]
    fn bind_unbind_roundtrip() {
        let mut h = HdcEngine::with_seed(512, 42);
        let a = h.encode("alpha_probe");
        let b = h.encode("beta_probe");
        let bound = h.bind(&a, &b);
        let recovered = h.unbind(&bound, &b);
        assert!(h.similarity(&recovered, &a) > 0.9);
    }

    #[test]
    fn pack_bipolar_roundtrip_10k() {
        let mut h = HdcEngine::with_seed(DIMENSIONS, 7);
        h.stimulate("sverige");
        h.stimulate("demokrati");
        let packed = pack_bipolar(h.context_vector());
        assert_eq!(packed.len(), DIMENSIONS.div_ceil(8));
        let unpacked = unpack_bipolar(&packed, DIMENSIONS);
        assert_eq!(unpacked.len(), DIMENSIONS);
        for (a, b) in h.context_vector().iter().zip(unpacked.iter()) {
            assert_eq!(a >= &0.0, b >= &0.0);
        }
        let sim = h.similarity(h.context_vector(), &unpacked);
        assert!(sim > 0.9, "bipolar pack roundtrip sim={sim}");
    }

    #[test]
    fn zero_vector_similarity_is_zero() {
        let h = HdcEngine::with_seed(64, 1);
        let z = vec![0.0f32; 64];
        let a = vec![1.0f32; 64];
        assert_eq!(h.similarity(&z, &a), 0.0);
        assert_eq!(h.similarity(&z, &z), 0.0);
    }
}