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
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
//! Governance builder: construct a `Governance` with named classes and constructions.
//!
//! ```ignore
//! let gov = GovernanceBuilder::new(algebra)
//!     .class("Point", GeomClassBuilder::new(&algebra)
//!         .grades(&[1])
//!         .null_constraint()
//!         .normalization(&einf, 1)
//!         .build())
//!     .construction("Point", 0, 2, point_body)
//!     .build();
//!
//! let p = gov.construct("Point", &params)?;
//! let geoit = gov.govern(&mv, "Point")?;
//! ```

use crate::algebra::mv::Mv;
use crate::algebra::signature::Signature;
use crate::governance::construction::{Construction, ConstructionError};
use crate::governance::expr::ContextShape;
use crate::governance::expr::Expr;
use crate::governance::field::FieldOp;
use crate::governance::geoit::Geoit;
use crate::governance::geom_class::GeomClass;
use crate::governance::geom_class::{inner_product_poly, norm_poly};
use crate::governance::governance::Governance;
use crate::governance::poly::Poly;
use crate::governance::profile::GeneratorProfile;
use crate::governance::reading::VariableMap;
use crate::governance::rule::{apply_transform, TransformOp, TransformRule};
use crate::governance::{self, GovernanceError};
use crate::scalar::{Rat, Scalar};

use super::algebra::Algebra;

// ═══════════════════════════════════════════════════════════
// GEOM CLASS BUILDER
// ═══════════════════════════════════════════════════════════

/// Builder for constructing a `GeomClass` with constraint helpers.
pub struct GeomClassBuilder<'a> {
    algebra: &'a Algebra,
    grades: Vec<u8>,
    equations: Vec<Poly>,
    inequalities: Vec<Poly>,
    field_op: FieldOp,
    expected_profile: Option<GeneratorProfile>,
}

impl<'a> GeomClassBuilder<'a> {
    pub fn new(algebra: &'a Algebra) -> Self {
        GeomClassBuilder {
            algebra,
            grades: Vec::new(),
            equations: Vec::new(),
            inequalities: Vec::new(),
            field_op: FieldOp::default(),
            expected_profile: None,
        }
    }

    /// Set permitted grades.
    pub fn grades(mut self, gs: &[u8]) -> Self {
        self.grades = gs.to_vec();
        self
    }

    /// Add a raw polynomial equation (must equal zero).
    pub fn equation(mut self, poly: Poly) -> Self {
        self.equations.push(poly);
        self
    }

    /// Add a raw polynomial inequality (must be nonzero).
    pub fn inequality(mut self, poly: Poly) -> Self {
        self.inequalities.push(poly);
        self
    }

    /// Add null constraint: norm² = 0.
    /// Shorthand for the quadratic equation that the Mv's self-inner-product vanishes.
    pub fn null_constraint(mut self) -> Self {
        let gm = self.grade_mask();
        let vm = VariableMap::for_grade_mask(self.algebra.sig(), gm);
        let np = norm_poly(self.algebra.sig(), gm, vm.num_vars, &vm.mask_to_var);
        if !np.is_zero() {
            self.equations.push(np);
        }
        self
    }

    /// Add normalization: ⟨reference, X⟩ = value.
    /// Common usage: `.normalization(&einf, 1)` for CGA point normalization.
    pub fn normalization(mut self, reference: &Mv, value: i64) -> Self {
        let gm = self.grade_mask();
        let vm = VariableMap::for_grade_mask(self.algebra.sig(), gm);
        let ip = inner_product_poly(
            reference,
            self.algebra.sig(),
            gm,
            Rat::from(value),
            vm.num_vars,
            &vm.mask_to_var,
        );
        if !ip.is_zero() {
            self.equations.push(ip);
        }
        self
    }

    /// Set the field operation for rendering/evaluation.
    pub fn field_op(mut self, op: FieldOp) -> Self {
        self.field_op = op;
        self
    }

    /// Set the expected generator participation profile.
    /// `govern()` will reject Mvs whose profile uses generators outside this mask.
    pub fn expected_profile(mut self, profile: GeneratorProfile) -> Self {
        self.expected_profile = Some(profile);
        self
    }

    /// Build the GeomClass.
    pub fn build(self) -> GeomClass {
        GeomClass {
            grade_mask: self.grade_mask(),
            equations: self.equations,
            inequalities: self.inequalities,
            field_op: self.field_op,
            expected_profile: self.expected_profile,
        }
    }

    fn grade_mask(&self) -> u64 {
        let mut mask = 0u64;
        for &g in &self.grades {
            mask |= 1u64 << g;
        }
        mask
    }
}

// ═══════════════════════════════════════════════════════════
// GOVERNANCE BUILDER
// ═══════════════════════════════════════════════════════════

/// Builder for constructing a `Governance` with string-keyed access.
pub struct GovernanceBuilder {
    algebra: Algebra,
    class_names: Vec<String>,
    classes: Vec<GeomClass>,
    construction_names: Vec<String>,
    constructions: Vec<Construction>,
    probe: Option<crate::governance::field::ProbeSpec>,
    rule_names: Vec<String>,
    rules: Vec<TransformRule>,
}

impl GovernanceBuilder {
    /// Start building a governance from an algebra context.
    pub fn new(algebra: Algebra) -> Self {
        GovernanceBuilder {
            algebra,
            class_names: Vec::new(),
            classes: Vec::new(),
            construction_names: Vec::new(),
            constructions: Vec::new(),
            probe: None,
            rule_names: Vec::new(),
            rules: Vec::new(),
        }
    }

    /// Add a named geometric class.
    pub fn class(mut self, name: &str, class: GeomClass) -> Self {
        self.class_names.push(name.to_string());
        self.classes.push(class);
        self
    }

    /// Add a named construction.
    /// `class_name` is the class this construction builds objects for.
    /// `arity` is the number of scalar parameters.
    /// `body` is the expression tree.
    pub fn construction(mut self, name: &str, class_name: &str, arity: usize, body: Expr) -> Self {
        let class_index = self
            .class_names
            .iter()
            .position(|n| n == class_name)
            .unwrap_or_else(|| {
                panic!(
                    "GovernanceBuilder: class '{}' not found (add it before its construction)",
                    class_name
                )
            });
        self.construction_names.push(name.to_string());
        self.constructions.push(Construction {
            class_index,
            arity,
            body,
        });
        self
    }

    /// Set the probe specification for rendering.
    pub fn probe(mut self, construction_name: &str, arity: usize) -> Self {
        let idx = self
            .construction_names
            .iter()
            .position(|n| n == construction_name)
            .unwrap_or_else(|| {
                panic!(
                    "GovernanceBuilder: construction '{}' not found for probe",
                    construction_name
                )
            });
        self.probe = Some(crate::governance::field::ProbeSpec {
            construction_index: idx,
            arity,
        });
        self
    }

    /// Add a named transformation rule.
    /// `input_class_names` are the classes this rule takes as input.
    /// `output_class_name` is the class the result belongs to.
    /// `op` is the algebraic operation to perform.
    pub fn rule(
        mut self,
        name: &str,
        input_class_names: &[&str],
        output_class_name: &str,
        op: TransformOp,
    ) -> Self {
        let input_classes: Vec<usize> = input_class_names
            .iter()
            .map(|n| {
                self.class_names
                    .iter()
                    .position(|cn| cn == n)
                    .unwrap_or_else(|| {
                        panic!(
                            "GovernanceBuilder: class '{}' not found for rule '{}'",
                            n, name
                        )
                    })
            })
            .collect();
        let output_class = self
            .class_names
            .iter()
            .position(|cn| cn == output_class_name)
            .unwrap_or_else(|| {
                panic!(
                    "GovernanceBuilder: output class '{}' not found for rule '{}'",
                    output_class_name, name
                )
            });
        self.rule_names.push(name.to_string());
        self.rules.push(TransformRule {
            name: name.to_string(),
            input_classes,
            output_class,
            operation: op,
            reading_derivation: crate::governance::rule::ReadingDerivation::Rederive,
        });
        self
    }

    /// Build the Governance.
    pub fn build(self) -> NamedGovernance {
        // Validate all construction expression trees
        let derived_gen_count = self.algebra.derived_gens().len();
        let construction_count = self.constructions.len();
        for (i, c) in self.constructions.iter().enumerate() {
            let shape =
                ContextShape::for_construction(c.arity, derived_gen_count, construction_count);
            if let Err(errors) = c.body.validate(&shape) {
                panic!(
                    "GovernanceBuilder: construction '{}' (index {}) has invalid expression tree: {:?}",
                    self.construction_names[i], i, errors
                );
            }
        }

        let gov = Governance {
            sig: *self.algebra.sig(),
            derived_gens: self.algebra.derived_gens().to_vec(),
            geom_classes: self.classes,
            constructions: self.constructions,
            probe: self.probe,
            transform_rules: self.rules,
        };
        NamedGovernance {
            gov: std::sync::Arc::new(gov),
            class_names: self.class_names,
            construction_names: self.construction_names,
            rule_names: self.rule_names,
        }
    }
}

// ═══════════════════════════════════════════════════════════
// NAMED GOVERNANCE
// ═══════════════════════════════════════════════════════════

/// A `Governance` with string-keyed access to classes and constructions.
///
/// Holds the Governance in an `Arc` for efficient sharing with Geoits.
#[derive(Clone, Debug)]
pub struct NamedGovernance {
    gov: std::sync::Arc<Governance>,
    class_names: Vec<String>,
    construction_names: Vec<String>,
    rule_names: Vec<String>,
}

impl NamedGovernance {
    /// The underlying Governance.
    pub fn inner(&self) -> &Governance {
        &self.gov
    }

    /// The shared Arc to the Governance. Use for `govern_shared()`.
    pub fn arc(&self) -> &std::sync::Arc<Governance> {
        &self.gov
    }

    /// Construct an Mv by construction name.
    pub fn construct(&self, name: &str, params: &[Scalar]) -> Result<Mv, crate::error::Error> {
        let idx = self.construction_index(name)?;
        Ok(self.gov.construct(idx, params)?)
    }

    /// Construct an Mv by index.
    pub fn construct_by_index(
        &self,
        idx: usize,
        params: &[Scalar],
    ) -> Result<Mv, ConstructionError> {
        self.gov.construct(idx, params)
    }

    /// Govern an Mv against a named class.
    /// Uses `Arc` sharing — multiple Geoits share one Governance allocation.
    pub fn govern(&self, mv: &Mv, class_name: &str) -> Result<Geoit, crate::error::Error> {
        let idx = self.class_index(class_name)?;
        Ok(governance::govern_shared(
            mv,
            std::sync::Arc::clone(&self.gov),
            idx,
        )?)
    }

    /// Govern an Mv against a class by index.
    /// Uses `Arc` sharing — multiple Geoits share one Governance allocation.
    pub fn govern_by_index(&self, mv: &Mv, class_index: usize) -> Result<Geoit, GovernanceError> {
        governance::govern_shared(mv, std::sync::Arc::clone(&self.gov), class_index)
    }

    /// Check if an Mv is valid for a named class.
    pub fn is_valid(&self, mv: &Mv, class_name: &str) -> Result<bool, crate::error::NotFoundError> {
        let idx = self.class_index(class_name)?;
        Ok(self.gov.is_valid(mv, idx))
    }

    /// Look up class index by name.
    pub fn class_index(&self, name: &str) -> Result<usize, crate::error::NotFoundError> {
        self.class_names
            .iter()
            .position(|n| n == name)
            .ok_or_else(|| crate::error::NotFoundError::Class(name.to_string()))
    }

    /// Look up construction index by name.
    pub fn construction_index(&self, name: &str) -> Result<usize, crate::error::NotFoundError> {
        self.construction_names
            .iter()
            .position(|n| n == name)
            .ok_or_else(|| crate::error::NotFoundError::Construction(name.to_string()))
    }

    /// List class names.
    pub fn class_names(&self) -> &[String] {
        &self.class_names
    }

    /// List construction names.
    pub fn construction_names(&self) -> &[String] {
        &self.construction_names
    }

    /// List rule names.
    pub fn rule_names(&self) -> &[String] {
        &self.rule_names
    }

    /// Look up rule index by name.
    pub fn rule_index(&self, name: &str) -> Result<usize, crate::error::NotFoundError> {
        self.rule_names
            .iter()
            .position(|n| n == name)
            .ok_or_else(|| crate::error::NotFoundError::Construction(name.to_string()))
    }

    /// Apply a named transformation rule to input Geoits.
    pub fn transform(
        &self,
        rule_name: &str,
        inputs: &[&Geoit],
    ) -> Result<Geoit, crate::error::Error> {
        let idx = self.rule_index(rule_name)?;
        let rule = &self.gov.transform_rules[idx];
        Ok(apply_transform(
            rule,
            inputs,
            std::sync::Arc::clone(&self.gov),
        )?)
    }

    /// The signature.
    pub fn sig(&self) -> &Signature {
        &self.gov.sig
    }
}

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

    fn vga3_governance() -> NamedGovernance {
        let alg = Algebra::new(Signature::new(0, 0, 3).unwrap());
        let class = GeomClassBuilder::new(&alg).grades(&[1]).build();
        let body = Expr::Add(
            Expr::add(
                Expr::mul(Expr::param(0), Expr::gen(0)),
                Expr::mul(Expr::param(1), Expr::gen(1)),
            ),
            Expr::mul(Expr::param(2), Expr::gen(2)),
        );
        GovernanceBuilder::new(alg)
            .class("Vector", class)
            .construction("Vector", "Vector", 3, body)
            .build()
    }

    #[test]
    fn builder_construct_by_name() {
        let gov = vga3_governance();
        let mv = gov
            .construct(
                "Vector",
                &[Scalar::from(3), Scalar::from(4), Scalar::from(5)],
            )
            .unwrap();
        assert_eq!(mv.coefficient(0b001), Scalar::from(3));
        assert_eq!(mv.coefficient(0b010), Scalar::from(4));
        assert_eq!(mv.coefficient(0b100), Scalar::from(5));
    }

    #[test]
    fn builder_govern_by_name() {
        let gov = vga3_governance();
        let params = vec![Scalar::from(3), Scalar::from(4), Scalar::from(5)];
        let mv = gov.construct("Vector", &params).unwrap();
        let geoit = gov.govern(&mv, "Vector").unwrap();
        assert!(geoit.is_satisfied());
        let extracted = geoit.read_all().unwrap();
        assert_eq!(extracted, params);
    }

    #[test]
    fn builder_is_valid() {
        let gov = vga3_governance();
        let mv = gov
            .construct(
                "Vector",
                &[Scalar::from(1), Scalar::from(0), Scalar::from(0)],
            )
            .unwrap();
        assert!(gov.is_valid(&mv, "Vector").unwrap());
    }

    #[test]
    fn builder_cga2_with_constraints() {
        let mut alg = Algebra::new(Signature::new(1, 0, 3).unwrap());
        let eo = Mv::from_rat_terms(&[(0b0001, Rat::new(1, 2)), (0b0010, Rat::new(1, 2))]);
        let einf = Mv::from_rat_terms(&[(0b0001, Rat::from(-1)), (0b0010, Rat::from(1))]);
        alg.add_derived("eo", eo);
        alg.add_derived("einf", einf.clone());

        let point_class = GeomClassBuilder::new(&alg)
            .grades(&[1])
            .null_constraint()
            .normalization(&einf, 1)
            .build();

        // Construction: x*e1 + y*e2 + (-1/2)(x²+y²)*einf + eo
        let eucl = Expr::Add(
            Expr::mul(Expr::param(0), Expr::gen(2)),
            Expr::mul(Expr::param(1), Expr::gen(3)),
        );
        let r_sq = Expr::Add(
            Expr::mul(Expr::param(0), Expr::param(0)),
            Expr::mul(Expr::param(1), Expr::param(1)),
        );
        let neg_half_r2 = Expr::mul(
            Box::new(Expr::Literal(Scalar::Rat(Rat::new(-1, 2)))),
            Box::new(r_sq),
        );
        let conformal = Expr::Mul(neg_half_r2, Expr::dgen(1));
        let body = Expr::Add(
            Box::new(Expr::Add(Box::new(eucl), Box::new(conformal))),
            Expr::dgen(0),
        );

        let gov = GovernanceBuilder::new(alg)
            .class("Point", point_class)
            .construction("Point", "Point", 2, body)
            .build();

        let params = vec![Scalar::from(3), Scalar::from(4)];
        let mv = gov.construct("Point", &params).unwrap();
        let geoit = gov.govern(&mv, "Point").unwrap();
        assert!(geoit.is_satisfied());
        let extracted = geoit.read_all().unwrap();
        assert_eq!(extracted, params);
    }

    #[test]
    fn builder_missing_class() {
        let gov = vga3_governance();
        assert!(gov.class_index("Nonexistent").is_err());
    }

    #[test]
    fn builder_missing_construction() {
        let gov = vga3_governance();
        assert!(gov.construction_index("Nonexistent").is_err());
    }

    #[test]
    fn builder_rule_roundtrip() {
        let alg = Algebra::new(Signature::new(0, 0, 3).unwrap());
        let class = GeomClassBuilder::new(&alg).grades(&[1]).build();
        let body = Expr::Add(
            Expr::add(
                Expr::mul(Expr::param(0), Expr::gen(0)),
                Expr::mul(Expr::param(1), Expr::gen(1)),
            ),
            Expr::mul(Expr::param(2), Expr::gen(2)),
        );
        let gov = GovernanceBuilder::new(alg)
            .class("Vector", class)
            .construction("Vector", "Vector", 3, body)
            .rule("Reverse", &["Vector"], "Vector", TransformOp::Reverse)
            .build();

        // The rule should be registered
        assert_eq!(gov.rule_names(), &["Reverse"]);
        assert!(gov.rule_index("Reverse").is_ok());
        assert!(gov.rule_index("Missing").is_err());

        // Apply the rule: reverse of a grade-1 vector is unchanged
        let params = vec![Scalar::from(3), Scalar::from(4), Scalar::from(5)];
        let mv = gov.construct("Vector", &params).unwrap();
        let geoit = gov.govern(&mv, "Vector").unwrap();
        let reversed = gov.transform("Reverse", &[&geoit]).unwrap();
        assert!(reversed.is_satisfied());
        // Grade 1: reverse sign is +1, so reversed == original
        assert_eq!(reversed.mv(), geoit.mv());
    }
}