Пример #1
0
    def test_pauli_error_2q_gate_from_pauli(self):
        """Test two-qubit pauli error as gate qobj from Pauli obj"""
        paulis = [qi.Pauli(s) for s in ['XZ', 'YX', 'ZY']]
        probs = [0.5, 0.3, 0.2]
        actual = pauli_error(zip(paulis, probs))

        expected = QuantumError(
            [(PauliGate("XZ"), 0.5), (PauliGate("YX"), 0.3), (PauliGate("ZY"), 0.2)]
        )
        for i in range(actual.size):
            circ, prob = actual.error_term(i)
            expected_circ, expected_prob = expected.error_term(i)
            self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit")
            self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability")
Пример #2
0
    def to_instruction(self):
        """Convert to Pauli circuit instruction."""
        from math import pi

        pauli, phase = self._to_label(self.z,
                                      self.x,
                                      self._phase[0],
                                      full_group=False,
                                      return_phase=True)
        if len(pauli) == 1:
            gate = {
                "I": IGate(),
                "X": XGate(),
                "Y": YGate(),
                "Z": ZGate()
            }[pauli]
        else:
            gate = PauliGate(pauli)
        if not phase:
            return gate
        # Add global phase
        circuit = QuantumCircuit(self.num_qubits, name=str(self))
        circuit.global_phase = -phase * pi / 2
        circuit.append(gate, range(self.num_qubits))
        return circuit.to_instruction()
Пример #3
0
    def to_circuit(self) -> QuantumCircuit:

        pauli = self.primitive.to_label()[-self.num_qubits:]
        phase = self.primitive.phase

        qc = QuantumCircuit(self.num_qubits)
        if pauli == "I" * self.num_qubits:
            qc.global_phase = -phase * pi / 2
            return qc

        if self.num_qubits == 1:
            gate = {
                "I": IGate(),
                "X": XGate(),
                "Y": YGate(),
                "Z": ZGate()
            }[pauli]
        else:
            gate = PauliGate(pauli)
        qc.append(gate, range(self.num_qubits))

        if not phase:
            return qc

        qc.global_phase = -phase * pi / 2
        return qc
Пример #4
0
    def test_from_dict(self):
        noise_ops_1q = [((IGate(), [0]), 0.9),
                     ((XGate(), [0]), 0.1)]

        noise_ops_2q = [((PauliGate('II'), [0, 1]), 0.9),
                     ((PauliGate('IX'), [0, 1]), 0.045),
                     ((PauliGate('XI'), [0, 1]), 0.045),
                     ((PauliGate('XX'), [0, 1]), 0.01)]

        noise_model = NoiseModel()
        with self.assertWarns(DeprecationWarning):
            noise_model.add_quantum_error(QuantumError(noise_ops_1q, 1), 'h', [0])
            noise_model.add_quantum_error(QuantumError(noise_ops_1q, 1), 'h', [1])
            noise_model.add_quantum_error(QuantumError(noise_ops_2q, 2), 'cx', [0, 1])
            noise_model.add_quantum_error(QuantumError(noise_ops_2q, 2), 'cx', [1, 0])
            deserialized = NoiseModel.from_dict(noise_model.to_dict())
            self.assertEqual(noise_model, deserialized)
 def test_init_pauli_gate(self, label):
     """Test initialization from Pauli basis gates"""
     pauli = Pauli(PauliGate(label))
     self.assertEqual(str(pauli), label)
Пример #6
0
    def _to_circuit(cls, op):
        if isinstance(op, QuantumCircuit):
            return op
        if isinstance(op, tuple):
            inst, qubits = op
            circ = QuantumCircuit(max(qubits) + 1)
            circ.append(inst, qargs=qubits)
            return circ
        if isinstance(op, Instruction):
            if op.num_clbits > 0:
                raise NoiseError(
                    f"Unable to convert instruction with clbits: {op.__class__.__name__}"
                )
            circ = QuantumCircuit(op.num_qubits)
            circ.append(op, qargs=list(range(op.num_qubits)))
            return circ
        if isinstance(op, QuantumChannel):
            if not op.is_cptp(atol=cls.atol):
                raise NoiseError("Input quantum channel is not CPTP.")
            try:
                return cls._to_circuit(Kraus(op).to_instruction())
            except QiskitError as err:
                raise NoiseError(
                    f"Fail to convert {op.__class__.__name__} to Instruction."
                ) from err
        if isinstance(op, BaseOperator):
            if hasattr(op, 'to_instruction'):
                try:
                    return cls._to_circuit(op.to_instruction())
                except QiskitError as err:
                    raise NoiseError(
                        f"Fail to convert {op.__class__.__name__} to Instruction."
                    ) from err
            else:
                raise NoiseError(
                    f"Unacceptable Operator, not implementing to_instruction: "
                    f"{op.__class__.__name__}")
        if isinstance(op, list):
            if all(isinstance(aop, tuple) for aop in op):
                num_qubits = max([max(qubits) for _, qubits in op]) + 1
                circ = QuantumCircuit(num_qubits)
                for inst, qubits in op:
                    try:
                        circ.append(inst, qargs=qubits)
                    except CircuitError as err:
                        raise NoiseError(
                            f"Invalid operation type: {inst.__class__.__name__},"
                            f" not appendable to circuit.") from err
                return circ
            # Support for old-style json-like input TODO: to be removed
            elif all(isinstance(aop, dict) for aop in op):
                warnings.warn(
                    'Constructing QuantumError with list of dict representing a mixed channel'
                    ' has been deprecated as of qiskit-aer 0.10.0 and will be removed'
                    ' no earlier than 3 months from that release date.',
                    DeprecationWarning,
                    stacklevel=3)
                # Convert json-like to non-kraus Instruction
                num_qubits = max([max(dic['qubits']) for dic in op]) + 1
                circ = QuantumCircuit(num_qubits)
                for dic in op:
                    if dic['name'] == 'reset':
                        # pylint: disable=import-outside-toplevel
                        from qiskit.circuit import Reset
                        circ.append(Reset(), qargs=dic['qubits'])
                    elif dic['name'] == 'kraus':
                        circ.append(Instruction(name='kraus',
                                                num_qubits=len(dic['qubits']),
                                                num_clbits=0,
                                                params=dic['params']),
                                    qargs=dic['qubits'])
                    elif dic['name'] == 'unitary':
                        circ.append(UnitaryGate(data=dic['params'][0]),
                                    qargs=dic['qubits'])
                    elif dic['name'] == 'pauli':
                        circ.append(PauliGate(dic['params'][0]),
                                    qargs=dic['qubits'])
                    else:
                        with warnings.catch_warnings():
                            warnings.filterwarnings(
                                "ignore",
                                category=DeprecationWarning,
                                module=
                                "qiskit.providers.aer.noise.errors.errorutils")
                            circ.append(UnitaryGate(label=dic['name'],
                                                    data=standard_gate_unitary(
                                                        dic['name'])),
                                        qargs=dic['qubits'])
                return circ
            else:
                raise NoiseError(f"Invalid type of op list: {op}")

        raise NoiseError(
            f"Invalid noise op type {op.__class__.__name__}: {op}")
Пример #7
0
    def test_depolarizing_error_2q_gate(self):
        """Test 2-qubit depolarizing error as gate qobj"""
        p_depol = 0.3
        actual = depolarizing_error(p_depol, 2)

        expected = QuantumError([
            (PauliGate("II"), 1 - p_depol * 15 / 16),
            (PauliGate("IX"), p_depol / 16),
            (PauliGate("IY"), p_depol / 16),
            (PauliGate("IZ"), p_depol / 16),
            (PauliGate("XI"), p_depol / 16),
            (PauliGate("XX"), p_depol / 16),
            (PauliGate("XY"), p_depol / 16),
            (PauliGate("XZ"), p_depol / 16),
            (PauliGate("YI"), p_depol / 16),
            (PauliGate("YX"), p_depol / 16),
            (PauliGate("YY"), p_depol / 16),
            (PauliGate("YZ"), p_depol / 16),
            (PauliGate("ZI"), p_depol / 16),
            (PauliGate("ZX"), p_depol / 16),
            (PauliGate("ZY"), p_depol / 16),
            (PauliGate("ZZ"), p_depol / 16),
        ])
        for i in range(actual.size):
            circ, prob = actual.error_term(i)
            expected_circ, expected_prob = expected.error_term(i)
            self.assertEqual(circ, expected_circ, msg=f"Incorrect {i}-th circuit")
            self.assertAlmostEqual(prob, expected_prob, msg=f"Incorrect {i}-th probability")