Skip to content

Commit

Permalink
Test for presence of π in _expression_to_string (rigetti#1076)
Browse files Browse the repository at this point in the history
  • Loading branch information
notmgsk authored and karalekas committed Oct 28, 2019
1 parent 854bf41 commit 6155f4d
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ Changelog
- Updated `examples/meyer_penny_game.py` with the correct path to the Meyer Penny
game exercise in `docs/source/exercises.rst` (@appleby, gh-1045).
- Fixed the Slack Workspace invite link in the README (@amyfbrown, gh-1042).
- Fixed pretty printing of parameter expressions where π is involved
(@notmgsk, gh-1076).

[v2.12](https://github.com/rigetti/pyquil/compare/v2.11.0...v2.12.0) (September 28, 2019)
----------------------------------------------------------------------------------------
Expand Down
6 changes: 6 additions & 0 deletions pyquil/quilatom.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,12 @@ def _expression_to_string(expression):
or expression.precedence == expression.op2.precedence
and expression.associates in ('right', 'both')):
right = '(' + right + ')'
# If op2 is a float, it will maybe represented as a multiple
# of pi in right. If that is the case, then we need to take
# extra care to insert parens. See gh-943.
elif isinstance(expression.op2, float) and (
("pi" in right and right != "pi")):
right = '(' + right + ')'

return left + expression.operator + right
elif isinstance(expression, Function):
Expand Down
21 changes: 21 additions & 0 deletions pyquil/tests/test_quil.py
Original file line number Diff line number Diff line change
Expand Up @@ -1298,3 +1298,24 @@ def test_placeholders_preserves_modifiers():
a = address_qubits(p)

assert a[0].modifiers == g.modifiers


def _eval_as_np_pi(exp):
eval(exp.replace('pi', repr(np.pi)).replace('theta[0]', "1"))


def test_params_pi_and_precedence():
trivial_pi = "3 * theta[0] / (2 * pi)"
prog = Program(f"RX({trivial_pi}) 0")
exp = str(prog[0].params[0])
assert(_eval_as_np_pi(trivial_pi) == _eval_as_np_pi(exp))

less_trivial_pi = "3 * theta[0] * 2 / (pi)"
prog = Program(f"RX({trivial_pi}) 0")
exp = str(prog[0].params[0])
assert(_eval_as_np_pi(trivial_pi) == _eval_as_np_pi(exp))

more_less_trivial_pi = "3 / (theta[0] / (pi + 1)) / pi"
prog = Program(f"RX({trivial_pi}) 0")
exp = str(prog[0].params[0])
assert(_eval_as_np_pi(trivial_pi) == _eval_as_np_pi(exp))

0 comments on commit 6155f4d

Please sign in to comment.