Claude 3.7 sonnet generated matlab version of the blochsim
part in sims.py
#2
tianrluo
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I was curious, so I tried a prompt of:
with https://github.com/tianrluo/MRphy.py/blob/master/mrphy/sims.py#L1-L315 pasted into the chatbox of Claude.
It returned me the attached file.
bloch-simulator-matlab.txt
and its response:
I'll convert this Python script to MATLAB. The script implements a Bloch simulator with explicit Jacobian operations for differentiation. Let me create the MATLAB equivalent: I've created a complete MATLAB translation of the Python Bloch simulation code. Let me explain some of the key transformations I made: Major Conversion Points: Function Organization: MATLAB doesn't have Python's class-based structure with forward and backward methods, so I've restructured it into multiple functions: blochsim (main function that users call) blochsim_forward (handles forward simulation) blochsim_backward (handles gradient calculation) Helper functions for relaxation Parameter Handling: Converted Python's keyword arguments to MATLAB's name-value pairs using inputParser Made sure optional parameters like T1/T2 are properly handled Tensor Operations: Replaced PyTorch tensor operations with MATLAB equivalents: torch.mul() → element-wise multiplication with .* torch.cross() → MATLAB's cross() function torch.norm() → MATLAB's vecnorm() function Memory Management: MATLAB handles memory differently, so I've structured the code to avoid unnecessary copies Used a cache struct to store intermediate values needed for the backward pass Variable Reshaping: MATLAB handles tensors differently than PyTorch, so I adjusted the dimension handling Added appropriate reshaping operations to ensure tensor dimensions match Function References: Replaced Python's lambda functions with MATLAB function handles Specific Implementation Notes: The blochsim_backward function implements the same algorithm as the Python backward method, calculating gradients with respect to input magnetization and effective magnetic field. In place of PyTorch's automatic gradient accumulation, I've made the gradients explicit. Special care was taken with the relaxation functions to ensure they behave the same way in forward and backward passes. The mathematics of rotation and magnetization evolution is preserved exactly as in the original code. This MATLAB implementation maintains all the functionality of the original Python code, including the crucial backward pass for gradient-based optimization. It could be integrated with MATLAB's automatic differentiation system if needed.
NOTE that I have not tested the matlab file that was generated by
Claude
.If anyone's interested, please try it yourself.
Beta Was this translation helpful? Give feedback.
All reactions