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
//! Governance system: constrain geometric algebras with equations.
//!
//! A [`Governance`] binds a [`Signature`](crate::Signature) to geometric classes
//! ([`GeomClass`]) defined by grade constraints and polynomial equations, plus
//! construction formulas ([`Construction`]) that build multivectors from parameters.
//!
//! The central operation is [`govern`]: verify an [`Mv`] against a class,
//! producing a [`Geoit`] — a certified multivector with phase, proof, and extraction rules.

pub mod category;
pub mod compile;
pub mod composition;
pub mod construction;
pub mod expr;
pub mod family;
pub mod field;
pub mod geoit;
pub mod geom_class;
#[allow(clippy::module_inception)]
pub mod governance;
pub mod groebner;
pub mod morphism;
pub mod pencil;
pub mod phase;
pub mod poly;
pub mod predicate;
pub mod profile;
pub mod reading;
pub mod rotor;
pub mod rule;
pub mod triangular;
pub mod validation;

pub use self::category::GovernanceCategory;
pub use self::composition::{compose, Embedding, EmbeddingError};
pub use self::construction::Construction;
pub use self::expr::Expr;
pub use self::expr::{ContextShape, EvalError};
pub use self::family::{GovernanceFamily, GovernanceRegistry};
pub use self::field::{FieldOp, ProbeSpec};
pub use self::geoit::Geoit;
pub use self::geom_class::GeomClass;
pub use self::governance::Governance;
pub use self::groebner::GroebnerError;
pub use self::phase::Phase;
pub use self::predicate::Predicate;
pub use self::profile::GeneratorProfile;
pub use self::reading::{ExtractionError, ExtractionMap, ReadingRules, VariableMap};
pub use self::rule::{apply_transform, ProofTerm, TransformOp, TransformRule};

use crate::algebra::blade_new::grade;
use crate::algebra::mv::Mv;
use crate::scalar::{Rat, Scalar};

/// Error from the govern() function.
#[derive(Clone, Debug)]
pub enum GovernanceError {
    ClassOutOfRange {
        index: usize,
        len: usize,
    },
    BladeMaskOutOfRange {
        mask: u64,
        max_generators: u8,
    },
    GradeViolation {
        mask: u64,
        grade: u8,
    },
    EquationsFailed {
        class_index: usize,
        failures: Vec<(usize, Scalar)>,
    },
    InequalitiesFailed {
        class_index: usize,
        failures: Vec<(usize, Scalar)>,
    },
    ReadingDerivation(reading::ExtractionError),
    /// v0.0.3: Mv's generator profile has generators outside the class's expected profile.
    ProfileMismatch {
        class_index: usize,
        expected: profile::GeneratorProfile,
        actual: profile::GeneratorProfile,
    },
}

/// The meeting point: Governance + Mv → Geoit.
///
/// Wraps the Governance in a fresh `Arc`. For the hot path where multiple
/// Geoits share one Governance, use `govern_shared()` instead.
pub fn govern(mv: &Mv, gov: &Governance, class_index: usize) -> Result<Geoit, GovernanceError> {
    govern_shared(mv, std::sync::Arc::new(gov.clone()), class_index)
}

/// Like `govern()`, but takes a shared `Arc<Governance>` to avoid cloning.
///
/// Multiple Geoits produced from the same Arc share one Governance allocation.
/// This is the hot path for `NamedGovernance::govern()`.
pub fn govern_shared(
    mv: &Mv,
    gov: std::sync::Arc<Governance>,
    class_index: usize,
) -> Result<Geoit, GovernanceError> {
    // 1. Validate class_index
    if class_index >= gov.geom_classes.len() {
        return Err(GovernanceError::ClassOutOfRange {
            index: class_index,
            len: gov.geom_classes.len(),
        });
    }

    // 2. Validate blade masks within algebra
    let n = gov.sig.n();
    let max_mask = if n >= 64 { u64::MAX } else { (1u64 << n) - 1 };
    for (mask, _) in mv.blades() {
        if mask > max_mask {
            return Err(GovernanceError::BladeMaskOutOfRange {
                mask,
                max_generators: n,
            });
        }
    }

    // 3. Check grade constraint
    let class = &gov.geom_classes[class_index];
    for (mask, coeff) in mv.blades() {
        if !coeff.is_zero() {
            let g = grade(mask);
            if !class.grade_permitted(g) {
                return Err(GovernanceError::GradeViolation { mask, grade: g });
            }
        }
    }

    // 4. Build variable map and evaluate polynomials
    let var_map = VariableMap::for_grade_mask(&gov.sig, class.grade_mask);
    let values: Vec<Rat> = var_map
        .var_to_mask
        .iter()
        .map(|&mask| mv.coefficient(mask).try_as_rat().unwrap_or(Rat::ZERO))
        .collect();

    let eq_residuals: Vec<Scalar> = class
        .equations
        .iter()
        .map(|poly| Scalar::Rat(poly.eval(&values)))
        .collect();
    let ineq_values: Vec<Scalar> = class
        .inequalities
        .iter()
        .map(|poly| Scalar::Rat(poly.eval(&values)))
        .collect();

    let equations_satisfied: Vec<bool> = eq_residuals.iter().map(|r| r.is_zero()).collect();
    let inequalities_satisfied: Vec<bool> = ineq_values.iter().map(|v| !v.is_zero()).collect();

    let pred = Predicate::new(
        class_index,
        &eq_residuals,
        &ineq_values,
        equations_satisfied.clone(),
        inequalities_satisfied.clone(),
        eq_residuals.iter().any(|r| r.is_big())
            || ineq_values.iter().any(|v| v.is_big())
            || mv.blades().any(|(_, c)| c.is_big()),
    );

    // 5. Check satisfaction
    let eq_failures: Vec<(usize, Scalar)> = equations_satisfied
        .iter()
        .enumerate()
        .filter(|(_, &s)| !s)
        .map(|(i, _)| (i, eq_residuals[i].clone()))
        .collect();
    let ineq_failures: Vec<(usize, Scalar)> = inequalities_satisfied
        .iter()
        .enumerate()
        .filter(|(_, &s)| !s)
        .map(|(i, _)| (i, ineq_values[i].clone()))
        .collect();

    if !eq_failures.is_empty() {
        return Err(GovernanceError::EquationsFailed {
            class_index,
            failures: eq_failures,
        });
    }
    if !ineq_failures.is_empty() {
        return Err(GovernanceError::InequalitiesFailed {
            class_index,
            failures: ineq_failures,
        });
    }

    // 6. Compute Phase
    let ph = phase::compute_phase(mv, &gov.sig);

    // 6b. Compute Profile (v0.0.2)
    let prof = profile::GeneratorProfile::compute(mv, &gov.sig);

    // 6c. Check profile constraint (v0.0.3)
    if let Some(ref expected) = class.expected_profile {
        let unexpected = prof.all_participation() & !expected.all_participation();
        if unexpected != 0 {
            return Err(GovernanceError::ProfileMismatch {
                class_index,
                expected: *expected,
                actual: prof,
            });
        }
    }

    // 7. Derive ReadingRules
    let construction = gov
        .constructions
        .iter()
        .find(|c| c.class_index == class_index);
    let rules = if let Some(constr) = construction {
        if gov.sig.dimension() <= 32 {
            ReadingRules::derive_from_groebner(class, constr, &gov.sig, &gov.derived_gens)
                .map_err(GovernanceError::ReadingDerivation)?
        } else {
            ReadingRules::derive_from_probing(constr, &gov.sig, &gov.derived_gens)
                .map_err(GovernanceError::ReadingDerivation)?
        }
    } else {
        ReadingRules::derive_from_grade_mask(class, 0, &gov.sig)
    };

    // 8. Assemble Geoit
    Ok(Geoit {
        mv: mv.clone(),
        governance: gov,
        predicate: pred,
        phase: ph,
        readings: rules,
        profile: prof,
        proof: rule::ProofTerm::Checked { class_index },
    })
}

impl std::fmt::Display for GovernanceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GovernanceError::ClassOutOfRange { index, len } => {
                write!(f, "class_index {} out of range (have {})", index, len)
            }
            GovernanceError::BladeMaskOutOfRange {
                mask,
                max_generators,
            } => write!(
                f,
                "blade mask {:#b} exceeds {} generators",
                mask, max_generators
            ),
            GovernanceError::GradeViolation { mask, grade } => {
                write!(f, "blade {:#b} (grade {}) not permitted", mask, grade)
            }
            GovernanceError::EquationsFailed {
                class_index,
                failures,
            } => {
                write!(f, "class {} equations failed: ", class_index)?;
                for (i, (idx, residual)) in failures.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "eq[{}] residual={}", idx, residual)?;
                }
                Ok(())
            }
            GovernanceError::InequalitiesFailed {
                class_index,
                failures,
            } => {
                write!(f, "class {} inequalities failed: ", class_index)?;
                for (i, (idx, value)) in failures.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "ineq[{}] value={}", idx, value)?;
                }
                Ok(())
            }
            GovernanceError::ReadingDerivation(e) => write!(f, "reading derivation: {}", e),
            GovernanceError::ProfileMismatch {
                class_index,
                expected,
                actual,
            } => write!(
                f,
                "class {} profile mismatch: expected {}, got {}",
                class_index, expected, actual
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::algebra::signature::Signature;
    use crate::scalar::Rat;

    fn vga3_gov() -> Governance {
        Governance {
            sig: Signature::new(0, 0, 3).unwrap(),
            derived_gens: vec![],
            geom_classes: vec![GeomClass::grades_only(&[1])],
            constructions: vec![Construction {
                class_index: 0,
                arity: 3,
                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)),
                ),
            }],
            probe: None,
            transform_rules: vec![],
        }
    }

    #[test]
    fn govern_valid() {
        let gov = vga3_gov();
        let mv = gov
            .construct(
                0,
                &[Scalar::from(3i64), Scalar::from(4i64), Scalar::from(5i64)],
            )
            .unwrap();
        let geoit = govern(&mv, &gov, 0).unwrap();
        assert_eq!(geoit.phase(), Phase::Commitment);
        assert!(geoit.is_satisfied());
    }

    #[test]
    fn govern_invalid_mv() {
        let gov = vga3_gov();
        let bv = Mv::from_rat_terms(&[(0b011, Rat::from(1))]);
        let result = govern(&bv, &gov, 0);
        assert!(result.is_err());
    }

    #[test]
    fn govern_class_out_of_range() {
        let gov = vga3_gov();
        let mv = Mv::new();
        assert!(matches!(
            govern(&mv, &gov, 99),
            Err(GovernanceError::ClassOutOfRange { .. })
        ));
    }

    #[test]
    fn govern_blade_out_of_range() {
        let gov = vga3_gov();
        let mv = Mv::from_rat_terms(&[(0b1000, Rat::from(1))]);
        assert!(matches!(
            govern(&mv, &gov, 0),
            Err(GovernanceError::BladeMaskOutOfRange { .. })
        ));
    }

    #[test]
    fn govern_profile_match_passes() {
        // VGA(3) vector with expected profile: h-type only
        let sig = Signature::new(0, 0, 3).unwrap();
        let expected = profile::GeneratorProfile {
            i_participation: 0,
            d_participation: 0,
            h_participation: 0b111,
        };
        let gov = Governance {
            sig,
            derived_gens: vec![],
            geom_classes: vec![GeomClass {
                grade_mask: 0b10,
                equations: vec![],
                inequalities: vec![],
                field_op: FieldOp::default(),
                expected_profile: Some(expected),
            }],
            constructions: vec![Construction {
                class_index: 0,
                arity: 3,
                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)),
                ),
            }],
            probe: None,
            transform_rules: vec![],
        };
        let mv = gov
            .construct(
                0,
                &[Scalar::from(1i64), Scalar::from(2i64), Scalar::from(3i64)],
            )
            .unwrap();
        let geoit = govern(&mv, &gov, 0).unwrap();
        assert!(geoit.is_satisfied());
    }

    #[test]
    fn govern_profile_mismatch_rejected() {
        // CGA(2) algebra but class expects h-type only — a vector with i-type participation should fail
        let sig = Signature::new(1, 0, 3).unwrap(); // Cl(1,0,3): gen0 is i-type
        let h_only = profile::GeneratorProfile {
            i_participation: 0,
            d_participation: 0,
            h_participation: 0b1110, // gens 1,2,3 only
        };
        let gov = Governance {
            sig,
            derived_gens: vec![],
            geom_classes: vec![GeomClass {
                grade_mask: 0b10,
                equations: vec![],
                inequalities: vec![],
                field_op: FieldOp::default(),
                expected_profile: Some(h_only),
            }],
            constructions: vec![],
            probe: None,
            transform_rules: vec![],
        };
        // Mv with gen0 (i-type) participation — should be rejected
        let mv = Mv::from_rat_terms(&[(0b0001, Rat::from(1)), (0b0010, Rat::from(2))]);
        assert!(matches!(
            govern(&mv, &gov, 0),
            Err(GovernanceError::ProfileMismatch { .. })
        ));
    }

    #[test]
    fn govern_no_expected_profile_backward_compatible() {
        // Without expected_profile, any profile is accepted (v0.0.1 behavior)
        let gov = vga3_gov();
        assert!(gov.geom_classes[0].expected_profile.is_none());
        let mv = gov
            .construct(
                0,
                &[Scalar::from(1i64), Scalar::from(0i64), Scalar::from(0i64)],
            )
            .unwrap();
        assert!(govern(&mv, &gov, 0).is_ok());
    }
}