Skip to content

Commit

Permalink
Add sign() method to ParameterExpression
Browse files Browse the repository at this point in the history
This method allows applying the sign operation to an expression with
possibly unassigned parameters.
  • Loading branch information
SamD-1998 authored and wshanks committed Sep 20, 2023
1 parent e62c86b commit 0c318c2
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
11 changes: 11 additions & 0 deletions qiskit/circuit/parameterexpression.py
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,17 @@ def log(self):

return self._call(_log)

def sign(self):
"""Sign of a ParameterExpression"""
if _optionals.HAS_SYMENGINE:
import symengine

return self._call(symengine.sign)
else:
from sympy import sign as _sign

return self._call(_sign)

def __repr__(self):
return f"{self.__class__.__name__}({str(self)})"

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
features:
- |
Added support for expressing the sign of a :class: 'ParameterExpression'
Instead of assigning a concrete value and using ''numpy.sign'' or other library functions, the user can use the instance of the ParameterExpression
class to calculate the sign and can work with the sign before the expression is fully assigned.
It can be used as follows::
from qiskit.circuit import Parameter
b = Parameter("phi")
sign_value = b.sign()
print("sign of an unassigned Parameter is: ", sign_value)
print("Sign of a Parameter assigned to -3 is: ", sign_value.assign(b,-3))
Refer to ' #10360<https://github.com/Qiskit/qiskit-terra/issues/10360>'__ for more details.
9 changes: 9 additions & 0 deletions test/python/circuit/test_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -950,6 +950,15 @@ def test_rebinding_instruction_copy(self):
self.assertEqual(expected1, output1)
self.assertEqual(expected2, output2)

def test_sign_of_parameter(self):
"""Test returning the sign of the value of the parameter"""

b = Parameter("phi")
sign_of_parameter = b.sign()
self.assertEqual(sign_of_parameter.assign(b, -3), -1)
self.assertEqual(sign_of_parameter.assign(b, 2), 1)
self.assertEqual(sign_of_parameter.assign(b, 0), 0)

@combine(target_type=["gate", "instruction"], parameter_type=["numbers", "parameters"])
def test_decompose_propagates_bound_parameters(self, target_type, parameter_type):
"""Verify bind-before-decompose preserves bound values."""
Expand Down

0 comments on commit 0c318c2

Please sign in to comment.