-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Closed
Closed
Copy link
Labels
Description
Environment
- Qiskit Terra version: main branch
- Python version: 3.11
- Operating system: Linux
What is happening?
When using SymEngine, sometimes a ParameterExpression
wraps a SymEngine expression that is equivalent to a float. But trying to convert the ParameterExpression
to a float fails with an error claiming that there are unbound parameters, when in fact all parameters are bound.
How can we reproduce the issue?
The following prints True
three times.
from qiskit import QuantumCircuit
from qiskit.circuit import Parameter, ParameterExpression
x = Parameter("x")
pex = 1j * x
pexb = pex.bind({x : 1j})
print(str(pexb) == '-1.0')
print(complex(pexb) == -1)
print(isinstance(complex(pexb), complex))
But this fails:
float(pexb)
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
File ~/qiskit/qiskit-terra/qiskit/circuit/parameterexpression.py:474, in ParameterExpression.__float__(self)
473 try:
--> 474 return float(self._symbol_expr)
475 # TypeError is for sympy, RuntimeError for symengine
File symengine_wrapper.pyx:1151, in symengine.lib.symengine_wrapper.Basic.__float__()
File symengine_wrapper.pyx:976, in symengine.lib.symengine_wrapper.Basic.n()
File symengine_wrapper.pyx:4346, in symengine.lib.symengine_wrapper.evalf()
RuntimeError: Not Implemented
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
Cell In[17], line 1
----> 1 float(pexb)
File ~/qiskit/qiskit-terra/qiskit/circuit/parameterexpression.py:477, in ParameterExpression.__float__(self)
475 # TypeError is for sympy, RuntimeError for symengine
476 except (TypeError, RuntimeError) as exc:
--> 477 raise TypeError(
478 "ParameterExpression with unbound parameters ({}) "
479 "cannot be cast to a float.".format(self.parameters)
480 ) from exc
TypeError: ParameterExpression with unbound parameters (set()) cannot be cast to a float.
The error message is misleading. The attempt made to cast to a float failed, but for a different reason.
What should happen?
Maybe
- Try to avoid calling
float
on the wrapped expression. Trap the attempt and print or forward the underlying reason (not implemented) - Call
complex
instead, check if the result is a float. If so return it, else raise error. This is the approach in Assign values directly to fully bound parameters in quantum circuits #10183
Any suggestions?
No response