Skip to content

feat(deep_causality_topology): certified Lattice Gauge Field #450

Merged
marvin-hansen merged 7 commits intodeepcausality-rs:mainfrom
marvin-hansen:main
Jan 12, 2026
Merged

feat(deep_causality_topology): certified Lattice Gauge Field #450
marvin-hansen merged 7 commits intodeepcausality-rs:mainfrom
marvin-hansen:main

Conversation

@marvin-hansen
Copy link
Copy Markdown
Member

@marvin-hansen marvin-hansen commented Jan 12, 2026

User description

Describe your changes

  • added example for Lattice Gauge Field
  • certified Lattice Gauge Field for physics correctness
  • refactored traits in Gauge Field and Lattice Gauge Field

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, Tests, Documentation


Description

  • Refactored gauge field type system from single generic parameter T to dual parameters M (matrix elements) and R (real scalars) to properly support complex matrices in U(1) and other gauge theories
  • Added comprehensive physics verification for 2D U(1) lattice gauge theory with 24 validation tests against exact analytical solutions using Bessel functions
  • Updated LinkVariable and LatticeGaugeField to use ComplexField<R> and DivisionAlgebra<R> trait bounds for proper complex matrix arithmetic
  • Refactored all gauge operations (Metropolis, Wilson loops, plaquettes, gradient flow, smearing, gauge transforms) to handle complex field elements with error handling
  • Simplified GaugeField from four type parameters to two (<G, M, R>) while maintaining full algebraic expressiveness
  • Added RandomField trait for generic random element generation supporting both real and complex types
  • Created 2D U(1) gauge theory example demonstrating high-precision verification with configurable float types (f32, f64, DoubleFloat)
  • Updated all test suites to use new type signatures with complex matrix support and proper complex number comparisons
  • Enhanced documentation with DoubleFloat vs f128 comparison and comprehensive physics validation status

Diagram Walkthrough

flowchart LR
  A["Single Type Parameter<br/>T: Field"] -->|"Refactor"| B["Dual Type Parameters<br/>M: ComplexField&lt;R&gt;<br/>R: RealField"]
  B -->|"Enable"| C["Complex Matrices<br/>U(1) Gauge Theory"]
  C -->|"Verify"| D["Physics Tests<br/>24 Validations<br/>Bessel Functions"]
  E["LinkVariable<br/>LatticeGaugeField<br/>GaugeField"] -->|"Update Signatures"| B
  F["Metropolis<br/>Wilson Loops<br/>Plaquettes<br/>Gradient Flow"] -->|"Add Error Handling"| B
  D -->|"Demonstrate"| G["2D U1 Example<br/>High Precision"]
Loading

File Walkthrough

Relevant files
Tests
13 files
lattice_gauge_field_tests.rs
Refactor tests to use complex matrix types for U(1) gauge fields

deep_causality_topology/tests/types/gauge/gauge_field_lattice/lattice_gauge_field_tests.rs

  • Updated all LatticeGaugeField type signatures to include Complex as
    matrix type and f64 as scalar type
  • Changed method calls from metropolis_sweep_f64() and
    metropolis_update_f64() to try_metropolis_sweep() and
    try_metropolis_update()
  • Updated plaquette trace comparisons to use Complex::new(1.0, 0.0) and
    .norm() for complex number handling
  • Added import for Complex from deep_causality_num
+108/-64
verification_tests.rs
Add physics verification tests against exact analytical solutions

deep_causality_topology/tests/types/gauge/gauge_field_lattice/verification_tests.rs

  • Added comprehensive physics verification tests for 2D U(1) lattice
    gauge theory
  • Implemented Bessel function computations (bessel_i0, bessel_i1,
    bessel_ratio) for exact analytical solutions
  • Added tests for identity configuration, Wilson/Polyakov loops,
    improved action coefficients, and gauge invariance
  • Included diagnostic tests documenting known limitations in U(1)
    Metropolis algorithm with real matrices
  • Added tests for topological charge, thermalization, and anisotropy
    detection
+894/-0 
mod.rs
Register new verification tests module                                     

deep_causality_topology/tests/types/gauge/gauge_field_lattice/mod.rs

  • Added verification_tests module to test suite
+2/-0     
link_variable_tests.rs
LinkVariable tests refactored for complex matrix support 

deep_causality_topology/tests/types/gauge/link_variable/link_variable_tests.rs

  • Updated LinkVariable type signatures from LinkVariable to
    LinkVariable, f64> to support complex matrix elements
  • Changed assertions from .abs() to .norm() for complex number
    comparisons
  • Updated tensor creation to use Complex::new() for matrix elements
    instead of raw floats
  • Modified scaling operations to use Complex::new() values and
    try_scale() methods
+82/-62 
hkt_lattice_gauge_tests.rs
HKT lattice gauge field tests updated for complex matrices

deep_causality_topology/tests/extensions/hkt_lattice_gauge_tests.rs

  • Updated LatticeGaugeField type signatures to include Complex as matrix
    element type
  • Changed witness type from LatticeGaugeFieldWitness to
    LatticeGaugeFieldWitness
  • Updated assertions to use .norm() for complex number comparisons
  • Modified test expectations for beta values and link element
    comparisons
+31/-26 
gauge_field_tests.rs
Gauge field tests updated for complex matrix support         

deep_causality_topology/tests/types/gauge/gauge_field/gauge_field_tests.rs

  • Updated GaugeField type signatures to use Complex for matrix elements
  • Changed tensor creation to use Complex::new() for connection and field
    strength tensors
  • Updated assertions to compare Complex values directly
  • Modified type signatures from GaugeField to
    GaugeField, f64>
+35/-17 
hkt_gauge_field_tests.rs
Update gauge field test instantiations                                     

deep_causality_topology/tests/extensions/hkt_gauge_field_tests.rs

  • Updated GaugeField instantiations from four type parameters to two
  • Changed from GaugeField to GaugeField
  • Updated GaugeField to GaugeField
+5/-5     
metropolis_tests.rs
Update metropolis tests with complex field elements           

deep_causality_topology/tests/types/gauge/gauge_field_lattice/metropolis_tests.rs

  • Added Complex import from deep_causality_num
  • Updated LatticeGaugeField instantiations to use Complex for matrix
    elements
  • Changed from LatticeGaugeField to LatticeGaugeField
    Complex, f64>
  • Renamed metropolis_sweep_f64 method call to try_metropolis_sweep
+14/-7   
wilson_tests.rs
Update Wilson loop tests with complex field support           

deep_causality_topology/tests/types/gauge/gauge_field_lattice/wilson_tests.rs

  • Added Complex import from deep_causality_num
  • Updated all LatticeGaugeField instantiations to use Complex for matrix
    elements
  • Changed assertions to use .abs() and .norm() methods for complex
    number comparisons
  • Updated floating-point equality checks to use tolerance-based
    comparisons
+8/-7     
continuum_tests.rs
Update continuum tests with complex field elements             

deep_causality_topology/tests/types/gauge/gauge_field_lattice/continuum_tests.rs

  • Added Complex import from deep_causality_num
  • Updated LatticeGaugeField instantiations to use Complex for matrix
    elements
  • Changed field strength assertions to compare Complex values using
    .norm()
  • Updated zero value comparisons to use Complex::new(0.0, 0.0)
+7/-6     
gauge_field_validation_tests.rs
Update gauge field validation tests                                           

deep_causality_topology/tests/types/gauge/gauge_field/gauge_field_validation_tests.rs

  • Updated GaugeField type instantiations from four to two type
    parameters
  • Changed from GaugeField to GaugeField
+3/-3     
gradient_flow_tests.rs
Update gradient flow tests with complex field elements     

deep_causality_topology/tests/types/gauge/gauge_field_lattice/gradient_flow_tests.rs

  • Added Complex import from deep_causality_num
  • Updated LatticeGaugeField instantiations to use Complex for matrix
    elements
  • Changed from LatticeGaugeField to LatticeGaugeField
    Complex, f64>
+5/-4     
display_tests.rs
Clean up display tests and simplify type parameters           

deep_causality_topology/tests/types/gauge/gauge_field/display_tests.rs

  • Removed verbose comments explaining base.len() and num_points
    calculation
  • Updated GaugeField instantiation from four to two type parameters
+1/-15   
Enhancement
34 files
ops.rs
Refactor LinkVariable to support complex matrices with real scalars

deep_causality_topology/src/types/gauge/link_variable/ops.rs

  • Refactored generic type parameters from single T: TensorData to M:
    TensorData (matrix) and R: RealField (scalar)
  • Updated try_dagger() and dagger() to conjugate complex matrix elements
    using ComplexField trait
  • Modified project_sun() to handle complex matrices with polar
    decomposition and determinant-based phase correction for SU(N)
  • Added try_determinant() helper method for 2×2 and 3×3 matrices
  • Updated all matrix operations to properly handle complex field
    arithmetic with real scalar parameters
+218/-55
hkt_lattice_gauge.rs
Update HKT witness for separated matrix and scalar type parameters

deep_causality_topology/src/extensions/hkt_gauge/hkt_lattice_gauge.rs

  • Updated LatticeGaugeFieldWitness to include matrix type parameter M in
    addition to gauge group G and dimension D
  • Refactored HKT trait implementations to use LatticeGaugeField
    R> signature with separate matrix and scalar types
  • Updated map_field(), zip_with(), and scale_field() helper methods to
    work with new type structure
  • Modified helper functions map_link_variable() and zip_link_variables()
    to handle matrix and scalar type separation
  • Added Debug and Clone bounds to TensorData constraints where needed
+87/-67 
ops_gradient_flow.rs
Gradient flow operations refactored for complex field support

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_gradient_flow.rs

  • Refactored FlowParams to FlowParams with RealField bounds for scalar
    parameters
  • Updated LatticeGaugeField impl bounds to use M: ComplexField +
    DivisionAlgebra for matrix elements
  • Changed numeric conversions from T::from() to R::from_f64() and added
    M::from_re_im() for complex scaling
  • Updated try_scale() calls to use try_scale() with error handling
    instead of direct scale()
+86/-52 
ops_wilson.rs
Wilson action and loop observables updated for complex matrices

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_wilson.rs

  • Updated impl bounds to use M: ComplexField + DivisionAlgebra for
    matrix elements
  • Changed return types from T to R for action and observable
    computations
  • Updated numeric conversions to use R::from_f64() instead of T::from()
  • Modified try_mul() calls to include error handling with
    map_err(TopologyError::from)
+47/-29 
ops_metropolis.rs
Metropolis algorithm refactored for complex field support

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_metropolis.rs

  • Renamed generic parameter R to RngType to avoid conflict with scalar
    type R
  • Updated impl bounds to include M: RandomField + ComplexField + Field
  • Changed epsilon parameter type from T to R (RealField)
  • Refactored perturbation generation to use M::generate_uniform() and
    M::from_re_im()
+55/-119
ops_plague.rs
Plaquette and rectangle operations refactored for complex support

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_plague.rs

  • Updated impl bounds to use M: ComplexField + DivisionAlgebra for
    matrix elements
  • Changed mul() calls to try_mul() with error handling throughout
    plaquette and rectangle computations
  • Updated return types from T to R for observable computations
  • Modified numeric conversions to use R::from_f64() instead of T::from()
+50/-24 
mod.rs
Lattice gauge field refactored with complex matrix element support

deep_causality_topology/src/types/gauge/gauge_field_lattice/mod.rs

  • Added comprehensive verification status documentation with 24 physics
    validation tests
  • Updated struct definition to use four type parameters: G, D, M, R
    instead of three
  • Changed links HashMap to store LinkVariable with complex
    matrix support
  • Updated all impl blocks to include M: ComplexField + DivisionAlgebra
    bounds
+57/-27 
mod.rs
LinkVariable refactored with separate matrix and scalar types

deep_causality_topology/src/types/gauge/link_variable/mod.rs

  • Updated struct to use three type parameters: G, M, R instead of two
  • Added _scalar: PhantomData field to track scalar type
  • Updated impl bounds to use M: Field + ComplexField + DivisionAlgebra
  • Refactored try_random() to use M::generate_uniform() for random matrix
    generation
+32/-21 
weak_field_ops_impl.rs
Weak force field operations updated for RealField trait   

deep_causality_physics/src/theories/weak_force/weak_field_ops_impl.rs

  • Changed trait bounds from Field + Float to RealField + ToPrimitive
  • Updated is_finite() checks to use
    .to_f64().unwrap_or(f64::NAN).is_finite()
  • Replaced powi() calls with powf() using S::from() for exponents
  • Updated accumulation operators from = to += for clarity
+23/-13 
ops_continuum.rs
Continuum limit operations refactored for complex field support

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_continuum.rs

  • Updated impl bounds to use M: ComplexField + DivisionAlgebra for
    matrix elements
  • Changed return types from T to R for topological charge computations
  • Refactored scaling operations to use M::from_re_im() and try_scale()
    with error handling
  • Updated numeric conversions to use R::from_f64() instead of T::from()
+54/-29 
ops_actions.rs
Improved gauge actions refactored for real field coefficients

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_actions.rs

  • Updated ActionCoeffs to ActionCoeffs with RealField + FromPrimitive
    bounds
  • Changed impl bounds to use M: ComplexField + DivisionAlgebra for
    matrix elements
  • Updated numeric conversions from T::from() to R::from_f64()
  • Modified accumulation operators from = to += for consistency
+32/-23 
ops_monte_carlo.rs
Monte Carlo operations refactored with error handling for complex
matrices

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_monte_carlo.rs

  • Updated impl bounds to use M: ComplexField + DivisionAlgebra for
    matrix elements
  • Changed mul() calls to try_mul() with error handling for staple and
    action computations
  • Updated add() calls to try_add() with error handling
  • Modified numeric conversions to use R::from_f64() instead of T::from()
+38/-17 
hkt_gauge_witness.rs
HKT gauge witness methods updated for new GaugeField signature

deep_causality_topology/src/extensions/hkt_gauge/hkt_gauge_witness.rs

  • Updated merge_fields() signature to use separate A, B, F2 types and R:
    RealField
  • Updated gauge_transform() signature to use F2: TensorData and R:
    RealField
  • Updated compute_field_strength_abelian() to use GaugeField
    signature
  • Updated compute_field_strength_non_abelian() to use GaugeField
    R> and R: Field
+23/-20 
ops_smearing.rs
Refactor smearing operations with algebraic trait bounds 

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_smearing.rs

  • Refactored type parameters from single T to dual M (matrix elements)
    and R (real scalars) with algebraic trait bounds
  • Updated SmearingParams to use RealField bounds instead of From
  • Modified scaling operations to use try_scale with proper error
    handling for complex field elements
  • Added conversion of scalar weights to matrix type M for correct matrix
    operations
+34/-14 
ops_gauge_transform.rs
Refactor gauge transformations with dual type parameters 

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_gauge_transform.rs

  • Introduced dual type parameters M and R replacing single T parameter
  • Updated gauge transformation function signatures to accept
    LinkVariable
  • Renamed generic type R to RngType in random gauge transform to avoid
    conflict with scalar type R
  • Modified multiplication operations to use try_mul with error handling
+30/-12 
mod.rs
Simplify GaugeField type parameters with algebraic bounds

deep_causality_topology/src/types/gauge/gauge_field/mod.rs

  • Simplified GaugeField from four type parameters to two

  • Updated trait bounds to use Field and RealField from
    deep_causality_num
  • Changed base manifold to use R for both scalar types
  • Updated connection and field_strength tensors to use M for matrix
    elements
+18/-18 
gauge_em_ops_impl.rs
Update electromagnetic operations with RealField bounds   

deep_causality_physics/src/theories/electromagnetism/gauge_em_ops_impl.rs

  • Updated GaugeEmOps implementation to use simplified GaugeField
    S> signature
  • Replaced Float trait bound with RealField for scalar operations
  • Changed method calls from Float::abs() to .abs() method on values
  • Updated helper functions to use RealField instead of Field + Float
    bounds
+11/-12 
getters.rs
Update lattice gauge field getters with new type parameters

deep_causality_topology/src/types/gauge/gauge_field_lattice/getters.rs

  • Updated all getter method signatures to use dual type parameters
    D, M, R>
  • Changed return types from T to R for beta-related getters
  • Updated LinkVariable references to use signature
  • Added #[allow(clippy::type_complexity)] for complex type signatures
+10/-9   
ops_gauge.rs
Refactor gauge operations with algebraic trait bounds       

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_gauge.rs

  • Introduced dual type parameters M and R with algebraic trait bounds
  • Updated gauge transformation function signatures to use
    LinkVariable
  • Modified multiplication operations to use try_mul with error handling
  • Added expect clause for infallible gauge transform operations
+18/-3   
lattice_gauge_simulation.rs
Update lattice gauge simulation example with complex fields

deep_causality_topology/examples/lattice_gauge_simulation.rs

  • Added Complex import from deep_causality_num
  • Updated LatticeGaugeField instantiation to use Complex for matrix
    elements
  • Changed from LatticeGaugeField to LatticeGaugeField
    D, Complex, f64>
  • Renamed metropolis_sweep_f64 method call to try_metropolis_sweep
+7/-2     
mod.rs
Simplify physics field type aliases                                           

deep_causality_physics/src/theories/alias/mod.rs

  • Simplified all physics field type aliases from four to two type
    parameters
  • Updated EM, WeakField, ElectroweakField, QCD, SMField, and GR aliases
  • Changed from GaugeField to
    GaugeField
+6/-6     
lib.rs
Reorganize library exports and add RandomField trait         

deep_causality_topology/src/lib.rs

  • Reordered imports to place trait exports before type exports
  • Added RandomField trait to public exports
  • Reorganized hkt_adjunction_stokes imports for consistency
+4/-3     
getters.rs
Update gauge field getters with new type parameters           

deep_causality_topology/src/types/gauge/gauge_field/getters.rs

  • Updated all getter method signatures to use dual type parameters
    M, R>
  • Changed return types from T to M for connection and field_strength
    getters
  • Updated Manifold reference to use R for scalar type
+4/-4     
getters.rs
Update link variable getters with dual type parameters     

deep_causality_topology/src/types/gauge/link_variable/getters.rs

  • Updated struct bounds to use M: std::fmt::Debug + Clone, R instead of
    T
  • Changed all method signatures to use M for matrix elements
  • Updated return types to reference M instead of T
+4/-4     
random.rs
Add RandomField trait for random element generation           

deep_causality_topology/src/types/gauge/link_variable/random.rs

  • Created new RandomField trait for generating random field elements
    uniformly
  • Implemented RandomField for f64 generating values in range [-0.5, 0.5)
  • Implemented RandomField for Complex with independent real and
    imaginary components
  • Bridges deep_causality_rand and algebraic types for generic random
    generation
+38/-0   
utils.rs
Refactor lattice gauge field utilities with algebraic bounds

deep_causality_topology/src/types/gauge/gauge_field_lattice/utils.rs

  • Updated type parameters from single T to dual M and R
  • Replaced Float trait bound with ComplexField + DivisionAlgebra
  • Updated get_link_or_identity return type to use LinkVariable
  • Added Debug trait bound to M type parameter
+10/-3   
gauge_em_ops.rs
Update electromagnetic operations trait bounds                     

deep_causality_physics/src/theories/electromagnetism/gauge_em_ops.rs

  • Updated trait bounds from Field + Float to RealField
  • Simplified type constraints for electromagnetic operations
+2/-2     
weak_field_ops.rs
Update weak force operations trait bounds                               

deep_causality_physics/src/theories/weak_force/weak_field_ops.rs

  • Updated trait bounds from Field + Float to RealField + ToPrimitive
  • Simplified type constraints for weak force operations
+2/-2     
display.rs
Update lattice gauge field display with new type parameters

deep_causality_topology/src/types/gauge/gauge_field_lattice/display.rs

  • Updated Display implementation to use dual type parameters
    R>
  • Changed type name extraction to use M instead of T
  • Added explicit imports for Debug and Display traits
+3/-5     
electroweak_ops.rs
Update electroweak operations with simplified type parameters

deep_causality_physics/src/theories/electroweak/electroweak_ops.rs

  • Updated extract_z method return type from GaugeField to
    GaugeField
+1/-1     
display.rs
Update gauge field display with new type parameters           

deep_causality_topology/src/types/gauge/gauge_field/display.rs

  • Updated Display implementation to use dual type parameters
  • Added explicit imports for Debug and Display traits
  • Removed blank line at beginning of file
+2/-2     
display.rs
Update link variable display with dual type parameters     

deep_causality_topology/src/types/gauge/link_variable/display.rs

  • Updated Display implementation to use dual type parameters
  • Changed from T: std::fmt::Debug + Clone to M: std::fmt::Debug + Clone,
    R
+1/-1     
electroweak_impl.rs
Update electroweak implementation with simplified type parameters

deep_causality_physics/src/theories/electroweak/electroweak_impl.rs

  • Updated extract_z method return type from GaugeField to
    GaugeField
+1/-1     
part_eq.rs
Update link variable PartialEq with dual type parameters 

deep_causality_topology/src/types/gauge/link_variable/part_eq.rs

  • Updated PartialEq implementation to use dual type parameters
  • Changed bounds from T: Clone + PartialEq to R: PartialEq, T: PartialEq
+1/-1     
Documentation
2 files
main.rs
Add 2D U(1) gauge theory verification example with Bessel functions

examples/physics_examples/gauge_lattice_u1_2d/main.rs

  • Created new example demonstrating 2D U(1) lattice gauge theory
    verification against exact analytical solutions
  • Implemented high-precision Bessel function computations using series
    expansion and Miller's backward recurrence
  • Verified identity configuration produces correct plaquette values and
    compares two independent algorithms
  • Supports configurable float precision via FloatType (f32, f64, or
    DoubleFloat)
  • Includes comprehensive documentation referencing Creutz's textbook on
    lattice gauge theory
+284/-0 
mod.rs
Add DoubleFloat vs f128 comparison documentation                 

deep_causality_num/src/float_double/mod.rs

  • Added comprehensive documentation comparing DoubleFloat with IEEE
    binary128 (f128)
  • Included precision comparison table showing mantissa bits and decimal
    digits
  • Added physical scale context table relating precision to SI prefixes
    and physical phenomena
  • Documented that DoubleFloat provides ~32 digits precision comparable
    to f128 with better performance
+21/-0   
Configuration changes
1 files
test.sh
Simplify test script with unified feature testing               

build/scripts/test.sh

  • Simplified test script to use --all-features flag
  • Removed separate doc test and feature-specific test commands
  • Changed to single-threaded execution for all tests with
    --test-threads=1
  • Added command prefix for cargo invocations
+2/-6     
Additional files
11 files
AGENTS.md +3/-1     
README.md +21/-0   
README.md +24/-0   
BUILD.bazel +2/-0     
Cargo.toml +4/-0     
README.md +73/-0   
topology_algebra_gauge_review.md +102/-0 
topology_verify_lattice_gauge_field.md +265/-0 
physics_gauge_theories.md +0/-607 
topology_gauge_field.md +0/-500 
topology_gauge_field_review.md +0/-228 

…correctness of the Lattice Gaugle Field up to 1e-31(!)

Signed-off-by: Marvin Hansen <marvin.hansen@gmail.com>
…uge Field.

Signed-off-by: Marvin Hansen <marvin.hansen@gmail.com>
…s and ComplexFiels in GaugeField and LatticeGauge Field

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>
Signed-off-by: Marvin Hansen <marvin.hansen@gmail.com>
Signed-off-by: Marvin Hansen <marvin.hansen@gmail.com>
@qodo-code-review
Copy link
Copy Markdown
Contributor

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: Robust Error Handling and Edge Case Management

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

Status:
Misleading error context: Newly added error messages still refer to the old generic type name T (e.g., "convert
... to T") after refactoring to R/M, reducing the actionable context of failures
during numeric conversions.

Referred Code
let n_t = R::from_f64(n as f64).ok_or_else(|| {
    TopologyError::LatticeGaugeError("Failed to convert matrix dimension to T".to_string())
})?;

for (edge, u) in self.links.iter() {
    // Compute staple and force
    let staple = self.try_staple(edge)?;
    let staple_dag = staple.dagger();
    let u_v_dag = u.mul(&staple_dag);

    // Force: F = β (U·V† - (1/N) Tr(U·V†) I) / N
    // For flow: we use simplified form proportional to staple
    let neg_eps = R::from_f64(-1.0).ok_or_else(|| {
        TopologyError::LatticeGaugeError("Failed to convert -1.0 to T".to_string())
    })? * *epsilon;
    let neg_eps_m = M::from_re_im(neg_eps, R::zero());
    let beta_norm_m = M::from_re_im(self.beta / n_t, R::zero());
    let update = u_v_dag
        .try_scale(&neg_eps_m)
        .map_err(TopologyError::from)?
        .try_scale(&beta_norm_m)


 ... (clipped 101 lines)

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

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

@codecov
Copy link
Copy Markdown

codecov Bot commented Jan 12, 2026

Codecov Report

❌ Patch coverage is 94.22750% with 34 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.38%. Comparing base (613a325) to head (ec7dd85).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
...lity_topology/src/types/gauge/link_variable/ops.rs 85.71% 19 Missing ⚠️
...pes/gauge/gauge_field_lattice/ops_gradient_flow.rs 86.36% 9 Missing ⚠️
...c/types/gauge/gauge_field_lattice/ops_continuum.rs 89.18% 4 Missing ⚠️
.../src/types/gauge/gauge_field_lattice/ops_plague.rs 97.29% 1 Missing ⚠️
.../src/types/gauge/gauge_field_lattice/ops_wilson.rs 97.22% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #450      +/-   ##
==========================================
+ Coverage   93.35%   93.38%   +0.03%     
==========================================
  Files         853      854       +1     
  Lines       38384    38547     +163     
==========================================
+ Hits        35835    35999     +164     
+ Misses       2549     2548       -1     

☔ 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.

@marvin-hansen marvin-hansen merged commit 17b1ab0 into deepcausality-rs:main Jan 12, 2026
12 of 15 checks passed
@qodo-code-review
Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Validate matching beta before zip

In zip_with, add a check to ensure that the beta values of both gauge fields are
equal before combining them, and return an error if they mismatch.

deep_causality_topology/src/extensions/hkt_gauge/hkt_lattice_gauge.rs [272-278]

 // Combine link variables
 let lattice = field_a.lattice_arc().clone();
+if field_a.beta() != field_b.beta() {
+    return Err(TopologyError::BetaMismatch(
+        *field_a.beta(),
+        *field_b.beta(),
+    ));
+}
 let beta = *field_a.beta();
 let mut new_links = HashMap::with_capacity(field_a.links().len());

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: This suggestion correctly identifies a potential runtime bug where two gauge fields with different coupling constants (beta) could be silently combined, leading to physically incorrect results. Adding an explicit check and returning an error is a critical improvement for correctness and robustness.

Medium
Better Miller initial value

Initialize the r variable in bessel_ratio_miller with the asymptotic value x /
(two * flt!((n_max + 1) as f64)) instead of zero to improve numerical stability.

examples/physics_examples/gauge_lattice_u1_2d/main.rs [55-74]

     fn bessel_ratio_miller(x: FloatType) -> FloatType {
       let n_max = 100;
       let two = flt!(2.0);
-  
-      // Start with asymptotic approximation for large n: r_n ≈ x / (2(n+1))
--    let mut r = flt!(0.0); // For large n, r_n → 0
-+    let mut r = flt!(0.0); // For large n, r_n → 0
++
++    // Start with better asymptotic approximation for large n
++    let mut r = x / (two * flt!((n_max + 1) as f64));
       // Backward recurrence: r_n = x / (2(n+1) + x * r_{n+1})
       for n in (0..=n_max).rev() {
         let two_n_plus_2 = two * flt!((n + 1) as f64);
         r = x / (two_n_plus_2 + x * r);
       }
       r
     }

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 6

__

Why: The suggestion correctly points out that initializing Miller's backward recurrence with the asymptotic value x / (2*(n_max+1)) instead of 0.0 can improve numerical stability and convergence, which is a valuable enhancement.

Low
Eliminate duplicate field-strength calls

Remove the redundant calls to try_field_strength for _f01 and _f23 to avoid
unnecessary computation.

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_continuum.rs [165-170]

-// F_01 * F_23
-let _f01 = self.try_field_strength(site, 0, 1)?;
-let _f23 = self.try_field_strength(site, 2, 3)?;
 // F_01 * F_23
 let f01 = self.try_field_strength(site, 0, 1)?;
 let f23 = self.try_field_strength(site, 2, 3)?;
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies and removes duplicated, computationally expensive function calls, which improves performance and cleans up the code.

Low
Possible issue
Use exp method on value

Correct the RealField::exp call to be a method call on the value, changing
RealField::exp(-delta_s) to (-delta_s).exp().

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_metropolis.rs [95-110]

     let accept = if delta_s < R::zero() {
       true
     } else {
       let rnd: f64 = rng.random();
       let r = R::from_f64(rnd).ok_or_else(|| {
           TopologyError::LatticeGaugeError("Failed to convert random value to T".to_string())
       })?;
       if !delta_s.is_finite() {
           false
       } else {
--       r < RealField::exp(-delta_s)
-+       r < RealField::exp(-delta_s)
++       (-delta_s).exp().gt(&r)
       }
     };

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 8

__

Why: The PR introduces a bug by changing a valid method call (-delta_s).exp() to an invalid associated function call RealField::exp(-delta_s). This suggestion correctly identifies and fixes this critical compilation error.

Medium
Center random perturbation

Center the random perturbation in generate_small_su_n_update by subtracting 0.5
from the value generated by M::generate_uniform(rng).

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_metropolis.rs [179-210]

-    fn generate_small_su_n_update<RngType>(
-        &self,
-        epsilon: R,
-        rng: &mut RngType,
-    ) -> Result<LinkVariable<G, M, R>, TopologyError>
-  where
-    RngType: deep_causality_rand::Rng,
-    M: RandomField + DivisionAlgebra<R> + Field + ComplexField<R>,
-    R: RealField,
-    {
-      // Start with identity
-      let result = LinkVariable::<G, M, R>::try_identity().map_err(TopologyError::from)?;
-  
-      // Add small random perturbation
-      let n = G::matrix_dim();
-      let data = result.as_slice();
-      let mut new_data = data.to_vec();
-  
-+    // Convert epsilon to M for scaling
-      let eps_m = M::from_re_im(epsilon, R::zero());
-  
-      for i in 0..n {
-        for j in 0..n {
--         // Generate uniform in [-0.5, 0.5] from RandomField
--         let r_val = M::generate_uniform(rng);
-+         // Center the uniform sample around zero
-+         let raw = M::generate_uniform(rng);
-+         let shift = M::from_re_im(R::from_f64(0.5).ok_or_else(|| TopologyError::LatticeGaugeError("Failed to convert 0.5 to R".to_string()))?, R::zero());
-+         let r_val = raw - shift;
-  
-          // perturbation = epsilon * r_val
-          let perturbation = eps_m * r_val;
-          new_data[i * n + j] = new_data[i * n + j] + perturbation;
-        }
-      }
++       // Center the uniform sample around zero
++       let raw = M::generate_uniform(rng);
++       let shift = M::from_re_im(
++           R::from_f64(0.5).ok_or_else(|| TopologyError::LatticeGaugeError("Failed to convert 0.5 to R".to_string()))?,
++           R::zero(),
++       );
++       let r_val = raw - shift;

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that the random perturbation is not centered around zero as intended, which is a bug in the Metropolis update logic. Fixing this is important for the correctness of the simulation.

Medium
Avoid panics in infallible functions

In gauge_transform, replace .expect() with a match statement to handle potential
multiplication errors gracefully by logging the error and preserving the
original link, thus avoiding a panic.

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_gauge.rs [71-77]

 // U' = g(n) U g(n+μ)†
-let new_u = g_n.try_mul(u).and_then(|tmp| tmp.try_mul(&g_n_plus_mu_dag));
+let new_u = g_n
+    .try_mul(u)
+    .and_then(|tmp| tmp.try_mul(&g_n_plus_mu_dag));
 
-// Panic on failure (infallible in theory if shapes match)
-let new_u = new_u.expect("Gauge transform multiplication failed");
+// If multiplication fails, log it and keep the old link.
+let new_u = match new_u {
+    Ok(link) => link,
+    Err(e) => {
+        // This part of the code is expected to be infallible.
+        // A failure indicates a severe logic error.
+        // Instead of panicking, we log the error and keep the old link.
+        eprintln!("Error during gauge transform: {:?}. Keeping original link.", e);
+        u.clone()
+    }
+};
 
 (cell.clone(), new_u)
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies that using .expect() in an "infallible" function is a design contradiction and proposes a more graceful failure mode that avoids panicking, improving the library's robustness.

Medium
Avoid panics in default constructors

Replace .unwrap() in ape_default and stout_default with fallible try_... methods
that return a Result to avoid potential panics and improve robustness.

deep_causality_topology/src/types/gauge/gauge_field_lattice/ops_smearing.rs [31-47]

 impl<R: RealField + FromPrimitive> SmearingParams<R> {
     /// Default APE smearing parameters.
-    pub fn ape_default() -> Self {
-        Self {
-            alpha: R::from_f64(0.45).unwrap(),
+    pub fn try_ape_default() -> Result<Self, TopologyError> {
+        Ok(Self {
+            alpha: R::from_f64(0.45).ok_or_else(|| {
+                TopologyError::LatticeGaugeError("Failed to convert APE alpha".to_string())
+            })?,
             n_steps: 10,
-        }
+        })
     }
 
     /// Default stout smearing parameters.
-    pub fn stout_default() -> Self {
-        Self {
-            alpha: R::from_f64(0.12).unwrap(),
+    pub fn try_stout_default() -> Result<Self, TopologyError> {
+        Ok(Self {
+            alpha: R::from_f64(0.12).ok_or_else(|| {
+                TopologyError::LatticeGaugeError("Failed to convert Stout alpha".to_string())
+            })?,
             n_steps: 6,
-        }
+        })
     }
 }
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies the use of .unwrap() as a potential panic point and proposes a robust, fallible constructor pattern, which is consistent with the library's design.

Low
  • More

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