Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

la.jacobi: fix incorrect eigen values/vectors #224

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

PottierLoic
Copy link
Contributor

@PottierLoic PottierLoic commented Mar 25, 2025

This PR resolves issue #202, where the Jacobi eigenvalue algorithm in vsl.la produced incorrect results. The original rotation logic failed to zero off-diagonal elements and broke the symmetry of the matrix a, resulting in incorrect eigenvalues (v) and eigenvectors (q).

I retained the initial test with a diagonal matrix:

mut a := la.Matrix.deep2([
  [2.0, 0.0, 0.0],
  [0.0, 2.0, 0.0],
  [0.0, 0.0, 2.0],
])

Expected : v = [2, 2, 2], q = identity, a unchanged. It still passes.

I added a new test for a more complex symmetric matrix, which was failing prior to the fix:

mut a := la.Matrix.deep2([
  [4.0, 1.0, 1.0],
  [1.0, 3.0, 0.0],
  [1.0, 0.0, 2.0],
])	

Expected : v = [4.879385241571816, 2.652703644666139, 1.467911113762045], q matches computed eigenvectors, a diagonalized. It now passes.

I compared the outputs against an online eigenvalue calculator.
v match exactly and q_values are matching the results from the solver once normalized.

I re-ran the code from #202 and it still doesn't return the expected values from the issue. I think there may be a problem in the code snippet provided too.

Summary by CodeRabbit

  • Refactor
    • Improved the matrix algorithm’s logic by revising convergence checks and updating numerical computations for enhanced clarity and correctness.
  • Tests
    • Expanded test coverage by introducing a new case for a symmetric 3x3 matrix and enhancing existing validations to ensure precise outputs.

Copy link

coderabbitai bot commented Mar 25, 2025

Walkthrough

The Jacobi method implementation has been updated to adjust its control flow and numerical updates. The convergence check now uses a break statement instead of an immediate return, and the computation of the difference variable has been reversed. Additional tolerance conditions have been added before processing further calculations. The matrix update logic has been refactored using a single loop, and the final matrix assembly now explicitly sets both diagonal and off-diagonal elements. In parallel, a new test case for a 3x3 symmetric matrix and additional assertions in an existing test have been introduced.

Changes

File Change Summary
la/jacobi.v Modified the jacobi function: convergence check now uses a break; reversed the computation of h; added extra tolerance checks; refactored matrix update loops; explicitly set diagonal/off-diagonal values; updated convergence validation.
la/jacobi_test.v Added a new test function test_jacobi_3x3_symmetric() for a 3x3 symmetric matrix; enhanced test_jacobi01() with additional assertions for updated matrix output.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller/Test
    participant Jacobi as jacobi()
    participant Matrix as Matrix (a, v, q)
    
    Caller->>Jacobi: Call jacobi(q, v, a)
    Note over Jacobi: Start iterations for Jacobi rotation
    
    Jacobi->>Jacobi: Compute h = v[j] - v[i]
    alt Tolerance Condition Met & Convergence Check
        Jacobi->>Jacobi: Break loop
    else Continue Calculations
        Jacobi->>Jacobi: Calculate t based on h and a.get(i, j)
        Jacobi->>Matrix: Update matrix values (aii, ajj, aij) and set a[i][j] to 0.0
    end
    
    Jacobi->>Matrix: Update remaining matrix entries (excluding i and j)
    Jacobi->>Matrix: Set diagonal elements to v and off-diagonals to zero
    Jacobi-->>Caller: Return updated matrices or error if not converged
Loading

Poem

I'm a bunny with a coder's delight,
Hopping through changes both day and night.
Jacobi's loop now twists and turns,
With each new check, my code burns.
Matrices dance with precision and cheer,
For in this code field, I’m the rabbit engineer!
🥕🐇 Happy coding!


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
la/jacobi_test.v (1)

35-63: Comprehensive test for a 3×3 symmetric matrix.

Introducing this test function is an excellent step, as it covers a non-trivial use case. Consider expanding validations further (e.g., checking orthonormality of the eigenvectors) for even greater confidence in correctness.

la/jacobi.v (1)

131-139: Convergence verification after final assembly.

Performing a final check on off-diagonal elements is good practice. For larger matrices or stricter needs, consider making max_iterations and tol externally configurable to handle edge cases without modifying the source.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8340b46 and 7544e43.

📒 Files selected for processing (2)
  • la/jacobi.v (2 hunks)
  • la/jacobi_test.v (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: run-tests-on-linux (ubuntu-22.04)
  • GitHub Check: run-tests-on-linux (ubuntu-20.04)
  • GitHub Check: run-tests-on-linux (ubuntu-24.04, --prod)
  • GitHub Check: run-tests-on-linux (ubuntu-22.04, --prod)
  • GitHub Check: run-tests-on-linux (ubuntu-20.04, --prod)
🔇 Additional comments (9)
la/jacobi_test.v (2)

22-26: Well-defined expected output for the diagonal matrix test.

These lines correctly define the expected diagonal matrix, matching the behavior where no rotation is needed. Good job including these checks to ensure the final matrix remains unchanged.


32-33: Great addition of the final matrix assertion.

Verifying that the resulting matrix a remains unchanged in test_jacobi01 ensures the algorithm’s correctness for trivial diagonal cases. This is an important validation step.

la/jacobi.v (7)

65-65: Switch to break for convergence check is appropriate.

Using break here allows the method to proceed with final matrix setup and validations, which is beneficial compared to an immediate return.


71-74: Early continuation for negligible off-diagonal elements.

Skipping the rotation when math.abs(a.get(i, j)) is below the tolerance is a valid optimization to avoid unnecessary computations while preserving accuracy.


77-77: Condition handles small differences robustly.

Checking math.abs(h) < tol in conjunction with math.abs(a.get(i, j)) accommodates tiny floating-point values, preventing numerical instability during rotation calculations.


90-99: Correct handling of updated diagonal and zeroed off-diagonal elements.

Properly adjusting a(i, i), a(j, j) and setting a(i, j) and a(j, i) to zero after computing t follows the Jacobi rotation approach, preserving symmetry and accurately tracking eigenvalues in v.


101-117: Single-pass updates for matrix rows and columns.

Applying the rotation in this unified loop ensures all relevant elements of a and q are updated consistently. This is a clean and efficient implementation of the Jacobi rotation procedure.


120-120: No changes needed here.

This is just the close of the nested loops. No issues are observed.


122-130: Final diagonalization step is standard Jacobi procedure.

Setting a(i, i) = v[i] while zeroing off-diagonal elements ensures that the final matrix a is diagonal, matching the extracted eigenvalues. This step aligns with the classical Jacobi method conclusion.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7544e43 and 556d557.

📒 Files selected for processing (1)
  • la/jacobi_test.v (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: run-tests-on-linux (ubuntu-20.04)
  • GitHub Check: run-tests-on-linux (ubuntu-22.04, --prod)
  • GitHub Check: run-tests-on-linux (ubuntu-22.04)
  • GitHub Check: run-tests-on-linux (ubuntu-20.04, --prod)
  • GitHub Check: run-tests-on-linux (ubuntu-24.04, --prod)
  • GitHub Check: run-tests-on-macos (macos-latest, --prod)
  • GitHub Check: run-tests-on-linux (ubuntu-24.04)
  • GitHub Check: run-tests-on-macos (macos-latest)
🔇 Additional comments (2)
la/jacobi_test.v (2)

22-32: Good addition of matrix verification in the existing test.

The addition of expected_a and its verification ensures that the Jacobi algorithm not only produces correct eigenvalues and eigenvectors but also correctly updates the input matrix a. This directly addresses the issue mentioned in the PR where the original implementation failed to properly zero off-diagonal elements.


35-63: Well-structured new test case for a complex symmetric matrix.

This is an excellent addition that tests the Jacobi algorithm with a non-trivial symmetric matrix. The test includes well-defined expected outputs for eigenvalues, eigenvectors, and the final state of matrix a. This test case directly addresses the issues mentioned in the PR objectives, where the original implementation produced incorrect results for non-diagonal matrices.

A few observations:

  1. The expected values have high precision, which suggests they were carefully calculated or verified against a reliable reference.
  2. The tolerance of 1e-14 for floating-point comparisons is appropriate for this type of numerical calculation.
  3. The test verifies all aspects of the algorithm's output: eigenvalues, eigenvectors, and the updated input matrix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant