Ejemplo n.º 1
0
    def z_dag(node, state, ctrl_qubits):
        new_dag = DAGCircuit()
        reg = QuantumRegister(len(node.qargs))
        new_dag.add_qreg(reg)

        new_qarg = []
        for qarg in node.qargs:
            new_qarg.append(reg[node.qargs.index(qarg)])

        new_ctrl_qubits = []
        for qarg in ctrl_qubits:
            new_ctrl_qubits.append(reg[node.qargs.index(qarg)])

        if len(state) == 1:
            op = ZGate()
            new_dag.apply_operation_back(op, new_ctrl_qubits)
        else:
            # With multiple places to put the Z gate in, choose the one with
            # the closed control, if possible.
            try:
                z_index = state.index('1')
            except ValueError:
                # It was not possible  so the open control is replaced by x-z-x
                raise Exception('TODO')
            else:
                # there is a closed controlled where to put the gate.
                state = state[0:z_index:] + state[z_index + 1::]
                op = ZGate().control(len(state), ctrl_state=state)
                z_qubit = new_ctrl_qubits[z_index]
                del new_ctrl_qubits[z_index]
                new_dag.apply_operation_back(op, new_ctrl_qubits + [z_qubit])
        return new_dag
Ejemplo n.º 2
0
    def from_label(cls, label):
        """Return a tensor product of single-qubit operators.

        Args:
            label (string): single-qubit operator string.

        Returns:
            Operator: The N-qubit operator.

        Raises:
            QiskitError: if the label contains invalid characters, or the
                         length of the label is larger than an explicitly
                         specified num_qubits.

        Additional Information:
            The labels correspond to the single-qubit matrices:
            'I': [[1, 0], [0, 1]]
            'X': [[0, 1], [1, 0]]
            'Y': [[0, -1j], [1j, 0]]
            'Z': [[1, 0], [0, -1]]
            'H': [[1, 1], [1, -1]] / sqrt(2)
            'S': [[1, 0], [0 , 1j]]
            'T': [[1, 0], [0, (1+1j) / sqrt(2)]]
            '0': [[1, 0], [0, 0]]
            '1': [[0, 0], [0, 1]]
            '+': [[0.5, 0.5], [0.5 , 0.5]]
            '-': [[0.5, -0.5], [-0.5 , 0.5]]
            'r': [[0.5, -0.5j], [0.5j , 0.5]]
            'l': [[0.5, 0.5j], [-0.5j , 0.5]]
        """
        # Check label is valid
        label_mats = {
            'I': IGate().to_matrix(),
            'X': XGate().to_matrix(),
            'Y': YGate().to_matrix(),
            'Z': ZGate().to_matrix(),
            'H': HGate().to_matrix(),
            'S': SGate().to_matrix(),
            'T': TGate().to_matrix(),
            '0': np.array([[1, 0], [0, 0]], dtype=complex),
            '1': np.array([[0, 0], [0, 1]], dtype=complex),
            '+': np.array([[0.5, 0.5], [0.5, 0.5]], dtype=complex),
            '-': np.array([[0.5, -0.5], [-0.5, 0.5]], dtype=complex),
            'r': np.array([[0.5, -0.5j], [0.5j, 0.5]], dtype=complex),
            'l': np.array([[0.5, 0.5j], [-0.5j, 0.5]], dtype=complex),
        }
        if re.match(r'^[IXYZHST01rl\-+]+$', label) is None:
            raise QiskitError('Label contains invalid characters.')
        # Initialize an identity matrix and apply each gate
        num_qubits = len(label)
        op = Operator(np.eye(2**num_qubits, dtype=complex))
        for qubit, char in enumerate(reversed(label)):
            if char != 'I':
                op = op.compose(label_mats[char], qargs=[qubit])
        return op
Ejemplo n.º 3
0
 def test_from_label(self):
     """Test from_label method"""
     label = 'IXYZHS'
     CI = Clifford(IGate())
     CX = Clifford(XGate())
     CY = Clifford(YGate())
     CZ = Clifford(ZGate())
     CH = Clifford(HGate())
     CS = Clifford(SGate())
     target = CI.tensor(CX).tensor(CY).tensor(CZ).tensor(CH).tensor(CS)
     self.assertEqual(Clifford.from_label(label), target)
Ejemplo n.º 4
0
 def to_instruction(self):
     """Convert to Pauli circuit instruction."""
     from qiskit.circuit import QuantumCircuit, QuantumRegister
     from qiskit.extensions.standard import IdGate, XGate, YGate, ZGate
     gates = {'I': IdGate(), 'X': XGate(), 'Y': YGate(), 'Z': ZGate()}
     label = self.to_label()
     n_qubits = self.numberofqubits
     qreg = QuantumRegister(n_qubits)
     circuit = QuantumCircuit(qreg, name='Pauli:{}'.format(label))
     for i, pauli in enumerate(reversed(label)):
         circuit.append(gates[pauli], [qreg[i]])
     return circuit.to_instruction()
Ejemplo n.º 5
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)), (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)
Ejemplo n.º 6
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
Ejemplo n.º 7
0
 def test_controlled_z(self):
     """Test creation of controlled z gate"""
     self.assertEqual(ZGate().control(), CzGate())