class_docstr: Tests that the template defines the correct decomposition.
class_docstr_tok: ["Tests","that","the","template","defines","the","correct","decomposition","."]
docstr: Tests that the QPE circuit can correctly estimate the phase of a simple RX rotation.
docstr_tok: ["Tests","that","the","QPE","circuit","can","correctly","estimate","the","phase","of","a","simple","RX","rotation","."]
code: def test_phase_estimated(self, phase):
      """Tests that the QPE circuit can correctly estimate the phase of a simple RX rotation."""
      # pylint: disable=cell-var-from-loop
      estimates = []
      wire_range = range(2, 10)
  
      for wires in wire_range:
          dev = qml.device("default.qubit", wires=wires)
          m = qml.RX(phase, wires=0).matrix()
          target_wires = [0]
          estimation_wires = range(1, wires)
  
          with qml.queuing.AnnotatedQueue() as q:
              # We want to prepare an eigenstate of RX, in this case |+>
              qml.Hadamard(wires=target_wires)
  
              qml.QuantumPhaseEstimation(
                  m,
                  target_wires=target_wires,
                  estimation_wires=estimation_wires,
              )
              qml.probs(estimation_wires)
  
          tape = qml.tape.QuantumScript.from_queue(q)
          tapes, _ = dev.preprocess()[0]([tape])
          assert len(tapes) == 1
  
          res = dev.execute(tapes)[0].flatten()
          initial_estimate = np.argmax(res) / 2 ** (wires - 1)
  
          # We need to rescale because RX is exp(- i theta X / 2) and we expect a unitary of the
          # form exp(2 pi i theta X)
          rescaled_estimate = (1 - initial_estimate) * np.pi * 4
          estimates.append(rescaled_estimate)
  
      # Check that the error is monotonically decreasing
      for i in range(len(estimates) - 1):
          err1 = np.abs(estimates[i] - phase)
          err2 = np.abs(estimates[i + 1] - phase)
          assert err1 >= err2
  
      # This is quite a large error, but we'd need to push the qubit number up more to get it
      # lower
      assert np.allclose(estimates[-1], phase, rtol=1e-2)
  
file_path: pennylane/tests/templates/test_subroutines/test_qpe.py
imports: import pytest
  import numpy
  from scipy.stats import unitary_group
  import pennylane
label_desc: Use image node_id 2 for calling the TestDecomposition obj's underlying member method code with example usage: obj.test_phase_estimated(phase) without return types