Skip to content

Removing remnant legacy methods #608

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

Open
wants to merge 24 commits into
base: develop
Choose a base branch
from
Open

Removing remnant legacy methods #608

wants to merge 24 commits into from

Conversation

apchytr
Copy link
Collaborator

@apchytr apchytr commented Jun 18, 2025

User description

Context: As an exercise, this PR aims to remove many of the methods that are no longer used in the core functionality of Mr Mustard.

Description of the Change: Updated DM.physical_stellar_decomposition_mixed to make use of math.pinv and updated the tensorflow pinv to account for the complex case. Updated several tests that globally mutated settings to instead make use of the context manager. Obliterated random.py. Removed the following:

backend_manager.py

  • atleast_1d, atleast_2d, atleast_3d, block_diag, boolean_mask, constraint_func, convolution, repeat, round, set_diag, squeeze, cholesky, Categorical, MultivariateNormalTriL, single_mode_to_multimode_vec, single_mode_to_multimode_mat, poisson, binomial_conditional_prob, convolve_probs_1d, convolve_probs

bargmann_utils.py

  • norm_ket, trace_dm

fock_utils.py

  • ket_to_dm, ket_to_probs, dm_to_probs, U_to_choi, number_means, number_variances, validate_contraction_indices, sample_homodyne

gaussian.py

  • number_cov, log_negativity

gaussian_integrals.py

  • reorder_abc

Benefits: A more lightweight Mr Mustard experience.

Possible Drawbacks: Many of these methods may still be useful for user to have access to outside of the core MM functionality. In this case, this PR can always serve as reference for these methods and we can reintroduce them on a "as needed" basis.


PR Type

Other


Description

• Remove legacy unused methods from backend managers
• Update tests to use settings context manager
• Fix TensorFlow pinv for complex matrices
• Replace deprecated atleast_1d/2d/3d with atleast_nd


Changes walkthrough 📝

Relevant files
Tests
4 files
test_opt_lab.py
Replace global settings mutation with context manager       
+365/-357
test_callbacks.py
Use settings context manager in tests                                       
+34/-34 
test_lattice_functions.py
Use settings context manager in tests                                       
+8/-8     
test_b_to_ps.py
Use settings context manager in tests                                       
+2/-3     
Enhancement
8 files
backend_manager.py
Remove legacy unused backend methods                                         
+17/-363
backend_jax.py
Remove legacy JAX backend methods                                               
+1/-109 
backend_numpy.py
Remove legacy NumPy backend methods                                           
+1/-134 
backend_tensorflow.py
Remove legacy methods and fix complex pinv                             
+11/-67 
fock_utils.py
Replace atleast_1d with atleast_nd                                             
+2/-125 
dm.py
Use math.pinv instead of numpy.linalg.pinv                             
+1/-1     
utils.py
Replace atleast_1d with atleast_nd                                             
+1/-1     
circuits.py
Replace atleast_1d with atleast_nd                                             
+1/-1     
Additional files
7 files
bargmann_utils.py +0/-23   
gaussian.py +0/-44   
gaussian_integrals.py +0/-32   
test_backend_manager.py +0/-129 
test_bargmann_utils.py +0/-18   
test_fock_utils.py +0/-26   
test_gaussian_integrals.py +0/-23   

Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • @apchytr apchytr added the no changelog Pull request does not require a CHANGELOG entry label Jun 18, 2025
    @qodo-merge-pro qodo-merge-pro bot added the Other label Jun 18, 2025
    Copy link
    Contributor

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🏅 Score: 82
    🧪 PR contains tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Complex Matrix

    The new TensorFlow pinv implementation for complex matrices uses a custom algorithm that may not be numerically stable for all cases. The implementation should be validated against edge cases like singular matrices, matrices with very small eigenvalues, and matrices with different condition numbers.

    # need to handle complex case on our own
    # https://stackoverflow.com/questions/60025950/tensorflow-pseudo-inverse-doesnt-work-for-complex-matrices
    real_matrix = tf.math.real(matrix)
    imag_matrix = tf.math.imag(matrix)
    r0 = tf.linalg.pinv(real_matrix) @ imag_matrix
    y11 = tf.linalg.pinv(imag_matrix @ r0 + real_matrix)
    y10 = -r0 @ y11
    return tf.cast(tf.complex(y11, y10), dtype=matrix.dtype)
    Missing Import

    The removal of scipy.special.binom import may cause issues if any remaining code still depends on binomial coefficient calculations. Need to verify all usages have been properly removed or replaced.

    from jax.errors import TracerArrayConversionError
    import numpy as np
    from scipy.stats import ortho_group, unitary_group
    
    from ..utils.settings import settings
    Numerical Stability

    The change from numpy.linalg.pinv to math.pinv may affect numerical stability and performance. The math.pinv implementation should handle edge cases consistently with the previous numpy implementation.

    gamma = math.pinv(R_c) @ R
    gamma_transpose = math.einsum("...ij->...ji", gamma)

    Copy link
    Contributor

    qodo-merge-pro bot commented Jun 18, 2025

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Add error handling for complex matrices

    The complex pseudo-inverse implementation may fail for singular matrices or when
    the intermediate matrix imag_matrix @ r0 + real_matrix becomes singular. Add
    error handling or fallback to the standard tf.linalg.pinv for real matrices to
    prevent runtime failures.

    mrmustard/math/backend_tensorflow.py [277-285]

     def pinv(matrix: tf.Tensor) -> tf.Tensor:
    -    # need to handle complex case on our own
    -    # https://stackoverflow.com/questions/60025950/tensorflow-pseudo-inverse-doesnt-work-for-complex-matrices
    +    # Handle real matrices with standard pinv
    +    if not tf.dtypes.as_dtype(matrix.dtype).is_complex:
    +        return tf.linalg.pinv(matrix)
    +    
    +    # Complex case - custom implementation
         real_matrix = tf.math.real(matrix)
         imag_matrix = tf.math.imag(matrix)
         r0 = tf.linalg.pinv(real_matrix) @ imag_matrix
    -    y11 = tf.linalg.pinv(imag_matrix @ r0 + real_matrix)
    +    intermediate = imag_matrix @ r0 + real_matrix
    +    y11 = tf.linalg.pinv(intermediate)
         y10 = -r0 @ y11
         return tf.cast(tf.complex(y11, y10), dtype=matrix.dtype)
    • Apply / Chat
    Suggestion importance[1-10]: 8

    __

    Why: The suggestion correctly points out that the custom pinv implementation is for complex matrices. Adding a check to use the standard tf.linalg.pinv for real matrices is a good practice that improves robustness and prevents potential runtime errors.

    Medium
    • Update

    Copy link

    codecov bot commented Jun 18, 2025

    Codecov Report

    All modified and coverable lines are covered by tests ✅

    Project coverage is 92.28%. Comparing base (9d12319) to head (0883982).

    Additional details and impacted files
    @@             Coverage Diff             @@
    ##           develop     #608      +/-   ##
    ===========================================
    + Coverage    91.55%   92.28%   +0.72%     
    ===========================================
      Files          102      102              
      Lines         5828     5700     -128     
    ===========================================
    - Hits          5336     5260      -76     
    + Misses         492      440      -52     
    Files with missing lines Coverage Δ
    mrmustard/lab/circuits.py 91.93% <ø> (ø)
    mrmustard/lab/states/dm.py 100.00% <100.00%> (ø)
    mrmustard/lab/utils.py 95.65% <100.00%> (ø)
    mrmustard/math/backend_manager.py 96.12% <100.00%> (+5.19%) ⬆️
    mrmustard/physics/bargmann_utils.py 100.00% <ø> (ø)
    mrmustard/physics/fock_utils.py 99.04% <100.00%> (+12.09%) ⬆️
    mrmustard/physics/gaussian.py 97.50% <ø> (+18.65%) ⬆️
    mrmustard/physics/gaussian_integrals.py 98.46% <ø> (+0.35%) ⬆️

    Continue to review full report in Codecov by Sentry.

    Legend - Click here to learn more
    Δ = absolute <relative> (impact), ø = not affected, ? = missing data
    Powered by Codecov. Last update 9d12319...0883982. Read the comment docs.

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

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    no changelog Pull request does not require a CHANGELOG entry Other Review effort 4/5
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    1 participant