def test_gate_inverse_phase_gate(self):
     """Test that an inverse pair of a PhaseGate can be cancelled."""
     qc = QuantumCircuit(2, 2)
     qc.p(np.pi / 4, 0)
     qc.p(-np.pi / 4, 0)
     pass_ = InverseCancellation([(PhaseGate(np.pi / 4), PhaseGate(-np.pi / 4))])
     pm = PassManager(pass_)
     new_circ = pm.run(qc)
     gates_after = new_circ.count_ops()
     self.assertNotIn("p", gates_after)
Пример #2
0
 def test_four_alternating_inverse_gates(self):
     """Test that inverse cancellation works correctly for alternating sequences
     of inverse gates of even-length."""
     qc = QuantumCircuit(2, 2)
     qc.p(np.pi / 4, 0)
     qc.p(-np.pi / 4, 0)
     qc.p(np.pi / 4, 0)
     qc.p(-np.pi / 4, 0)
     pass_ = InverseCancellation([(PhaseGate(np.pi / 4),
                                   PhaseGate(-np.pi / 4))])
     pm = PassManager(pass_)
     new_circ = pm.run(qc)
     gates_after = new_circ.count_ops()
     self.assertNotIn("p", gates_after)
Пример #3
0
 def test_sequence_of_inverse_gates_1(self):
     """Test that inverse cancellation works correctly for more general sequences
     of inverse gates. In this test two pairs of inverse gates are supposed to
     cancel out."""
     qc = QuantumCircuit(2, 2)
     qc.p(np.pi / 4, 0)
     qc.p(-np.pi / 4, 0)
     qc.p(-np.pi / 4, 0)
     qc.p(np.pi / 4, 0)
     qc.p(np.pi / 4, 0)
     pass_ = InverseCancellation([(PhaseGate(np.pi / 4),
                                   PhaseGate(-np.pi / 4))])
     pm = PassManager(pass_)
     new_circ = pm.run(qc)
     gates_after = new_circ.count_ops()
     self.assertIn("p", gates_after)
     self.assertEqual(gates_after["p"], 1)
    def test_ignores_conditional_rotations_phase_gates(self):
        """Conditional rotations should not be considered in the chain.

        qr0:--[U1]-[U1]-[U1]-[U1]-    qr0:--[U1]-[U1]-
               ||   ||                       ||   ||
        cr0:===.================== == cr0:===.====.===
                    ||                            ||
        cr1:========.=============    cr1:========.===
        """
        qr = QuantumRegister(1, "qr")
        cr = ClassicalRegister(2, "cr")
        circuit = QuantumCircuit(qr, cr)
        circuit.append(PhaseGate(0.1), [qr]).c_if(cr, 1)
        circuit.append(PhaseGate(0.2), [qr]).c_if(cr, 3)
        circuit.append(PhaseGate(0.3), [qr])
        circuit.append(PhaseGate(0.4), [qr])
        dag = circuit_to_dag(circuit)

        expected = QuantumCircuit(qr, cr)
        expected.append(PhaseGate(0.1), [qr]).c_if(cr, 1)
        expected.append(PhaseGate(0.2), [qr]).c_if(cr, 3)
        expected.append(PhaseGate(0.7), [qr])

        pass_ = Optimize1qGates(["p", "u2", "u", "cx", "id"])
        after = pass_.run(dag)

        self.assertEqual(circuit_to_dag(expected), after)
Пример #5
0
 def test_sequence_of_inverse_gates_2(self):
     """Test that inverse cancellation works correctly for more general sequences
     of inverse gates. In this test, in theory three pairs of inverse gates can
     cancel out, but in practice only two pairs are back-to-back."""
     qc = QuantumCircuit(2, 2)
     qc.p(np.pi / 4, 0)
     qc.p(np.pi / 4, 0)
     qc.p(-np.pi / 4, 0)
     qc.p(-np.pi / 4, 0)
     qc.p(-np.pi / 4, 0)
     qc.p(np.pi / 4, 0)
     qc.p(np.pi / 4, 0)
     pass_ = InverseCancellation([(PhaseGate(np.pi / 4),
                                   PhaseGate(-np.pi / 4))])
     pm = PassManager(pass_)
     new_circ = pm.run(qc)
     gates_after = new_circ.count_ops()
     self.assertIn("p", gates_after)
     self.assertEqual(gates_after["p"] % 2, 1)
    def test_in_the_back_phase_gate(self):
        """Optimizations can be in the back of the circuit.
        See https://github.com/Qiskit/qiskit-terra/issues/2004.

        qr0:--[U1]-[U1]-[H]--    qr0:--[U1]-[H]--
        """
        qr = QuantumRegister(1, "qr")
        circuit = QuantumCircuit(qr)
        circuit.append(PhaseGate(0.3), [qr])
        circuit.append(PhaseGate(0.4), [qr])
        circuit.h(qr)
        dag = circuit_to_dag(circuit)

        expected = QuantumCircuit(qr)
        expected.append(PhaseGate(0.7), [qr])
        expected.h(qr)

        pass_ = Optimize1qGates(["p", "u2", "u", "cx", "id"])
        after = pass_.run(dag)

        self.assertEqual(circuit_to_dag(expected), after)
    def test_optimize_1q_gates_collapse_identity_equivalent_phase_gate(self):
        """test optimize_1q_gates removes u1(2*pi) rotations.

        See: https://github.com/Qiskit/qiskit-terra/issues/159
        """
        qr = QuantumRegister(2, "qr")
        cr = ClassicalRegister(2, "cr")
        qc = QuantumCircuit(qr, cr)
        qc.h(qr[0])
        qc.cx(qr[1], qr[0])
        qc.append(PhaseGate(2 * np.pi), [qr[0]])
        qc.cx(qr[1], qr[0])
        qc.append(PhaseGate(np.pi / 2), [qr[0]])  # these three should combine
        qc.append(PhaseGate(np.pi), [qr[0]])  # to identity then
        qc.append(PhaseGate(np.pi / 2), [qr[0]])  # optimized away.
        qc.cx(qr[1], qr[0])
        qc.append(PhaseGate(np.pi), [qr[1]])
        qc.append(PhaseGate(np.pi), [qr[1]])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])

        dag = circuit_to_dag(qc)
        simplified_dag = Optimize1qGates(["p", "u2", "u", "cx", "id"]).run(dag)

        num_u1_gates_remaining = len(simplified_dag.named_nodes("p"))
        self.assertEqual(num_u1_gates_remaining, 0)
    def test_optimize_u_basis_phase_gate(self):
        """U(0, 0, pi/4) ->  p(pi/4). Basis [p]."""
        qr = QuantumRegister(2, "qr")
        circuit = QuantumCircuit(qr)
        circuit.append(UGate(0, 0, np.pi / 4), [qr[0]])

        expected = QuantumCircuit(qr)
        expected.append(PhaseGate(np.pi / 4), [qr[0]])

        passmanager = PassManager()
        passmanager.append(Optimize1qGates(["p"]))
        result = passmanager.run(circuit)

        self.assertEqual(expected, result)
    def test_optimize_u3_to_phase_round(self):
        """U3(1e-16, 1e-16, pi/4) ->  U1(pi/4)"""
        qr = QuantumRegister(1, "qr")
        circuit = QuantumCircuit(qr)
        circuit.append(U3Gate(1e-16, 1e-16, np.pi / 4), [qr[0]])

        expected = QuantumCircuit(qr)
        expected.append(PhaseGate(np.pi / 4), [qr[0]])

        passmanager = PassManager()
        passmanager.append(Optimize1qGates(["p", "u2", "u", "cx", "id"]))
        result = passmanager.run(circuit)

        self.assertEqual(expected, result)
    def test_optimize_u3_to_phase_gate(self):
        """U3(0, 0, pi/4) ->  U1(pi/4)"""
        qr = QuantumRegister(1, 'qr')
        circuit = QuantumCircuit(qr)
        circuit.append(U3Gate(0, 0, np.pi / 4), [qr[0]])

        expected = QuantumCircuit(qr)
        expected.append(PhaseGate(np.pi / 4), [qr[0]])

        passmanager = PassManager()
        passmanager.append(Optimize1qGates(['p', 'u2', 'u', 'cx', 'id']))
        result = passmanager.run(circuit)

        self.assertEqual(expected, result)
Пример #11
0
class TestParameterCtrlState(QiskitTestCase):
    """Test gate equality with ctrl_state parameter."""
    @data((RXGate(0.5), CRXGate(0.5)), (RYGate(0.5), CRYGate(0.5)),
          (RZGate(0.5), CRZGate(0.5)), (XGate(), CXGate()),
          (YGate(), CYGate()), (ZGate(), CZGate()),
          (U1Gate(0.5), CU1Gate(0.5)), (PhaseGate(0.5), CPhaseGate(0.5)),
          (SwapGate(), CSwapGate()), (HGate(), CHGate()),
          (U3Gate(0.1, 0.2, 0.3), CU3Gate(0.1, 0.2, 0.3)),
          (UGate(0.1, 0.2, 0.3), CUGate(0.1, 0.2, 0.3, 0)))
    @unpack
    def test_ctrl_state_one(self, gate, controlled_gate):
        """Test controlled gates with ctrl_state
        See https://github.com/Qiskit/qiskit-terra/pull/4025
        """
        self.assertEqual(gate.control(1, ctrl_state='1'), controlled_gate)
Пример #12
0
 def test_encoder_instruction(self):
     """Test encoding and decoding instructions"""
     subtests = (
         {
             "instruction": CXGate()
         },
         {
             "instruction": PhaseGate(theta=1)
         },
         {
             "instruction": U2Gate(phi=1, lam=1)
         },
         {
             "instruction":
             U2Gate(phi=Parameter("phi"), lam=Parameter("lambda"))
         },
     )
     for obj in subtests:
         encoded = json.dumps(obj, cls=RuntimeEncoder)
         self.assertIsInstance(encoded, str)
         decoded = json.loads(encoded, cls=RuntimeDecoder)
         self.assertEqual(decoded, obj)
Пример #13
0
    def test_optimize_1q_gates_collapse_identity_equivalent_phase_gate(self):
        """test optimize_1q_gates removes u1(2*pi) rotations.

        See: https://github.com/Qiskit/qiskit-terra/issues/159
        """
        #       ┌───┐┌───┐┌───────┐┌───┐┌────────┐┌──────┐┌────────┐┌───┐        ┌─┐»
        # qr_0: ┤ H ├┤ X ├┤ P(2π) ├┤ X ├┤ P(π/2) ├┤ P(π) ├┤ P(π/2) ├┤ X ├────────┤M├»
        #       └───┘└─┬─┘└───────┘└─┬─┘└────────┘└──────┘└────────┘└─┬─┘┌──────┐└╥┘»
        # qr_1: ───────■─────────────■────────────────────────────────■──┤ P(π) ├─╫─»
        #                                                                └──────┘ ║ »
        # cr: 2/══════════════════════════════════════════════════════════════════╩═»
        #                                                                         0 »
        # «
        # «qr_0: ───────────
        # «      ┌──────┐┌─┐
        # «qr_1: ┤ P(π) ├┤M├
        # «      └──────┘└╥┘
        # «cr: 2/═════════╩═
        # «               1
        qr = QuantumRegister(2, "qr")
        cr = ClassicalRegister(2, "cr")
        qc = QuantumCircuit(qr, cr)
        qc.h(qr[0])
        qc.cx(qr[1], qr[0])
        qc.append(PhaseGate(2 * np.pi), [qr[0]])
        qc.cx(qr[1], qr[0])
        qc.append(PhaseGate(np.pi / 2), [qr[0]])  # these three should combine
        qc.append(PhaseGate(np.pi), [qr[0]])  # to identity then
        qc.append(PhaseGate(np.pi / 2), [qr[0]])  # optimized away.
        qc.cx(qr[1], qr[0])
        qc.append(PhaseGate(np.pi), [qr[1]])
        qc.append(PhaseGate(np.pi), [qr[1]])
        qc.measure(qr[0], cr[0])
        qc.measure(qr[1], cr[1])

        dag = circuit_to_dag(qc)
        simplified_dag = Optimize1qGates(["p", "u2", "u", "cx", "id"]).run(dag)

        num_u1_gates_remaining = len(simplified_dag.named_nodes("p"))
        self.assertEqual(num_u1_gates_remaining, 0)
Пример #14
0
 def test_controlled_phase(self):
     """Test the creation of a controlled U1 gate."""
     theta = 0.5
     self.assertEqual(PhaseGate(theta).control(), CPhaseGate(theta))
 def test_double_controlled_phase(self):
     """Test the creation of a controlled phase gate."""
     theta = 0.5
     self.assertEqual(PhaseGate(theta).control(2), MCPhaseGate(theta, 2))