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 random two-qubit
  unitary.
docstr_tok: ["Tests","that","the","QPE","circuit","can","correctly","estimate","the","phase","of","a","random","two-qubit","unitary","."]
code: def test_phase_estimated_two_qubit(self):
      """Tests that the QPE circuit can correctly estimate the phase of a random two-qubit
      unitary."""
      # pylint: disable=cell-var-from-loop
  
      unitary = unitary_group.rvs(4, random_state=1967)
      eigvals, eigvecs = np.linalg.eig(unitary)
  
      state = eigvecs[:, 0]
      eigval = eigvals[0]
      phase = np.real_if_close(np.log(eigval) / (2 * np.pi * 1j))
  
      estimates = []
      wire_range = range(3, 11)
  
      for wires in wire_range:
          dev = qml.device("default.qubit", wires=wires)
  
          target_wires = [0, 1]
          estimation_wires = range(2, wires)
  
          with qml.queuing.AnnotatedQueue() as q:
              # We want to prepare an eigenstate of RX, in this case |+>
              qml.StatePrep(state, wires=target_wires)
  
              qml.QuantumPhaseEstimation(
                  unitary,
                  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()
  
          if phase < 0:
              estimate = np.argmax(res) / 2 ** (wires - 2) - 1
          else:
              estimate = np.argmax(res) / 2 ** (wires - 2)
          estimates.append(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 3 for calling the TestDecomposition obj's underlying member method code with example usage: obj.test_phase_estimated_two_qubit() without return types