diff --git a/CHANGELOG.md b/CHANGELOG.md index 44e286a0..4a59d336 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,7 @@ Types of changes: ### Removed ### Fixed +- Fixed Complex value initialization error. ([#253](https://github.com/qBraid/pyqasm/pull/253)) ### Dependencies - Bumps `@actions/checkout` from 4 to 5 ([#250](https://github.com/qBraid/pyqasm/pull/250)) diff --git a/src/pyqasm/maps/expressions.py b/src/pyqasm/maps/expressions.py index 7a6eef2e..6a907ac9 100644 --- a/src/pyqasm/maps/expressions.py +++ b/src/pyqasm/maps/expressions.py @@ -108,9 +108,9 @@ def qasm_variable_type_cast(openqasm_type, var_name, base_size, rhs_value): if type_of_rhs not in VARIABLE_TYPE_CAST_MAP[openqasm_type]: raise ValidationError( - f"Cannot cast {type_of_rhs} to {openqasm_type}. " - f"Invalid assignment of type {type_of_rhs} to variable {var_name} " - f"of type {openqasm_type}" + f"Cannot cast '{type_of_rhs.__name__}' to '{openqasm_type.__name__}'. " + f"Invalid assignment of type '{type_of_rhs.__name__}' to variable '{var_name}' " + f"of type '{openqasm_type.__name__}'" ) if openqasm_type == BoolType: @@ -130,6 +130,8 @@ def qasm_variable_type_cast(openqasm_type, var_name, base_size, rhs_value): return ((2 * CONSTANTS_MAP["pi"]) * (1 / 2)) if rhs_value else 0.0 return rhs_value # not sure if openqasm_type == ComplexType: + if isinstance(rhs_value, float): + return complex(rhs_value) return rhs_value @@ -166,7 +168,7 @@ def qasm_variable_type_cast(openqasm_type, var_name, base_size, rhs_value): UintType: (bool, int, float, np.int64, np.uint64, np.float64, np.bool_), FloatType: (bool, int, float, np.int64, np.float64, np.bool_), AngleType: (float, np.float64, bool, np.bool_), - ComplexType: (complex, np.complex128), + ComplexType: (complex, np.complex128, float, np.float64), } ARRAY_TYPE_MAP = { diff --git a/tests/qasm3/declarations/test_classical.py b/tests/qasm3/declarations/test_classical.py index 25d83444..1d6733f0 100644 --- a/tests/qasm3/declarations/test_classical.py +++ b/tests/qasm3/declarations/test_classical.py @@ -752,6 +752,14 @@ def test_complex_type_variables(): complex[float[64]] g = a ** b; complex[float] h = a + b; complex i = sqrt(1.0 + 2.0im); + complex j = 1.0; + complex k; + k = 1.0; + const complex l = 20.0; + float m = 1.0; + complex n = m; + complex o = l * (2 - 1im); + complex p = o + (1.0 + 1.0im); """ loads(qasm3_string).validate() diff --git a/tests/qasm3/resources/variables.py b/tests/qasm3/resources/variables.py index 2ef514f2..10415d25 100644 --- a/tests/qasm3/resources/variables.py +++ b/tests/qasm3/resources/variables.py @@ -447,8 +447,8 @@ const float[64] f1 = 2.5; const bit[2] b1 = bit[2](f1); """, - "Cannot cast to . Invalid assignment " - "of type to variable f1 of type ", + "Cannot cast 'float' to 'BitType'. Invalid assignment of type " + "'float' to variable 'f1' of type 'BitType'", 5, 8, "const bit[2] b1 = bit[2](f1);",