Skip to content

feat(deep_causality_multivector): Added new normalize_l2#409

Merged
marvin-hansen merged 6 commits intodeepcausality-rs:mainfrom
marvin-hansen:main
Dec 4, 2025
Merged

feat(deep_causality_multivector): Added new normalize_l2#409
marvin-hansen merged 6 commits intodeepcausality-rs:mainfrom
marvin-hansen:main

Conversation

@marvin-hansen
Copy link
Copy Markdown
Member

@marvin-hansen marvin-hansen commented Dec 4, 2025

User description

Describe your changes

deep_causality_multivector:

  • Added normalize_l2
  • Added norm_l2
  • Added modulus_squared
  • Added scale_by_real

Issue ticket number and link

Code checklist before requesting a review

  • I have signed the DCO?
  • All tests are passing when running make test?
  • No errors or security vulnerabilities are reported by make check?

For details on make, please see BUILD.md

Note: The CI runs all of the above and fixing things before they hit CI speeds
up the review and merge process. Thank you.


PR Type

Enhancement, Documentation


Description

  • Added L2 norm operations (norm_l2, normalize_l2) and scalar evaluation traits (modulus_squared, scale_by_real) to support vector space normalization independent of geometric metric

  • Implemented comprehensive example demonstrating adaptive gravity observer using Causal Monad for tilt estimation and gimbal lock elimination in robotics

  • Enhanced all example files with detailed engineering value documentation explaining real-world applications in physics, robotics, and quantum computing

  • Reorganized module structure for better code organization and added comprehensive README documenting all examples with use cases


Diagram Walkthrough

flowchart LR
  A["New Traits:<br/>MultiVectorL2Norm<br/>ScalarEval"] --> B["CausalMultiVector<br/>Implementations"]
  B --> C["norm_l2<br/>normalize_l2"]
  D["Geometric Tilt<br/>Estimator Example"] --> E["Adaptive Gravity<br/>Observer"]
  E --> F["Causal Monad<br/>Integration"]
  G["Enhanced Examples<br/>Documentation"] --> H["Engineering Value<br/>Explanations"]
  H --> I["Physics & Robotics<br/>Applications"]
Loading

File Walkthrough

Relevant files
Enhancement
8 files
l2_norm.rs
New L2 norm trait for multivectors                                             
+29/-0   
scalar_eval.rs
New scalar evaluation trait for norm calculations               
+21/-0   
multivector_l2_norm.rs
L2 norm implementation for CausalMultiVector                         
+49/-0   
scalar_eval.rs
ScalarEval trait implementations for f32, f64, Complex     
+54/-0   
lib.rs
Export new traits and reorganize module visibility             
+16/-5   
geometric_tilt_estimator.rs
New adaptive gravity observer example with Causal Monad   
+455/-0 
mod.rs
Reorganized API module structure for clarity                         
+3/-97   
mod.rs
Reorganized test module structure                                               
+4/-8     
Documentation
10 files
basic_multivector.rs
Added engineering value documentation and GA concepts       
+14/-0   
clifford_mhd_mulitvector.rs
Added metric agnosticism engineering value explanation     
+12/-0   
dixon_multivector.rs
Added particle physics engineering value documentation     
+12/-0   
grmhd_integration.rs
Added multi-physics coupling engineering value explanation
+15/-0   
hilbert_multivector.rs
Added quantum computing engineering value documentation   
+12/-0   
hkt_multivector.rs
Added higher-kinded types engineering value explanation   
+15/-0   
hopf_fibration_multivector.rs
Added topological data analysis engineering value documentation
+14/-0   
maxwell_multivector.rs
Refactored documentation for electromagnetic field unification
+14/-15 
pga3d_multivector.rs
Added projective geometry engineering value documentation
+15/-1   
README.md
New comprehensive examples guide with use cases                   
+19/-0   
Tests
2 files
ops_norm_impl_tests.rs
Comprehensive tests for L2 norm operations                             
+102/-0 
causal_multivector_tests.rs
Added data and metric getter tests                                             
+19/-2   
Dependencies
1 files
Cargo.toml
Added deep_causality_core dependency and reorganized         
+6/-6     
Additional files
15 files
mod.rs +2/-0     
multi_vector.rs +1/-0     
multivector.rs +100/-0 
mod.rs +1/-0     
ops_norm_impl.rs +4/-0     
causal_multivector_error_tests.rs +1/-2     
metric_tests.rs +1/-1     
algebra_tests.rs [link]   
mod.rs +6/-0     
arithmetic_tests.rs [link]   
mod.rs +6/-0     
getters_tests.rs +0/-24   
mod.rs +11/-0   
ops_misc_impl_tests.rs [link]   
ops_product_impl_tests.rs [link]   

…on of the Gravity Vector

Signed-off-by: Marvin Hansen <marvin.hansen@gmail.com>
Signed-off-by: Marvin Hansen <marvin.hansen@gmail.com>
…as well as modulus_squared and scale_by_real methods to CausalMultiVector.

Signed-off-by: Marvin Hansen <marvin.hansen@gmail.com>
@marvin-hansen marvin-hansen self-assigned this Dec 4, 2025
@qodo-code-review qodo-code-review Bot changed the title feat(deep_causality_multivector): Added new normalize_l2 feat(deep_causality_multivector): Added new normalize_l2 Dec 4, 2025
@qodo-code-review
Copy link
Copy Markdown
Contributor

qodo-code-review Bot commented Dec 4, 2025

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Missing Auditing: New example performs state updates and adaptive filtering without any audit logging of
critical actions or outcomes, but as an example binary this may be acceptable.

Referred Code
fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("--- Geometric Tilt Estimator & Adaptive Gravity Observer ---");

    // 1. Setup Metric (Euclidean 3D)
    let metric = Metric::Euclidean(3);

    // 2. Initialize State
    // Initial Orientation: Identity (Scalar 1.0)
    let mut init_orientation_data = vec![0.0; 8];
    init_orientation_data[0] = 1.0;
    let init_orientation = CausalMultiVector::new(init_orientation_data, metric)?;

    // Initial Gravity Estimate (Body Frame): Assuming starting flat, gravity is down (-Z or +Z depending on frame).
    // Let's assume NED (North-East-Down), so Gravity is +g in Z axis (down).
    // But accelerometer measures reaction force (up), so reading is -g in Z.
    // Let's stick to: Gravity vector g = [0, 0, 9.81].
    let init_gravity = create_vector(&[0.0, 0.0, 9.81], &metric)?;

    // Initial Covariance P = 100 * I
    let init_covariance = CausalTensor::new(
        vec![100.0, 0.0, 0.0, 0.0, 100.0, 0.0, 0.0, 0.0, 100.0],


 ... (clipped 272 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Error Handling: Example code uses many unwrap/expect calls and minimal error propagation in adaptive
filter steps, which could cause panics rather than graceful handling, though examples may
prioritize brevity.

Referred Code
// Approx: R_new = R_old * (1 - 0.5 * Omega * dt)
let metric = Metric::Euclidean(3);
let omega = create_bivector_from_gyro(&current_sensor_data.gyro, &metric).unwrap();
let half_omega_dt = omega.clone() * (-0.5 * dt);
// exp(B) approx 1 + B (first order)
// We need to add scalar 1.0 to Bivector.
let mut one_data = vec![0.0; 8];
one_data[0] = 1.0;
let one = CausalMultiVector::new(one_data, metric).unwrap();

let rotor_update = one + half_omega_dt;
let current_orientation = prev_state.orientation.clone().unwrap();
let predicted_orientation = (current_orientation * rotor_update).normalize_l2();

// --- Step B: Adaptive Gravity Observer (RLS / Kalman Filter) ---
//
// -------------------------------------------------------------------------------------
// WHY THIS MATTERS (For Robotics):
//
// 1. THE PROBLEM: "Down" is hard to find.
//    Accelerometers measure *Proper Acceleration* (Gravity + Motion), not just Gravity.


 ... (clipped 9 lines)

Learn more about managing compliance generic rules or creating your own custom rules

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link
Copy Markdown
Contributor

qodo-code-review Bot commented Dec 4, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Re-evaluate the complex tilt-estimator example

The geometric_tilt_estimator.rs example is overly complex, implementing a full
Kalman filter. It should be simplified to focus on demonstrating the new
normalize_l2 feature, or moved to a separate, higher-level crate.

Examples:

deep_causality_multivector/examples/geometric_tilt_estimator.rs [70-362]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("--- Geometric Tilt Estimator & Adaptive Gravity Observer ---");

    // 1. Setup Metric (Euclidean 3D)
    let metric = Metric::Euclidean(3);

    // 2. Initialize State
    // Initial Orientation: Identity (Scalar 1.0)
    let mut init_orientation_data = vec![0.0; 8];
    init_orientation_data[0] = 1.0;

 ... (clipped 283 lines)

Solution Walkthrough:

Before:

// file: geometric_tilt_estimator.rs
fn main() {
    // ... setup ...
    let process = CausalMonad::pure(...);

    let final_process = sensor_stream.fold(process, |current_process, input| {
        CausalMonad::bind(current_process, |...| {
            // --- Step A: Prediction (Kinematics) ---
            let predicted_orientation = (...).normalize_l2();

            // --- Step B: Adaptive Gravity Observer (Kalman Filter) ---
            // ... ~100 lines of Kalman filter implementation ...
            // using CausalTensor for matrix math (inverse, mat_mul)
            let (x_new, p_new) = if motion_detected { ... } else {
                let s_inv = s.inverse()...;
                let k = CausalTensor::ein_sum(&EinSumOp::mat_mul(p_old, s_inv))...;
                // ... more steps ...
            };

            // --- Tilt Correction ---
            // ... ~40 lines of rotor blending and correction ...
            CausalMonad::pure((current_sensor_data, next_state))
        })
    });
}

After:

// A simplified example focusing only on the new normalization features.
fn main() {
    // 1. Create a non-unit multivector (e.g., a rotor from a non-unit-speed rotation)
    let metric = Metric::Euclidean(3);
    let omega = create_bivector_from_gyro(&[1.2, 0.5, -0.3], &metric).unwrap();
    let dt = 0.1;
    let non_unit_rotor = CausalMultiVector::scalar(1.0, metric) + omega * (-0.5 * dt);

    // 2. Show its L2 norm is not 1.0
    println!("Norm before normalization: {}", non_unit_rotor.norm_l2());

    // 3. Use normalize_l2 to make it a valid rotor for rotations
    let normalized_rotor = non_unit_rotor.normalize_l2();

    // 4. Verify the new norm is 1.0
    println!("Norm after normalization: {}", normalized_rotor.norm_l2());
    println!("Normalized rotor: {:?}", normalized_rotor.data());

    // 5. (Optional) Show it correctly rotates a vector while preserving its norm
    let v = create_vector(&[1.0, 0.0, 0.0], &metric).unwrap();
    let v_rotated = normalized_rotor.geometric_product(&v).geometric_product(&normalized_rotor.reversion());
    println!("Original vector norm: {}", v.norm_l2());
    println!("Rotated vector norm: {}", v_rotated.norm_l2());
}
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that the geometric_tilt_estimator.rs example is overly complex, which obscures the demonstration of the newly added normalize_l2 feature. This is a valid high-level concern about the example's scope and effectiveness, impacting the library's usability.

Medium
  • Update

@codecov
Copy link
Copy Markdown

codecov Bot commented Dec 4, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.74%. Comparing base (60b6d17) to head (e623b74).
⚠️ Report is 8 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #409   +/-   ##
=======================================
  Coverage   94.73%   94.74%           
=======================================
  Files         675      677    +2     
  Lines       25020    25062   +42     
=======================================
+ Hits        23703    23745   +42     
  Misses       1317     1317           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Signed-off-by: Marvin Hansen <marvin.hansen@gmail.com>
Signed-off-by: Marvin Hansen <marvin.hansen@gmail.com>
Signed-off-by: Marvin Hansen <marvin.hansen@gmail.com>
@marvin-hansen marvin-hansen merged commit 4b0e871 into deepcausality-rs:main Dec 4, 2025
12 of 15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant