Skip to content

Commit

Permalink
Invalidate QuantumCircuit.parameters cache on global-phase modifica…
Browse files Browse the repository at this point in the history
…tion

Previously, replacing a parametric `global_phase` with a non-parametric
global phase would modify the `ParameterTable` without invalidating the
`parameters` cache that the circuit kept.
  • Loading branch information
jakelishman committed Jan 25, 2024
1 parent 1c20b84 commit 0e49d7b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
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

0 comments on commit 0e49d7b

Please sign in to comment.