コード例 #1
0
 def setUp(self):
     super().setUp()
     self.ops = {
         'X': XGate(),
         'Y': YGate(),
         'Z': ZGate(),
         'H': HGate(),
         'S': SGate()
     }
コード例 #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
コード例 #3
0
    def from_label(label):
        """Return a tensor product of single-qubit Clifford gates.

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

        Returns:
            Clifford: The N-qubit Clifford operator.

        Raises:
            QiskitError: if the label contains invalid characters.

        Additional Information:
            The labels correspond to the single-qubit Cliffords are

            * - Label
              - Stabilizer
              - Destabilizer
            * - ``"I"``
              - +Z
              - +X
            * - ``"X"``
              - -Z
              - +X
            * - ``"Y"``
              - -Z
              - -X
            * - ``"Z"``
              - +Z
              - -X
            * - ``"H"``
              - +X
              - +Z
            * - ``"S"``
              - +Z
              - +Y
        """
        # Check label is valid
        label_gates = {
            'I': IGate(),
            'X': XGate(),
            'Y': YGate(),
            'Z': ZGate(),
            'H': HGate(),
            'S': SGate()
        }
        if re.match(r'^[IXYZHS\-+]+$', label) is None:
            raise QiskitError('Label contains invalid characters.')
        # Initialize an identity matrix and apply each gate
        num_qubits = len(label)
        op = Clifford(np.eye(2 * num_qubits, dtype=np.bool))
        for qubit, char in enumerate(reversed(label)):
            _append_circuit(op, label_gates[char], qargs=[qubit])
        return op
コード例 #4
0
    def test_control_implementation(self):
        """Run a test case for controlling the circuit, which should use ``Gate.control``."""
        qc = QuantumCircuit(3)
        qc.cx(0, 1)
        qc.cry(0.2, 0, 1)
        qc.t(0)
        qc.append(SGate().control(2), [0, 1, 2])
        qc.iswap(2, 0)

        c_qc = qc.control(2, ctrl_state="10")

        cgate = qc.to_gate().control(2, ctrl_state="10")
        ref = QuantumCircuit(*c_qc.qregs)
        ref.append(cgate, ref.qubits)

        self.assertEqual(ref, c_qc)
コード例 #5
0
 def test_decompose_gate_type(self):
     """Test decompose specifying gate type."""
     circuit = QuantumCircuit(1)
     circuit.append(SGate(label="s_gate"), [0])
     decomposed = circuit.decompose(gates_to_decompose=SGate)
     self.assertNotIn("s", decomposed.count_ops())
コード例 #6
0
def modify_subcircuit_instance(subcircuit, init, meas):
    """
    Modify the different init, meas for a given subcircuit
    Returns:
    Modified subcircuit_instance
    List of mutated measurements
    """
    subcircuit_dag = circuit_to_dag(subcircuit)
    subcircuit_instance_dag = copy.deepcopy(subcircuit_dag)
    for i, x in enumerate(init):
        q = subcircuit.qubits[i]
        if x == "zero":
            continue
        elif x == "one":
            subcircuit_instance_dag.apply_operation_front(
                op=XGate(), qargs=[q], cargs=[]
            )
        elif x == "plus":
            subcircuit_instance_dag.apply_operation_front(
                op=HGate(), qargs=[q], cargs=[]
            )
        elif x == "minus":
            subcircuit_instance_dag.apply_operation_front(
                op=HGate(), qargs=[q], cargs=[]
            )
            subcircuit_instance_dag.apply_operation_front(
                op=XGate(), qargs=[q], cargs=[]
            )
        elif x == "plusI":
            subcircuit_instance_dag.apply_operation_front(
                op=SGate(), qargs=[q], cargs=[]
            )
            subcircuit_instance_dag.apply_operation_front(
                op=HGate(), qargs=[q], cargs=[]
            )
        elif x == "minusI":
            subcircuit_instance_dag.apply_operation_front(
                op=SGate(), qargs=[q], cargs=[]
            )
            subcircuit_instance_dag.apply_operation_front(
                op=HGate(), qargs=[q], cargs=[]
            )
            subcircuit_instance_dag.apply_operation_front(
                op=XGate(), qargs=[q], cargs=[]
            )
        else:
            raise Exception("Illegal initialization :", x)
    for i, x in enumerate(meas):
        q = subcircuit.qubits[i]
        if x == "I" or x == "comp":
            continue
        elif x == "X":
            subcircuit_instance_dag.apply_operation_back(
                op=HGate(), qargs=[q], cargs=[]
            )
        elif x == "Y":
            subcircuit_instance_dag.apply_operation_back(
                op=SdgGate(), qargs=[q], cargs=[]
            )
            subcircuit_instance_dag.apply_operation_back(
                op=HGate(), qargs=[q], cargs=[]
            )
        else:
            raise Exception("Illegal measurement basis:", x)
    subcircuit_instance_circuit = dag_to_circuit(subcircuit_instance_dag)
    return subcircuit_instance_circuit
コード例 #7
0
def _standard_gate_instruction(instruction, ignore_phase=True):
    """Temporary function to create Instruction objects from a json string,
    which is necessary for creating a new QuantumError object from deprecated
    json-based input. Note that the type of returned object is different from
    the deprecated standard_gate_instruction.
    TODO: to be removed after deprecation period.

    Args:
        instruction (dict): A qobj instruction.
        ignore_phase (bool): Ignore global phase on unitary matrix in
                             comparison to canonical unitary.

    Returns:
        list: a list of (instructions, qubits) equivalent to in input instruction.
    """
    gate = {
        "id": IGate(),
        "x": XGate(),
        "y": YGate(),
        "z": ZGate(),
        "h": HGate(),
        "s": SGate(),
        "sdg": SdgGate(),
        "t": TGate(),
        "tdg": TdgGate(),
        "cx": CXGate(),
        "cz": CZGate(),
        "swap": SwapGate()
    }

    name = instruction.get("name", None)
    qubits = instruction["qubits"]
    if name in gate:
        return [(gate[name], qubits)]

    if name not in ["mat", "unitary", "kraus"]:
        return [instruction]

    params = instruction["params"]
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore",
                                category=DeprecationWarning,
                                module="qiskit.providers.aer.noise.errors.errorutils")

        # Check for single-qubit reset Kraus
        if name == "kraus":
            if len(qubits) == 1:
                superop = SuperOp(Kraus(params))
                # Check if reset to |0>
                reset0 = reset_superop(1)
                if superop == reset0:
                    return [(Reset(), [0])]
                # Check if reset to |1>
                reset1 = reset0.compose(Operator(standard_gate_unitary('x')))
                if superop == reset1:
                    return [(Reset(), [0]), (XGate(), [0])]
            return [instruction]

        # Check single qubit gates
        mat = params[0]
        if len(qubits) == 1:
            # Check clifford gates
            for j in range(24):
                if matrix_equal(
                        mat,
                        single_qubit_clifford_matrix(j),
                        ignore_phase=ignore_phase):
                    return [(gate, [0]) for gate in _CLIFFORD_GATES[j]]
            # Check t gates
            for name in ["t", "tdg"]:
                if matrix_equal(
                        mat,
                        standard_gate_unitary(name),
                        ignore_phase=ignore_phase):
                    return [(gate[name], qubits)]
            # TODO: u1,u2,u3 decomposition
        # Check two qubit gates
        if len(qubits) == 2:
            for name in ["cx", "cz", "swap"]:
                if matrix_equal(
                        mat,
                        standard_gate_unitary(name),
                        ignore_phase=ignore_phase):
                    return [(gate[name], qubits)]
            # Check reversed CX
            if matrix_equal(
                    mat,
                    standard_gate_unitary("cx_10"),
                    ignore_phase=ignore_phase):
                return [(CXGate(), [qubits[1], qubits[0]])]
            # Check 2-qubit Pauli's
            paulis = ["id", "x", "y", "z"]
            for pauli0 in paulis:
                for pauli1 in paulis:
                    pmat = np.kron(
                        standard_gate_unitary(pauli1),
                        standard_gate_unitary(pauli0))
                    if matrix_equal(mat, pmat, ignore_phase=ignore_phase):
                        if pauli0 == "id":
                            return [(gate[pauli1], [qubits[1]])]
                        elif pauli1 == "id":
                            return [(gate[pauli0], [qubits[0]])]
                        else:
                            return [(gate[pauli0], [qubits[0]]), (gate[pauli1], [qubits[1]])]
        # Check three qubit toffoli
        if len(qubits) == 3:
            if matrix_equal(
                    mat,
                    standard_gate_unitary("ccx_012"),
                    ignore_phase=ignore_phase):
                return [(CCXGate(), qubits)]
            if matrix_equal(
                    mat,
                    standard_gate_unitary("ccx_021"),
                    ignore_phase=ignore_phase):
                return [(CCXGate(), [qubits[0], qubits[2], qubits[1]])]
            if matrix_equal(
                    mat,
                    standard_gate_unitary("ccx_120"),
                    ignore_phase=ignore_phase):
                return [(CCXGate(), [qubits[1], qubits[2], qubits[0]])]

    # Else return input in
    return [instruction]
コード例 #8
0
        ('s', 'h', 'z'),
        ('sdg', 'h', 'z'),
        ('z', 'h', 'z'),
        # u3 gates
        (
            'x', ),
        ('y', ),
        ('s', 'x'),
        ('sdg', 'x')
    ]
    return labels[j]


_CLIFFORD_GATES = [
    (IGate(), ),
    (SGate(), ),
    (SdgGate(), ),
    (ZGate(), ),
    # u2 gates
    (HGate(), ),
    (HGate(), ZGate()),
    (ZGate(), HGate()),
    (HGate(), SGate()),
    (SGate(), HGate()),
    (HGate(), SdgGate()),
    (SdgGate(), HGate()),
    (SGate(), HGate(), SGate()),
    (SdgGate(), HGate(), SGate()),
    (ZGate(), HGate(), SGate()),
    (SGate(), HGate(), SdgGate()),
    (SdgGate(), HGate(), SdgGate()),
コード例 #9
0
def get_one_subcircuit_instances(subcircuit, combinations):
    '''
    Modify the different init, meas for a given subcircuit
    Returns:
    subcircuit_instances[subcircuit_instance_idx] = circuit, init, meas, shots
    subcircuit_instances_idx[init,meas] = subcircuit_instance_idx
    '''
    subcircuit_instances = {}
    subcircuit_instances_idx = {}
    for combination_ctr, combination in enumerate(combinations):
        # print('combination %d/%d :'%(combination_ctr+1,len(combinations)),combination)
        subcircuit_dag = circuit_to_dag(subcircuit)
        inits, meas = combination
        for i, x in enumerate(inits):
            q = subcircuit.qubits[i]
            if x == 'zero':
                continue
            elif x == 'one':
                subcircuit_dag.apply_operation_front(op=XGate(),
                                                     qargs=[q],
                                                     cargs=[])
            elif x == 'plus':
                subcircuit_dag.apply_operation_front(op=HGate(),
                                                     qargs=[q],
                                                     cargs=[])
            elif x == 'minus':
                subcircuit_dag.apply_operation_front(op=HGate(),
                                                     qargs=[q],
                                                     cargs=[])
                subcircuit_dag.apply_operation_front(op=XGate(),
                                                     qargs=[q],
                                                     cargs=[])
            elif x == 'plusI':
                subcircuit_dag.apply_operation_front(op=SGate(),
                                                     qargs=[q],
                                                     cargs=[])
                subcircuit_dag.apply_operation_front(op=HGate(),
                                                     qargs=[q],
                                                     cargs=[])
            elif x == 'minusI':
                subcircuit_dag.apply_operation_front(op=SGate(),
                                                     qargs=[q],
                                                     cargs=[])
                subcircuit_dag.apply_operation_front(op=HGate(),
                                                     qargs=[q],
                                                     cargs=[])
                subcircuit_dag.apply_operation_front(op=XGate(),
                                                     qargs=[q],
                                                     cargs=[])
            else:
                raise Exception('Illegal initialization : ', x)
        for i, x in enumerate(meas):
            q = subcircuit.qubits[i]
            if x == 'I' or x == 'comp':
                continue
            elif x == 'X':
                subcircuit_dag.apply_operation_back(op=HGate(),
                                                    qargs=[q],
                                                    cargs=[])
            elif x == 'Y':
                subcircuit_dag.apply_operation_back(op=SdgGate(),
                                                    qargs=[q],
                                                    cargs=[])
                subcircuit_dag.apply_operation_back(op=HGate(),
                                                    qargs=[q],
                                                    cargs=[])
            else:
                raise Exception('Illegal measurement basis:', x)
        subcircuit_inst = dag_to_circuit(subcircuit_dag)
        num_shots = max(8192, int(2**subcircuit_inst.num_qubits))
        num_shots = min(8192 * 10, num_shots)
        mutated_meas = mutate_measurement_basis(meas)
        for idx, meas in enumerate(mutated_meas):
            subcircuit_instance_idx = len(subcircuit_instances)
            if idx == 0:
                parent_subcircuit_instance_idx = subcircuit_instance_idx
                shots = num_shots
            else:
                shots = 0
            subcircuit_instances[subcircuit_instance_idx] = {
                'circuit': subcircuit_inst,
                'init': tuple(inits),
                'meas': tuple(meas),
                'shots': shots,
                'parent': parent_subcircuit_instance_idx
            }
            subcircuit_instances_idx[(tuple(inits),
                                      tuple(meas))] = subcircuit_instance_idx
    return subcircuit_instances, subcircuit_instances_idx
コード例 #10
0
def get_subcircuit_instance(subcircuit_idx, subcircuit, combinations):
    circ_dict = {}
    for combination_ctr, combination in enumerate(combinations):
        # print('combination %d/%d :'%(combination_ctr,len(combinations)),combination)
        subcircuit_dag = circuit_to_dag(subcircuit)
        inits, meas = combination
        for i, x in enumerate(inits):
            q = subcircuit.qubits[i]
            if x == 'zero':
                continue
            elif x == 'one':
                subcircuit_dag.apply_operation_front(op=XGate(),
                                                     qargs=[q],
                                                     cargs=[])
            elif x == 'plus':
                subcircuit_dag.apply_operation_front(op=HGate(),
                                                     qargs=[q],
                                                     cargs=[])
            elif x == 'minus':
                subcircuit_dag.apply_operation_front(op=HGate(),
                                                     qargs=[q],
                                                     cargs=[])
                subcircuit_dag.apply_operation_front(op=XGate(),
                                                     qargs=[q],
                                                     cargs=[])
            elif x == 'plusI':
                subcircuit_dag.apply_operation_front(op=SGate(),
                                                     qargs=[q],
                                                     cargs=[])
                subcircuit_dag.apply_operation_front(op=HGate(),
                                                     qargs=[q],
                                                     cargs=[])
            elif x == 'minusI':
                subcircuit_dag.apply_operation_front(op=SGate(),
                                                     qargs=[q],
                                                     cargs=[])
                subcircuit_dag.apply_operation_front(op=HGate(),
                                                     qargs=[q],
                                                     cargs=[])
                subcircuit_dag.apply_operation_front(op=XGate(),
                                                     qargs=[q],
                                                     cargs=[])
            else:
                raise Exception('Illegal initialization : ', x)
        for i, x in enumerate(meas):
            q = subcircuit.qubits[i]
            if x == 'I' or x == 'comp':
                continue
            elif x == 'X':
                subcircuit_dag.apply_operation_back(op=HGate(),
                                                    qargs=[q],
                                                    cargs=[])
            elif x == 'Y':
                subcircuit_dag.apply_operation_back(op=SdgGate(),
                                                    qargs=[q],
                                                    cargs=[])
                subcircuit_dag.apply_operation_back(op=HGate(),
                                                    qargs=[q],
                                                    cargs=[])
            else:
                raise Exception('Illegal measurement basis:', x)
        subcircuit_inst = dag_to_circuit(subcircuit_dag)
        # NOTE: Adjust subcircuit shots here
        num_shots = max(8192, int(2**subcircuit_inst.num_qubits))
        num_shots = min(8192 * 10, num_shots)
        circ_dict[(subcircuit_idx, tuple(inits), tuple(meas))] = {
            'circuit': subcircuit_inst,
            'shots': num_shots
        }
    return circ_dict