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

feat!: add correct computeJacobian method #485

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

vishwa2710
Copy link
Contributor

@vishwa2710 vishwa2710 commented Jan 5, 2025

  • Refactor computeJacobian to computeStateTransitionMatrix as that is what the method was actually doing
  • add a correct computeJacobian method that computes the jacobian of a state vector

Summary by CodeRabbit

  • New Features

    • Enhanced finite difference solver with improved state transition matrix computation
    • Added new Jacobian computation method for more flexible mathematical calculations
  • Refactor

    • Renamed computeJacobian method to computeStateTransitionMatrix
    • Updated method signatures and documentation across multiple files
    • Improved consistency in method naming and functionality
  • Tests

    • Updated test cases to reflect new method names and behaviors
    • Added new test scenarios for gradient and Jacobian computations

…teDifferenceSolver class and add computeJacobian
@vishwa2710 vishwa2710 self-assigned this Jan 5, 2025
@vishwa2710 vishwa2710 linked an issue Jan 5, 2025 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Jan 5, 2025

Walkthrough

The pull request introduces significant modifications to the FiniteDifferenceSolver across multiple files in the OpenSpaceToolkit Astrodynamics module. The primary changes involve renaming the computeJacobian method to computeStateTransitionMatrix and introducing a new computeJacobian method. These changes are consistently implemented across C++ header files, source files, Python bindings, and test suites. The modifications aim to clarify the distinction between computing state transition matrices and Jacobians while maintaining the overall solver functionality.

Changes

File Change Summary
bindings/python/src/OpenSpaceToolkitAstrodynamicsPy/Solver/FiniteDifferenceSolver.cpp - Renamed compute_jacobian to compute_state_transition_matrix
- Added new compute_jacobian method
bindings/python/test/solvers/test_finite_difference_solver.py - Renamed test methods to match new method names
- Added new test for compute_jacobian
include/OpenSpaceToolkit/Astrodynamics/Solver/FiniteDifferenceSolver.hpp - Renamed computeJacobian to computeStateTransitionMatrix
- Added new computeJacobian method
src/OpenSpaceToolkit/Astrodynamics/GuidanceLaw/QLaw.cpp - Updated method call from computeJacobian to computeStateTransitionMatrix
src/OpenSpaceToolkit/Astrodynamics/Solvers/FiniteDifferenceSolver.cpp - Renamed computeJacobian to computeStateTransitionMatrix
- Added new computeJacobian method
test/OpenSpaceToolkit/Astrodynamics/Solver/FiniteDifferenceSolver.test.cpp - Renamed test methods
- Added new test cases for gradient and Jacobian computations

Sequence Diagram

sequenceDiagram
    participant Solver as FiniteDifferenceSolver
    participant State as State Coordinates
    participant Function as Derivative Function

    Solver->>State: Access initial state
    Solver->>State: Apply perturbations
    Solver->>Function: Compute derivatives
    Solver->>Solver: Calculate State Transition Matrix or Jacobian
    Solver-->>State: Return computed matrix
Loading

Poem

🐰 A Solver's Transformation Tale 🧮

In matrices of state and change,
Our solver danced, its methods rearrange
From Jacobian to Transition's might,
Precision leaps to a new height!

Hop, hop, algorithm, clear and bright! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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
Contributor

@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 (3)
src/OpenSpaceToolkit/Astrodynamics/Solvers/FiniteDifferenceSolver.cpp (1)

141-141: Minor improvement suggestion for consistency.
Consider encapsulating the repeated pattern of computing stepSize in a small inline helper method to avoid duplication among your finite difference methods and to simplify code.

bindings/python/src/OpenSpaceToolkitAstrodynamicsPy/Solver/FiniteDifferenceSolver.cpp (1)

128-137: Docstring discrepancy.
The docstring mentions "Compute the jacobian," yet the method returns an STM. Ensure the docstring matches the actual functionality (STM).

-                Compute the jacobian.
+                Compute the state transition matrix (STM).
src/OpenSpaceToolkit/Astrodynamics/GuidanceLaw/QLaw.cpp (1)

662-662: Clarify function naming to avoid confusion.

Here, you retrieve a 5×1 vector of partial derivatives from computeStateTransitionMatrix, yet store that result in a variable named jacobian. Since this code is computing the gradient of a scalar function Q, consider calling the newly introduced computeJacobian method, or at least renaming the variable to avoid mixing the conceptual “Jacobian” of Q with a “state transition matrix.” This will help maintain clarity and consistency for future maintainers.

Here's a possible change to call computeJacobian (assuming it produces the same 5×1 vector of partial derivatives) and rename the local variable:

-    const Vector5d jacobian = Eigen::Map<Vector5d>(
-        finiteDifferenceSolver_
-            .computeStateTransitionMatrix(stateBuilder_.build(Instant::J2000(), aCOEVector), Instant::J2000(), getQ, 1)
-            .data(),
-        5
-    );
+    const Vector5d dQ_dOE_numeric = Eigen::Map<Vector5d>(
+        finiteDifferenceSolver_
+            .computeJacobian(stateBuilder_.build(Instant::J2000(), aCOEVector), Instant::J2000(), getQ, 1)
+            .data(),
+        5
+    );
+
+    return dQ_dOE_numeric;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d1c4ed4 and 8912019.

📒 Files selected for processing (6)
  • bindings/python/src/OpenSpaceToolkitAstrodynamicsPy/Solver/FiniteDifferenceSolver.cpp (2 hunks)
  • bindings/python/test/solvers/test_finite_difference_solver.py (3 hunks)
  • include/OpenSpaceToolkit/Astrodynamics/Solver/FiniteDifferenceSolver.hpp (3 hunks)
  • src/OpenSpaceToolkit/Astrodynamics/GuidanceLaw/QLaw.cpp (1 hunks)
  • src/OpenSpaceToolkit/Astrodynamics/Solvers/FiniteDifferenceSolver.cpp (7 hunks)
  • test/OpenSpaceToolkit/Astrodynamics/Solver/FiniteDifferenceSolver.test.cpp (14 hunks)
🔇 Additional comments (25)
src/OpenSpaceToolkit/Astrodynamics/Solvers/FiniteDifferenceSolver.cpp (6)

53-53: Great rename for clarity.
Renaming from a Jacobian-centric name to computeStateTransitionMatrix more precisely reflects its purpose.


152-152: Useful overloaded method.
This overload improves usability when a single instant is involved, ensuring consistent usage patterns.


170-170: Concise bridging function.
The local lambda approach to adapt a single-instant function into a multi-instant context is both elegant and succinct.


181-181: Good structured approach.
Using the chosen finite difference scheme consistently in computeGradient helps maintain coded clarity across forward, backward, and central difference logic.


193-193: Validation: negative step durations.
Consider checking if stepDuration_ is positive before using it. Negative or zero durations could produce unexpected results or divide-by-zero errors.


219-306: Well-structured Jacobian computation.
The introduction of computeJacobian separately from computeStateTransitionMatrix clarifies the difference between these matrices. Good job on distinct flows for forward, backward, and central differences.

include/OpenSpaceToolkit/Astrodynamics/Solver/FiniteDifferenceSolver.hpp (3)

Line range hint 86-96: Accurate docstrings.
The documentation now aligns well with the actual computation of the state transition matrix (STM).


103-112: Helpful overload.
Providing an overload for a single instant usage scenario is user-friendly and consistent.


130-139: Clear separation of responsibilities.
Defining computeJacobian as a separate public method helps disambiguate math concepts for end-users. Good clarity in the docstrings.

bindings/python/test/solvers/test_finite_difference_solver.py (3)

129-136: Consistent method rename.
Refactoring the test to test_compute_state_transition_matrix_array aligns with the newly introduced naming in the solver.


148-155: Clear single-instant STM test.
Renaming to test_compute_state_transition_matrix_single and verifying shape correctness ensures coverage for the single-instant path.


180-192: Robust check for the newly added compute_jacobian.
This test method properly ensures that the returned Jacobian is accurate. Great that it checks numerical precision.

bindings/python/src/OpenSpaceToolkitAstrodynamicsPy/Solver/FiniteDifferenceSolver.cpp (2)

99-108: Improved naming alignment.
Renaming the Python binding to compute_state_transition_matrix clarifies usage for Python consumers.


178-185: New binding for Jacobian.
Properly exposes computeJacobian to Python. The docstring precisely defines input and output expectations.

test/OpenSpaceToolkit/Astrodynamics/Solver/FiniteDifferenceSolver.test.cpp (11)

7-12: Added Earth environment includes.
These headers are essential to test gravitational models. Good addition to broaden coverage.


25-28: Imported matrix objects.
Clear usage of MatrixXd and VectorXd. Maintains consistency with the rest of the solver code.


Line range hint 48-73: Refactor function naming.
Renaming helper lambdas to generateStatesCoordinates_ and generateStateCoordinates_ clarifies their usage.


98-98: Step duration in microseconds.
Using microseconds can improve numerical accuracy but also consider potential floating-point rounding issues when computations involve large intervals.


112-113: Convenient function objects.
Storing lambdas as std::functions is flexible and keeps the test setup organized.


Line range hint 147-193: Thorough STM testing with multiple difference schemes.
These tests validate that computeStateTransitionMatrix is consistent across central, forward, and backward difference methods. Excellent approach.


Line range hint 200-236: Single-instant STM coverage.
Well-structured single-instant test block verifies shape and numeric correctness with each difference scheme.


Line range hint 252-277: Gradient checks.
Validating the gradient result with known expected outputs is a solid approach. Has coverage across difference schemes.


280-354: Extended two-body problem gradient test.
Comprehensive coverage with real-world physics ensures correctness in more complex scenarios. Great job.


384-444: General Jacobian test.
Confirms functional correctness of computeJacobian for a 2D simple harmonic oscillator. Proper numerical tolerance checks.


446-523: Robust two-body Jacobian test.
Brings added confidence in the solver’s real-world utility. Great to see domain-specific checks with gravitational effects.

Copy link

codecov bot commented Jan 5, 2025

Codecov Report

Attention: Patch coverage is 91.07143% with 5 lines in your changes missing coverage. Please review.

Project coverage is 91.20%. Comparing base (d1c4ed4) to head (8912019).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...t/Astrodynamics/Solvers/FiniteDifferenceSolver.cpp 90.90% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #485      +/-   ##
==========================================
- Coverage   91.21%   91.20%   -0.01%     
==========================================
  Files          86       86              
  Lines        8720     8769      +49     
==========================================
+ Hits         7954     7998      +44     
- Misses        766      771       +5     

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

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.

[feat] add computeJacobian in FiniteDifferenceSolver class
1 participant