geoit 0.0.2

Exact geometric algebra with governed multivectors
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
//! Blade representation for geometric algebra.
//!
//! A blade is a sorted set of generator indices. The grade is the length.
//! The scalar blade is empty.
//!
//! For algebras with ≤ 8 generators per blade (covers CGA(3) and below),
//! all storage is inline — no heap allocation. For larger blades
//! (Veronese/QGA and above), spills to heap automatically.

use std::cmp::Ordering;

// ═══════════════════════════════════════════════════════════
// INLINE VEC
// ═══════════════════════════════════════════════════════════

const INLINE_CAP: usize = 8;

/// A small sorted vector of u16, inline for up to 8 elements.
/// Zero dependencies. Zero heap allocation for grade ≤ 8.
#[derive(Clone)]
#[allow(clippy::box_collection)]
pub struct BladeKey {
    /// Inline storage for up to INLINE_CAP elements.
    inline: [u16; INLINE_CAP],
    /// Number of elements (grade). If len > INLINE_CAP, `heap` is used.
    len: u8,
    /// Heap overflow for grade > INLINE_CAP.
    heap: Option<Vec<u16>>,
}

impl BladeKey {
    /// The scalar blade (grade 0, empty).
    pub const SCALAR: BladeKey = BladeKey {
        inline: [0; INLINE_CAP],
        len: 0,
        heap: None,
    };

    /// Create from a single generator index.
    #[inline]
    pub fn generator(k: u16) -> Self {
        let mut b = Self::SCALAR;
        b.inline[0] = k;
        b.len = 1;
        b
    }

    /// Create from a sorted slice of generator indices.
    /// Caller guarantees: sorted, no duplicates.
    pub fn from_sorted(indices: &[u16]) -> Self {
        debug_assert!(
            indices.windows(2).all(|w| w[0] < w[1]),
            "BladeKey::from_sorted: indices must be strictly sorted"
        );
        if indices.len() <= INLINE_CAP {
            let mut inline = [0u16; INLINE_CAP];
            inline[..indices.len()].copy_from_slice(indices);
            BladeKey {
                inline,
                len: indices.len() as u8,
                heap: None,
            }
        } else {
            BladeKey {
                inline: [0; INLINE_CAP],
                len: indices.len() as u8,
                heap: Some(indices.to_vec()),
            }
        }
    }

    /// Create the pseudoscalar blade for n generators: [0, 1, 2, ..., n-1].
    pub fn pseudoscalar(n: u32) -> Self {
        let indices: Vec<u16> = (0..n as u16).collect();
        Self::from_sorted(&indices)
    }

    /// Grade (number of participating generators).
    #[inline]
    pub fn grade(&self) -> u8 {
        self.len
    }

    /// Access the sorted generator indices as a slice.
    #[inline]
    pub fn indices(&self) -> &[u16] {
        if let Some(ref h) = self.heap {
            h.as_slice()
        } else {
            &self.inline[..self.len as usize]
        }
    }

    /// Is this the scalar blade (grade 0)?
    #[inline]
    pub fn is_scalar(&self) -> bool {
        self.len == 0
    }

    /// Does generator k participate in this blade?
    #[inline]
    pub fn contains_generator(&self, k: u16) -> bool {
        self.indices().binary_search(&k).is_ok()
    }

    /// Symmetric difference of two sorted blade keys.
    /// Result is the blade of generators in exactly one of `a` or `b`.
    /// This is the blade mask of the geometric product result.
    pub fn symmetric_difference(a: &BladeKey, b: &BladeKey) -> BladeKey {
        let ai = a.indices();
        let bi = b.indices();
        let mut result = Vec::with_capacity(ai.len() + bi.len());
        let (mut i, mut j) = (0, 0);
        while i < ai.len() && j < bi.len() {
            match ai[i].cmp(&bi[j]) {
                Ordering::Less => {
                    result.push(ai[i]);
                    i += 1;
                }
                Ordering::Greater => {
                    result.push(bi[j]);
                    j += 1;
                }
                Ordering::Equal => {
                    i += 1;
                    j += 1;
                } // cancel
            }
        }
        result.extend_from_slice(&ai[i..]);
        result.extend_from_slice(&bi[j..]);
        BladeKey::from_sorted(&result)
    }

    /// Intersection of two sorted blade keys.
    /// These are the generators that cancel in the geometric product.
    pub fn intersection(a: &BladeKey, b: &BladeKey) -> BladeKey {
        let ai = a.indices();
        let bi = b.indices();
        let mut result = Vec::with_capacity(ai.len().min(bi.len()));
        let (mut i, mut j) = (0, 0);
        while i < ai.len() && j < bi.len() {
            match ai[i].cmp(&bi[j]) {
                Ordering::Less => {
                    i += 1;
                }
                Ordering::Greater => {
                    j += 1;
                }
                Ordering::Equal => {
                    result.push(ai[i]);
                    i += 1;
                    j += 1;
                }
            }
        }
        BladeKey::from_sorted(&result)
    }
}

// ═══════════════════════════════════════════════════════════
// CANONICAL REORDER SIGN
// ═══════════════════════════════════════════════════════════

/// Sign from reordering generators of blade `a` past generators of blade `b`
/// into canonical (sorted) order. Returns +1 or -1.
///
/// For each element in b, count how many elements in a are greater.
/// The parity of the total count determines the sign.
pub fn canonical_reorder(a: &BladeKey, b: &BladeKey) -> i8 {
    let ai = a.indices();
    let bi = b.indices();
    let mut swaps = 0u32;
    // For each element in b, count elements in a that are strictly greater
    // Using the fact that both are sorted, we can do this efficiently
    let mut a_ptr = ai.len(); // start from the end
    for &bk in bi.iter().rev() {
        // Count elements in a > bk
        while a_ptr > 0 && ai[a_ptr - 1] > bk {
            a_ptr -= 1;
        }
        swaps += (ai.len() - a_ptr) as u32;
    }
    if swaps & 1 == 0 {
        1
    } else {
        -1
    }
}

// ═══════════════════════════════════════════════════════════
// TRAIT IMPLEMENTATIONS
// ═══════════════════════════════════════════════════════════

impl PartialEq for BladeKey {
    fn eq(&self, other: &Self) -> bool {
        self.indices() == other.indices()
    }
}

impl Eq for BladeKey {}

impl PartialOrd for BladeKey {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for BladeKey {
    fn cmp(&self, other: &Self) -> Ordering {
        // Grade first (lower grade comes first), then lexicographic on indices
        self.grade()
            .cmp(&other.grade())
            .then_with(|| self.indices().cmp(other.indices()))
    }
}

impl std::hash::Hash for BladeKey {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.indices().hash(state);
    }
}

impl std::fmt::Debug for BladeKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Blade{:?}", self.indices())
    }
}

impl std::fmt::Display for BladeKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.is_scalar() {
            write!(f, "1")
        } else {
            write!(f, "e")?;
            for &k in self.indices() {
                write!(f, "{}", k)?;
            }
            Ok(())
        }
    }
}

// ═══════════════════════════════════════════════════════════
// LEGACY COMPATIBILITY
// ═══════════════════════════════════════════════════════════

/// Type alias preserved for migration. Will be removed in v0.1.0.
pub type BladeMask = u64;

/// Convert a legacy u64 bitmask to a BladeKey.
/// Bit k set means generator k participates.
pub fn mask_to_blade(mask: BladeMask) -> BladeKey {
    if mask == 0 {
        return BladeKey::SCALAR;
    }
    let mut indices = Vec::new();
    let mut m = mask;
    while m != 0 {
        let k = m.trailing_zeros() as u16;
        indices.push(k);
        m &= m - 1;
    }
    BladeKey::from_sorted(&indices)
}

/// Convert a BladeKey back to a u64 bitmask.
/// Only valid for generators < 64.
pub fn blade_to_mask(blade: &BladeKey) -> BladeMask {
    let mut mask: u64 = 0;
    for &k in blade.indices() {
        debug_assert!(k < 64, "blade_to_mask: generator {} exceeds u64 range", k);
        mask |= 1u64 << k;
    }
    mask
}

/// Grade of a legacy bitmask (popcount).
#[inline]
pub fn grade(mask: BladeMask) -> u8 {
    mask.count_ones() as u8
}

/// Does generator k participate in this legacy bitmask?
#[inline]
pub fn contains_generator(mask: BladeMask, gen: u8) -> bool {
    mask & (1u64 << gen) != 0
}

/// Legacy canonical reorder on u64 bitmasks.
pub fn canonical_reorder_mask(a: BladeMask, b: BladeMask) -> i8 {
    let mut a = a >> 1;
    let mut swaps = 0u32;
    while a != 0 {
        swaps += (a & b).count_ones();
        a >>= 1;
    }
    if swaps & 1 == 0 {
        1
    } else {
        -1
    }
}

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

    // ─── BladeKey basics ───

    #[test]
    fn scalar_blade() {
        let s = BladeKey::SCALAR;
        assert_eq!(s.grade(), 0);
        assert!(s.is_scalar());
        assert_eq!(s.indices(), &[]);
    }

    #[test]
    fn single_generator() {
        let b = BladeKey::generator(2);
        assert_eq!(b.grade(), 1);
        assert!(!b.is_scalar());
        assert_eq!(b.indices(), &[2]);
        assert!(b.contains_generator(2));
        assert!(!b.contains_generator(0));
    }

    #[test]
    fn from_sorted_inline() {
        let b = BladeKey::from_sorted(&[0, 2, 5]);
        assert_eq!(b.grade(), 3);
        assert_eq!(b.indices(), &[0, 2, 5]);
        assert!(b.heap.is_none());
    }

    #[test]
    fn from_sorted_heap() {
        let indices: Vec<u16> = (0..10).collect();
        let b = BladeKey::from_sorted(&indices);
        assert_eq!(b.grade(), 10);
        assert_eq!(b.indices(), &indices[..]);
        assert!(b.heap.is_some());
    }

    #[test]
    fn pseudoscalar() {
        let ps = BladeKey::pseudoscalar(5);
        assert_eq!(ps.grade(), 5);
        assert_eq!(ps.indices(), &[0, 1, 2, 3, 4]);
    }

    // ─── Symmetric difference ───

    #[test]
    fn sym_diff_disjoint() {
        let a = BladeKey::from_sorted(&[0, 1]);
        let b = BladeKey::from_sorted(&[2, 3]);
        let r = BladeKey::symmetric_difference(&a, &b);
        assert_eq!(r.indices(), &[0, 1, 2, 3]);
    }

    #[test]
    fn sym_diff_overlap() {
        let a = BladeKey::from_sorted(&[0, 1, 2]);
        let b = BladeKey::from_sorted(&[1, 2, 3]);
        let r = BladeKey::symmetric_difference(&a, &b);
        assert_eq!(r.indices(), &[0, 3]);
    }

    #[test]
    fn sym_diff_identical() {
        let a = BladeKey::from_sorted(&[0, 1]);
        let r = BladeKey::symmetric_difference(&a, &a);
        assert!(r.is_scalar());
    }

    #[test]
    fn sym_diff_with_scalar() {
        let a = BladeKey::from_sorted(&[1, 3]);
        let r = BladeKey::symmetric_difference(&a, &BladeKey::SCALAR);
        assert_eq!(r, a);
    }

    // ─── Intersection ───

    #[test]
    fn intersection_overlap() {
        let a = BladeKey::from_sorted(&[0, 1, 2]);
        let b = BladeKey::from_sorted(&[1, 2, 3]);
        let r = BladeKey::intersection(&a, &b);
        assert_eq!(r.indices(), &[1, 2]);
    }

    #[test]
    fn intersection_disjoint() {
        let a = BladeKey::from_sorted(&[0, 1]);
        let b = BladeKey::from_sorted(&[2, 3]);
        let r = BladeKey::intersection(&a, &b);
        assert!(r.is_scalar());
    }

    // ─── Canonical reorder ───

    #[test]
    fn reorder_identity() {
        // e0 * e1 → already sorted → +1
        let a = BladeKey::generator(0);
        let b = BladeKey::generator(1);
        assert_eq!(canonical_reorder(&a, &b), 1);
    }

    #[test]
    fn reorder_swap() {
        // e1 * e0 → one swap → -1
        let a = BladeKey::generator(1);
        let b = BladeKey::generator(0);
        assert_eq!(canonical_reorder(&a, &b), -1);
    }

    #[test]
    fn reorder_e01_e2() {
        let a = BladeKey::from_sorted(&[0, 1]);
        let b = BladeKey::generator(2);
        assert_eq!(canonical_reorder(&a, &b), 1);
    }

    #[test]
    fn reorder_e2_e01() {
        let a = BladeKey::generator(2);
        let b = BladeKey::from_sorted(&[0, 1]);
        assert_eq!(canonical_reorder(&a, &b), 1);
    }

    #[test]
    fn reorder_e1_e02() {
        let a = BladeKey::generator(1);
        let b = BladeKey::from_sorted(&[0, 2]);
        assert_eq!(canonical_reorder(&a, &b), -1);
    }

    #[test]
    fn reorder_self_e01() {
        let a = BladeKey::from_sorted(&[0, 1]);
        assert_eq!(canonical_reorder(&a, &a), -1);
    }

    // ─── Verify new BladeKey reorder matches legacy bitmask reorder ───

    #[test]
    fn reorder_matches_legacy() {
        for a_mask in 0u64..32 {
            for b_mask in 0u64..32 {
                let legacy = canonical_reorder_mask(a_mask, b_mask);
                let a_blade = mask_to_blade(a_mask);
                let b_blade = mask_to_blade(b_mask);
                let new = canonical_reorder(&a_blade, &b_blade);
                assert_eq!(
                    legacy, new,
                    "reorder mismatch: a={:#b} b={:#b} legacy={} new={}",
                    a_mask, b_mask, legacy, new
                );
            }
        }
    }

    // ─── Ordering ───

    #[test]
    fn ord_grade_first() {
        let scalar = BladeKey::SCALAR;
        let vector = BladeKey::generator(0);
        let bivector = BladeKey::from_sorted(&[0, 1]);
        assert!(scalar < vector);
        assert!(vector < bivector);
    }

    #[test]
    fn ord_same_grade_lexicographic() {
        let e01 = BladeKey::from_sorted(&[0, 1]);
        let e02 = BladeKey::from_sorted(&[0, 2]);
        let e12 = BladeKey::from_sorted(&[1, 2]);
        assert!(e01 < e02);
        assert!(e02 < e12);
    }

    // ─── Legacy conversion ───

    #[test]
    fn mask_roundtrip() {
        for mask in 0u64..64 {
            let blade = mask_to_blade(mask);
            let back = blade_to_mask(&blade);
            assert_eq!(mask, back, "roundtrip failed for mask {:#b}", mask);
        }
    }

    #[test]
    fn legacy_grade() {
        assert_eq!(grade(0b000), 0);
        assert_eq!(grade(0b001), 1);
        assert_eq!(grade(0b011), 2);
        assert_eq!(grade(0b111), 3);
    }
}