Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 7 additions & 10 deletions src/qurveros/optspacecurve.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,16 +312,13 @@ def initialize_parameters(self, *, init_free_points=None,
raise ValueError('Inconsistent number of free points with'
' provided initial free points.')

if init_pgf_params is None:

init_pgf_params = barqtools.get_default_pgf_params_dict()

if init_prs_params is None:
init_prs_params = {}

params['free_points'] = init_free_points
params['pgf_params'] = init_pgf_params
params['prs_params'] = init_prs_params
# Set parameters (type conversion happens in parent's set_params)

params.update({
'free_points': init_free_points,
'pgf_params': init_pgf_params or barqtools_get_default_pgf_params_dict(),
'prs_params': init_prs_params or {}
})

return super().initialize_parameters(params)

Expand Down
58 changes: 27 additions & 31 deletions src/qurveros/spacecurve.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
import jax
import jax.numpy as jnp
import functools
import re
import numpy as np
import warnings

from qurveros.settings import settings
from qurveros import controltools, frametools, beziertools, plottools
Expand Down Expand Up @@ -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):
Copy link

Choose a reason for hiding this comment

The 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()

Expand Down Expand Up @@ -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
Expand Down
77 changes: 77 additions & 0 deletions tests/test_fix_data_type.py
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

import warnings

def test_dtype_conversion():
"""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()