Exemplo n.º 1
0
    def test_slice(self):
        """Verify circuit.data can be sliced."""
        qr = QuantumRegister(2)
        qc = QuantumCircuit(qr)

        qc.h(0)
        qc.cx(0, 1)
        qc.h(1)
        qc.cx(1, 0)
        qc.h(1)
        qc.cx(0, 1)
        qc.h(0)

        h_slice = qc.data[::2]
        cx_slice = qc.data[1:-1:2]

        self.assertEqual(h_slice, [
            (HGate(), [qr[0]], []),
            (HGate(), [qr[1]], []),
            (HGate(), [qr[1]], []),
            (HGate(), [qr[0]], []),
        ])
        self.assertEqual(cx_slice, [
            (CXGate(), [qr[0], qr[1]], []),
            (CXGate(), [qr[1], qr[0]], []),
            (CXGate(), [qr[0], qr[1]], []),
        ])
Exemplo n.º 2
0
    def test_instruction_init(self):
        """Test initialization from a circuit."""
        gate = CXGate()
        op = Operator(gate).data
        target = gate.to_matrix()
        global_phase_equivalent = matrix_equal(op, target, ignore_phase=True)
        self.assertTrue(global_phase_equivalent)

        gate = CHGate()
        op = Operator(gate).data
        had = HGate().to_matrix()
        target = np.kron(had, np.diag([0, 1])) + np.kron(
            np.eye(2), np.diag([1, 0]))
        global_phase_equivalent = matrix_equal(op, target, ignore_phase=True)
        self.assertTrue(global_phase_equivalent)
Exemplo n.º 3
0
    def run(self, dag):
        """Run the CXDirection pass on `dag`.

        Flips the cx nodes to match the directed coupling map. Modifies the
        input dag.

        Args:
            dag (DAGCircuit): DAG to map.

        Returns:
            DAGCircuit: The rearranged dag for the coupling map

        Raises:
            TranspilerError: If the circuit cannot be mapped just by flipping the
                cx nodes.
        """
        cmap_edges = set(self.coupling_map.get_edges())

        if len(dag.qregs) > 1:
            raise TranspilerError(
                'CXDirection expects a single qreg input DAG,'
                'but input DAG had qregs: {}.'.format(dag.qregs))

        for cnot_node in dag.named_nodes('cx', 'CX'):
            control = cnot_node.qargs[0]
            target = cnot_node.qargs[1]

            physical_q0 = control.index
            physical_q1 = target.index

            if self.coupling_map.distance(physical_q0, physical_q1) != 1:
                raise TranspilerError(
                    'The circuit requires a connection between physical '
                    'qubits %s and %s' % (physical_q0, physical_q1))

            if (physical_q0, physical_q1) not in cmap_edges:
                # A flip needs to be done

                # Create the replacement dag and associated register.
                sub_dag = DAGCircuit()
                sub_qr = QuantumRegister(2)
                sub_dag.add_qreg(sub_qr)

                # Add H gates before
                sub_dag.apply_operation_back(U2Gate(0, pi), [sub_qr[0]], [])
                sub_dag.apply_operation_back(U2Gate(0, pi), [sub_qr[1]], [])

                # Flips the cx
                sub_dag.apply_operation_back(CXGate(), [sub_qr[1], sub_qr[0]],
                                             [])

                # Add H gates after
                sub_dag.apply_operation_back(U2Gate(0, pi), [sub_qr[0]], [])
                sub_dag.apply_operation_back(U2Gate(0, pi), [sub_qr[1]], [])

                dag.substitute_node_with_dag(cnot_node, sub_dag)

        return dag
Exemplo n.º 4
0
 def test_circuit_append(self):
     """Test appending a controlled gate to a quantum circuit."""
     circ = QuantumCircuit(5)
     inst = CXGate()
     circ.append(inst.control(), qargs=[0, 2, 1])
     circ.append(inst.control(2), qargs=[0, 3, 1, 2])
     circ.append(inst.control().control(), qargs=[0, 3, 1, 2])  # should be same as above
     self.assertEqual(circ[1][0], circ[2][0])
     self.assertEqual(circ.depth(), 3)
     self.assertEqual(circ[0][0].num_ctrl_qubits, 2)
     self.assertEqual(circ[1][0].num_ctrl_qubits, 3)
     self.assertEqual(circ[2][0].num_ctrl_qubits, 3)
     self.assertEqual(circ[0][0].num_qubits, 3)
     self.assertEqual(circ[1][0].num_qubits, 4)
     self.assertEqual(circ[2][0].num_qubits, 4)
     for instr in circ:
         gate = instr[0]
         self.assertTrue(isinstance(gate, ControlledGate))
Exemplo n.º 5
0
 def test_cnot_rxx_decompose(self):
     """Verify CNOT decomposition into RXX gate is correct"""
     cnot = Operator(CXGate())
     decomps = [cnot_rxx_decompose(),
                cnot_rxx_decompose(plus_ry=True, plus_rxx=True),
                cnot_rxx_decompose(plus_ry=True, plus_rxx=False),
                cnot_rxx_decompose(plus_ry=False, plus_rxx=True),
                cnot_rxx_decompose(plus_ry=False, plus_rxx=False)]
     for decomp in decomps:
         self.assertTrue(cnot.equiv(decomp))
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)), (SwapGate(), CSwapGate()),
          (HGate(), CHGate()), (U3Gate(0.1, 0.2, 0.3), CU3Gate(0.1, 0.2, 0.3)))
    @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)
Exemplo n.º 7
0
    def test_index_gates(self):
        """Verify finding the index of a inst/qarg/carg tuple in circuit.data."""
        qr = QuantumRegister(2)
        qc = QuantumCircuit(qr)

        qc.h(0)
        qc.cx(0, 1)
        qc.h(1)
        qc.h(0)

        self.assertEqual(qc.data.index((HGate(), [qr[0]], [])), 0)
        self.assertEqual(qc.data.index((CXGate(), [qr[0], qr[1]], [])), 1)
        self.assertEqual(qc.data.index((HGate(), [qr[1]], [])), 2)
Exemplo n.º 8
0
    def test_getitem_by_insertion_order(self):
        """Verify one can get circuit.data items in insertion order."""
        qr = QuantumRegister(2)
        qc = QuantumCircuit(qr)
        qc.h(0)
        qc.cx(0, 1)
        qc.h(1)

        data = qc.data

        self.assertEqual(data[0], (HGate(), [qr[0]], []))
        self.assertEqual(data[1], (CXGate(), [qr[0], qr[1]], []))
        self.assertEqual(data[2], (HGate(), [qr[1]], []))
Exemplo n.º 9
0
    def test_iter(self):
        """Verify circuit.data can behave as an iterator."""
        qr = QuantumRegister(2)
        qc = QuantumCircuit(qr)

        qc.h(0)
        qc.cx(0, 1)
        qc.h(1)

        iter_ = iter(qc.data)
        self.assertEqual(next(iter_), (HGate(), [qr[0]], []))
        self.assertEqual(next(iter_), (CXGate(), [qr[0], qr[1]], []))
        self.assertEqual(next(iter_), (HGate(), [qr[1]], []))
        self.assertRaises(StopIteration, next, iter_)
Exemplo n.º 10
0
def random_clifford_circuit(num_qubits, num_gates, gates='all', seed=None):
    """Generate a pseudo random Clifford circuit."""

    if gates == 'all':
        if num_qubits == 1:
            gates = ['i', 'x', 'y', 'z', 'h', 's', 'sdg', 'v', 'w']
        else:
            gates = [
                'i', 'x', 'y', 'z', 'h', 's', 'sdg', 'v', 'w', 'cx', 'cz',
                'swap'
            ]

    instructions = {
        'i': (IGate(), 1),
        'x': (XGate(), 1),
        'y': (YGate(), 1),
        'z': (ZGate(), 1),
        'h': (HGate(), 1),
        's': (SGate(), 1),
        'sdg': (SdgGate(), 1),
        'v': (VGate(), 1),
        'w': (WGate(), 1),
        'cx': (CXGate(), 2),
        'cz': (CZGate(), 2),
        'swap': (SwapGate(), 2)
    }

    if isinstance(seed, np.random.RandomState):
        rng = seed
    else:
        rng = np.random.RandomState(seed=seed)

    samples = rng.choice(gates, num_gates)

    circ = QuantumCircuit(num_qubits)

    for name in samples:
        gate, nqargs = instructions[name]
        qargs = rng.choice(range(num_qubits), nqargs, replace=False).tolist()
        circ.append(gate, qargs)

    return circ
Exemplo n.º 11
0
    def test_setting_data_is_validated(self):
        """Verify setting circuit.data is broadcast and validated."""
        qr = QuantumRegister(2)
        qc = QuantumCircuit(qr)

        qc.data = [(HGate(), [qr[0]], []), (CXGate(), [0, 1], []),
                   (HGate(), [qr[1]], [])]

        expected_qc = QuantumCircuit(qr)

        expected_qc.h(0)
        expected_qc.cx(0, 1)
        expected_qc.h(1)

        self.assertEqual(qc, expected_qc)

        with self.assertRaises(CircuitError):
            qc.data = [(HGate(), [qr[0], qr[1]], [])]
        with self.assertRaises(CircuitError):
            qc.data = [(HGate(), [], [qr[0]])]
Exemplo n.º 12
0
    def test_extend_is_validated(self):
        """Verify extending circuit.data is broadcast and validated."""
        qr = QuantumRegister(2)
        qc = QuantumCircuit(qr)

        qc.data.extend([(HGate(), [qr[0]], []), (CXGate(), [0, 1], []),
                        (HGate(), [qr[1]], [])])

        expected_qc = QuantumCircuit(qr)

        expected_qc.h(0)
        expected_qc.cx(0, 1)
        expected_qc.h(1)

        self.assertEqual(qc, expected_qc)

        self.assertRaises(CircuitError, qc.data.extend,
                          [(HGate(), [qr[0], qr[1]], [])])
        self.assertRaises(CircuitError, qc.data.extend,
                          [(HGate(), [], [qr[0]])])
Exemplo n.º 13
0
    def test_append_is_validated(self):
        """Verify appended gates via circuit.data are broadcast and validated."""
        qr = QuantumRegister(2)
        qc = QuantumCircuit(qr)

        qc.data.append((HGate(), [qr[0]], []))
        qc.data.append((CXGate(), [0, 1], []))
        qc.data.append((HGate(), [qr[1]], []))

        expected_qc = QuantumCircuit(qr)

        expected_qc.h(0)
        expected_qc.cx(0, 1)
        expected_qc.h(1)

        self.assertEqual(qc, expected_qc)

        self.assertRaises(CircuitError, qc.data.append,
                          (HGate(), [qr[0], qr[1]], []))
        self.assertRaises(CircuitError, qc.data.append, (HGate(), [], [qr[0]]))
Exemplo n.º 14
0
 def test_controlled_cx(self):
     """Test creation of controlled cx gate"""
     self.assertEqual(CXGate().control(), CCXGate())