Skip to content

Commit

Permalink
Fix Moment.resolve_parameter for constant sympy expressions (#6794)
Browse files Browse the repository at this point in the history
Problem: `Moment._resolve_parameters_` might keep constant sympy expression
if its resolved value is numerically equal.

Solution: Check if parameterization changed for the resolved operation and
if so replace the original operation with resolved (even if equal).

Fixes #6778

---------

Co-authored-by: Pavol Juhas <[email protected]>
Co-authored-by: Noureldin <[email protected]>
  • Loading branch information
3 people authored Nov 19, 2024
1 parent b35382f commit 7096acd
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
7 changes: 5 additions & 2 deletions cirq-core/cirq/circuits/moment.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,11 @@ def _resolve_parameters_(
resolved_ops: List['cirq.Operation'] = []
for op in self:
resolved_op = protocols.resolve_parameters(op, resolver, recursive)
if resolved_op != op:
changed = True
changed = (
changed
or resolved_op != op
or (protocols.is_parameterized(op) and not protocols.is_parameterized(resolved_op))
)
resolved_ops.append(resolved_op)
if not changed:
return self
Expand Down
8 changes: 8 additions & 0 deletions cirq-core/cirq/circuits/moment_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,14 @@ def test_resolve_parameters():
moment = cirq.Moment(cirq.X(a) ** sympy.Symbol('v'), cirq.Y(b) ** sympy.Symbol('w'))
resolved_moment = cirq.resolve_parameters(moment, cirq.ParamResolver({'v': 0.1, 'w': 0.2}))
assert resolved_moment == cirq.Moment(cirq.X(a) ** 0.1, cirq.Y(b) ** 0.2)
# sympy constant is resolved to a Python number
moment = cirq.Moment(cirq.Rz(rads=sympy.pi).on(a))
resolved_moment = cirq.resolve_parameters(moment, {'pi': np.pi})
assert resolved_moment == cirq.Moment(cirq.Rz(rads=np.pi).on(a))
resolved_gate = resolved_moment.operations[0].gate
assert not isinstance(resolved_gate.exponent, sympy.Basic)
assert isinstance(resolved_gate.exponent, float)
assert not cirq.is_parameterized(resolved_moment)


def test_resolve_parameters_no_change():
Expand Down

0 comments on commit 7096acd

Please sign in to comment.