Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalidate QuantumCircuit.parameters cache on global-phase modification #11641

Merged
merged 1 commit into from
Jan 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions qiskit/circuit/quantumcircuit.py
Original file line number Diff line number Diff line change
Expand Up @@ -2932,6 +2932,7 @@ def global_phase(self, angle: ParameterValueType):
# called by some subclasses before the inner `_global_phase` is initialised.
global_phase_reference = (ParameterTable.GLOBAL_PHASE, None)
if isinstance(previous := getattr(self, "_global_phase", None), ParameterExpression):
self._parameters = None
self._parameter_table.discard_references(previous, global_phase_reference)

if isinstance(angle, ParameterExpression) and angle.parameters:
Expand Down
18 changes: 18 additions & 0 deletions test/python/circuit/test_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,24 @@ def test_get_parameter_global_phase(self):
self.assertIs(qc.get_parameter("x"), x)
self.assertIsNone(qc.get_parameter("y", None), None)

def test_setting_global_phase_invalidates_cache(self):
"""Test that setting the global phase to a non-parametric value invalidates the `parameters`
cache of the circuit."""
x = Parameter("x")
qc = QuantumCircuit(0, global_phase=x)
self.assertEqual(qc.global_phase, x)
self.assertEqual(set(qc.parameters), {x})
qc.global_phase = 0
self.assertEqual(qc.global_phase, 0)
self.assertEqual(set(qc.parameters), set())

qc = QuantumCircuit(0, global_phase=0)
self.assertEqual(qc.global_phase, 0)
self.assertEqual(set(qc.parameters), set())
qc.global_phase = x
self.assertEqual(qc.global_phase, x)
self.assertEqual(set(qc.parameters), {x})

def test_has_parameter(self):
"""Test the `has_parameter` method."""
x = Parameter("x")
Expand Down
Loading