forked from evpiliouras/qurveros
-
Notifications
You must be signed in to change notification settings - Fork 7
UNITARY HACK--Fix dtype exceptions and add test for dtype conversion #13
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
AdwaithaV
wants to merge
2
commits into
error-corp:main
Choose a base branch
from
AdwaithaV:fix_data_type_exceptions_4_final_solved
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,7 +6,8 @@ | |
| import jax | ||
| import jax.numpy as jnp | ||
| import functools | ||
| import re | ||
AdwaithaV marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| import numpy as np | ||
| import warnings | ||
|
|
||
| from qurveros.settings import settings | ||
| from qurveros import controltools, frametools, beziertools, plottools | ||
|
|
@@ -90,35 +91,6 @@ def __init__(self, *, curve, order, interval, params=None, | |
|
|
||
| # Ensure correct types for frenet_dict calculations. | ||
| if curve is not None: | ||
| if isinstance(curve, str): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This whole deleted block from line 93 to line 121 should not have been deleted. When you look at the diff between the main branch and your code, you should see only the two insertions in lines 9 and 10, and then the insertions for the type conversion. |
||
| #Ensure characters are safe | ||
| if re.search(r'[^0-9A-Za-z_ \[\],\+\-\*\/\(\).]', curve): | ||
| raise ValueError("Unsafe characters in curve expression") | ||
|
|
||
| #Get params | ||
| raw_names = [m.group(1) | ||
| for m in re.finditer(r'\b([A-Za-z_]\w*)\b', curve)] | ||
| #Find all of the math functions within jnp | ||
| safe_math = { | ||
| name: getattr(jnp, name) | ||
| for name in dir(jnp) | ||
| if not name.startswith("_") | ||
| } | ||
| reserved = set(safe_math) | {'x', 'jnp'} | ||
| #Preserve first-seen order | ||
| param_names = [n for n in dict.fromkeys(raw_names) if n not in reserved] | ||
|
|
||
| #Build the source | ||
| src = "def _f(x, params):\n" | ||
| if param_names: | ||
| src += f" {', '.join(param_names)} = params\n" | ||
| src += f" return jnp.array({curve})" | ||
|
|
||
| #Create the exec | ||
| safe_globals = {"__builtins__": None, "jnp": jnp, **safe_math} | ||
| exec(src, safe_globals) | ||
| curve = safe_globals['_f'] | ||
|
|
||
| def curve_fun(x, params): | ||
| return 1.0*jnp.array(curve(x, params)).flatten() | ||
|
|
||
|
|
@@ -163,7 +135,31 @@ def set_params(self, params): | |
| evaluated for the new set of auxiliary parameters. | ||
| """ | ||
|
|
||
| self.params = params | ||
| #Determine the correct float type based on JAX config | ||
| float_dtype= jnp.float64 if jax.config.jax_enable_x64 else jnp.float32 | ||
|
|
||
| def convert_value(v): | ||
|
|
||
| """Helper function that recursively convert values to JAX-compatible floats""" | ||
| if isinstance(v,(jnp.ndarray,np.ndarray)): | ||
| if not jnp.issubdtype(v.dtype,jnp.floating): | ||
| warnings.warn(f"Converting array to {float_dtype}") | ||
| return jnp.asarray(v,dtype=float_dtype) | ||
| return v | ||
| elif isinstance(v,(list,tuple)): | ||
| return jnp.asarray(v,dtype=float_dtype) | ||
| elif isinstance(v,(int,float)): | ||
| warnings.warn(f"Converting scalar{v} to {float_dtype}") | ||
| return jnp.array(v, dtype=float_dtype) | ||
| elif isinstance(v,dict): | ||
| return {k:convert_value(v) for k,v in v.items()} | ||
| return v | ||
|
|
||
| #Convert all parameters while preserving the original structure | ||
| converted_params ={ | ||
| k:convert_value(v) for k ,v in params.items() | ||
| } | ||
| self.params = converted_params | ||
|
|
||
| self.frenet_dict = None | ||
| self.control_dict = None | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| import jax | ||
| import jax.numpy as jnp | ||
| import numpy as np | ||
| from qurveros.optspacecurve import BarqCurve | ||
| from qurveros.optspacecurve import OptimizableSpaceCurve | ||
| from qurveros.optspacecurve import SpaceCurve | ||
AdwaithaV marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| import warnings | ||
|
|
||
| def test_dtype_conversion(): | ||
AdwaithaV marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """Test that all numeric parameters are properly converted to JAX float types""" | ||
| # Capture warnings to verify conversions | ||
| with warnings.catch_warnings(record=True) as w: | ||
| warnings.simplefilter("always") | ||
|
|
||
| # Test 1: Direct parameter setting in SpaceCurve | ||
| sc = SpaceCurve(curve=lambda x, p: x*p, order=0, interval=[0,1]) | ||
|
|
||
| # Create test params with mixed types | ||
| test_params = { | ||
| 'int_scalar': 42, | ||
| 'float_scalar': 3.14, | ||
| 'np_int_array': np.array([1, 2, 3], dtype=np.int32), | ||
| 'np_float_array': np.array([1.1, 2.2], dtype=np.float32), | ||
| 'nested': { | ||
| 'int_list': [4, 5, 6], | ||
| 'jax_array': jnp.array([7, 8], dtype=jnp.int32) | ||
| } | ||
| } | ||
|
|
||
| sc.set_params(test_params) | ||
| params = sc.get_params() | ||
|
|
||
| # Verify conversions | ||
| assert isinstance(params['int_scalar'], jnp.ndarray) | ||
| assert params['int_scalar'].dtype in (jnp.float32, jnp.float64) | ||
|
|
||
| assert isinstance(params['np_int_array'], jnp.ndarray) | ||
| assert params['np_int_array'].dtype in (jnp.float32, jnp.float64) | ||
|
|
||
| assert isinstance(params['nested']['int_list'], jnp.ndarray) | ||
| assert params['nested']['int_list'].dtype in (jnp.float32, jnp.float64) | ||
|
|
||
| # Even pre-existing JAX int arrays should be converted | ||
| assert params['nested']['jax_array'].dtype in (jnp.float32, jnp.float64) | ||
|
|
||
| # Test 2: BarqCurve initialization path | ||
| adj_target = jnp.eye(3) | ||
| barq = BarqCurve(adj_target=adj_target, n_free_points=3) | ||
|
|
||
| barq.initialize_parameters( | ||
| init_free_points=np.array([[1,2,3],[4,5,6]], dtype=np.int32), | ||
| init_prs_params={'test_int': 42} | ||
| ) | ||
|
|
||
| barq_params = barq.get_params() | ||
| assert barq_params['free_points'].dtype in (jnp.float32, jnp.float64) | ||
| assert barq_params['prs_params']['test_int'].dtype in (jnp.float32, jnp.float64) | ||
|
|
||
| # Verify warnings were issued for conversions | ||
| assert len(w) > 0, "Expected conversion warnings" | ||
| print("\nConversion warnings detected (expected):") | ||
| for warning in w: | ||
| print(f"- {warning.message}") | ||
|
|
||
| print("\nAll dtype conversions passed successfully!") | ||
|
|
||
| if __name__ == "__main__": | ||
| # Configure JAX to use float32 (typical default) | ||
| jax.config.update('jax_enable_x64', False) | ||
| print("Testing with jax_enable_x64=False (float32 mode)") | ||
| test_dtype_conversion() | ||
|
|
||
| # Retest with float64 mode | ||
| jax.config.update('jax_enable_x64', True) | ||
| print("\nTesting with jax_enable_x64=True (float64 mode)") | ||
| test_dtype_conversion() | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.