Skip to content

Commit ae0a334

Browse files
Fix sympify() for expressions with vector element .subs() (#14641) (#14642)
This commit fixes an issue in the .sympify() method when building the Sympy expression for a `ParameterExpression` that was constructed by calling `ParameterExpression.subs()` with a ParameterVectorElement type. The previous implementation of this method was passing the symbols for substitution by string which required sympy to "parse" the input. The square brackets for indexing the vector element in it's string representation was not valid for sympy to parse and this caused the error. To avoid this problem this commit adjusts the usage to pass a sypy expression object instead of a string. This is the intent of the function as string parsing has other issues in sympy and this was an oversight in the implementation that was doing this. By passing a sympy object to sympy it is able to handle the vector's name with square brackets. Fixes #14640 (cherry picked from commit 69d7dbd) Co-authored-by: Matthew Treinish <[email protected]>
1 parent d9d72f7 commit ae0a334

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

qiskit/circuit/parameterexpression.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -683,8 +683,8 @@ def sympify(self):
683683
sympy_binds = {}
684684
for old, new in inst.binds.items():
685685
if isinstance(new, ParameterExpression):
686-
new = new.name
687-
sympy_binds[old.name] = new
686+
new = new.sympify()
687+
sympy_binds[old.sympify()] = new
688688
output = output.subs(sympy_binds, simultaneous=True)
689689
continue
690690

test/python/circuit/test_parameter_expression.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,3 +505,17 @@ def test_sympify_all_ops(self):
505505
expected = sympy.Abs(expected)
506506
expected = expected.subs({c: a})
507507
self.assertEqual(result, expected)
508+
509+
@unittest.skipUnless(HAS_SYMPY, "Sympy is required for this test")
510+
def test_sympify_subs_vector(self):
511+
"""Test an expression with subbed ParameterVectorElements is sympifiable"""
512+
import sympy
513+
514+
p_vec = ParameterVector("p", length=2)
515+
theta = Parameter("theta")
516+
517+
expression = theta + 1
518+
expression = expression.subs({theta: p_vec[0]})
519+
result = expression.sympify()
520+
expected = sympy.Symbol("p[0]") + 1
521+
self.assertEqual(expected, result)

0 commit comments

Comments
 (0)