def test_measurement_error_mitigation(self):
        aqua_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        backend = Aer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend=backend, seed=167, seed_transpiler=167,
                                           noise_model=noise_model)

        quantum_instance_with_mitigation = QuantumInstance(backend=backend, seed=167, seed_transpiler=167,
                                                           noise_model=noise_model,
                                                           measurement_error_mitigation_cls=CompleteMeasFitter)

        input = 'a & b & c'
        oracle = LogicalExpressionOracle(input, optimization='off')
        grover = Grover(oracle)

        result_wo_mitigation = grover.run(quantum_instance)
        prob_top_measurement_wo_mitigation = result_wo_mitigation['measurement'][
            result_wo_mitigation['top_measurement']]

        result_w_mitigation = grover.run(quantum_instance_with_mitigation)
        prob_top_measurement_w_mitigation = result_w_mitigation['measurement'][result_w_mitigation['top_measurement']]

        self.assertGreaterEqual(prob_top_measurement_w_mitigation, prob_top_measurement_wo_mitigation)
    def test_measurement_error_mitigation_auto_refresh(self):
        aqua_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        backend = Aer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend=backend, seed=1679, seed_transpiler=167,
                                           noise_model=noise_model,
                                           measurement_error_mitigation_cls=CompleteMeasFitter,
                                           cals_matrix_refresh_period=0)
        input = 'a & b & c'
        oracle = LogicalExpressionOracle(input, optimization='off')
        grover = Grover(oracle)
        _ = grover.run(quantum_instance)
        cals_matrix_1 = quantum_instance.cals_matrix.copy()

        time.sleep(15)
        aqua_globals.random_seed = 2
        quantum_instance.set_config(seed=111)
        _ = grover.run(quantum_instance)
        cals_matrix_2 = quantum_instance.cals_matrix.copy()

        diff = cals_matrix_1 - cals_matrix_2
        total_diff = np.sum(np.abs(diff))

        self.assertGreater(total_diff, 0.0)
Ejemplo n.º 3
0
    def test_measurement_error_mitigation_qaoa(self):
        """measurement error mitigation test with QAOA"""
        algorithm_globals.random_seed = 167

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],
                                                            [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        backend = Aer.get_backend("aer_simulator")
        quantum_instance = QuantumInstance(
            backend=backend,
            seed_simulator=algorithm_globals.random_seed,
            seed_transpiler=algorithm_globals.random_seed,
            noise_model=noise_model,
            measurement_error_mitigation_cls=CompleteMeasFitter,
        )
        w = rx.adjacency_matrix(
            rx.undirected_gnp_random_graph(5,
                                           0.5,
                                           seed=algorithm_globals.random_seed))
        qubit_op, _ = self._get_operator(w)
        qaoa = QAOA(
            optimizer=COBYLA(maxiter=1),
            quantum_instance=quantum_instance,
            initial_point=np.asarray([0.0, 0.0]),
        )
        result = qaoa.compute_minimum_eigenvalue(operator=qubit_op)
        self.assertAlmostEqual(result.eigenvalue.real, 3.49, delta=0.05)
Ejemplo n.º 4
0
    def _test_kraus_gate_noise_on_QFT(self, **options):
        shots = 10000

        # Build noise model
        error1 = noise.amplitude_damping_error(0.2)
        error2 = error1.tensor(error1)
        noise_model = noise.NoiseModel()
        noise_model.add_all_qubit_quantum_error(error1, ['h'])
        noise_model.add_all_qubit_quantum_error(error2, ['cp', 'swap'])

        backend = self.backend(**options, noise_model=noise_model)
        ideal_circuit = transpile(QFT(3), backend)

        # manaully build noise circuit
        noise_circuit = QuantumCircuit(3)
        for inst, qargs, cargs in ideal_circuit.data:
            noise_circuit.append(inst, qargs, cargs)
            if inst.name == "h":
                noise_circuit.append(error1, qargs)
            elif inst.name in ["cp", "swap"]:
                noise_circuit.append(error2, qargs)
        # compute target counts
        noise_state = DensityMatrix(noise_circuit)
        ref_target = {i: shots * p for i, p in noise_state.probabilities_dict().items()}

        # Run sim
        ideal_circuit.measure_all()
        result = backend.run(ideal_circuit, shots=shots).result()
        self.assertSuccess(result)
        self.compare_counts(result, [ideal_circuit], [ref_target], hex_counts=False, delta=0.1 * shots)
Ejemplo n.º 5
0
    def noise_model_converter(self, nm):
        if nm is None:
            return None
        basis_gates = basis
        qnoise = qiskitnoise.NoiseModel(basis_gates)
        for noise in nm.noises:
            op = self.noise_lookup[noise.name]
            if op is qiskitnoise.depolarizing_error:
                active = op(noise.probs[0], noise.level)
            else:
                if noise.level == 1:
                    active = op(*noise.probs)
                else:
                    active = op(*noise.probs)
                    action = op(*noise.probs)
                    for i in range(noise.level - 1):
                        active = active.tensor(action)

            if noise.level == 2:
                targets = ['cx', 'cy', 'cz', 'crz', 'crx', 'cry', 'cu3', 'ch']

            elif noise.level == 1:
                targets = ['x', 'y', 'z', 'u3', 'u1', 'u2', 'h']

            elif noise.level == 3:
                targets = ['ccx']

            else:
                raise TequilaQiskitException(
                    'Sorry, no support yet for qiskit for noise on more than 3 qubits.'
                )
            qnoise.add_all_qubit_quantum_error(active, targets)

        return qnoise
    def test_measurement_error_mitigation_with_dedicated_shots(self):
        from qiskit import Aer
        from qiskit.providers.aer import noise

        aqua_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        backend = Aer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend=backend, seed_simulator=1679, seed_transpiler=167, shots=100,
                                           noise_model=noise_model,
                                           measurement_error_mitigation_cls=CompleteMeasFitter,
                                           cals_matrix_refresh_period=0)
        input = 'a & b & c'
        oracle = LogicalExpressionOracle(input)
        grover = Grover(oracle)
        _ = grover.run(quantum_instance)
        cals_matrix_1, timestamp_1 = quantum_instance.cals_matrix(qubit_index=[0, 1, 2])

        quantum_instance.measurement_error_mitigation_shots = 1000
        _ = grover.run(quantum_instance)
        cals_matrix_2, timestamp_2 = quantum_instance.cals_matrix(qubit_index=[0, 1, 2])

        diff = cals_matrix_1 - cals_matrix_2
        total_diff = np.sum(np.abs(diff))

        self.assertGreater(total_diff, 0.0)
        self.assertGreater(timestamp_2, timestamp_1)
    def test_measurement_error_mitigation(self):
        try:
            from qiskit import Aer
            from qiskit.providers.aer import noise
        except Exception as e:
            self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(e)))
            return

        aqua_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        backend = Aer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend=backend, seed_simulator=167, seed_transpiler=167,
                                           noise_model=noise_model)

        quantum_instance_with_mitigation = QuantumInstance(backend=backend, seed_simulator=167, seed_transpiler=167,
                                                           noise_model=noise_model,
                                                           measurement_error_mitigation_cls=CompleteMeasFitter)

        input = 'a & b & c'
        oracle = LogicalExpressionOracle(input)
        grover = Grover(oracle)

        result_wo_mitigation = grover.run(quantum_instance)
        prob_top_measurement_wo_mitigation = result_wo_mitigation['measurement'][
            result_wo_mitigation['top_measurement']]

        result_w_mitigation = grover.run(quantum_instance_with_mitigation)
        prob_top_measurement_w_mitigation = result_w_mitigation['measurement'][result_w_mitigation['top_measurement']]

        self.assertGreaterEqual(prob_top_measurement_w_mitigation, prob_top_measurement_wo_mitigation)
Ejemplo n.º 8
0
    def test_save_qiskit_noise_model(self):
        # Given
        noise_model = AerNoise.NoiseModel()
        quantum_error = AerNoise.depolarizing_error(0.0, 1)
        coherent_error = np.asarray([
            np.asarray(
                [0.87758256 - 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j,
                 0.0 + 0.0j]),
            np.asarray(
                [0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j,
                 0.0 + 0.0j]),
            np.asarray(
                [0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 + 0.47942554j,
                 0.0 + 0.0j]),
            np.asarray(
                [0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j,
                 0.87758256 - 0.47942554j]),
        ])
        noise_model.add_quantum_error(
            AerNoise.coherent_unitary_error(coherent_error), ["cx"], [0, 1])
        filename = "noise_model.json"

        # When
        save_qiskit_noise_model(noise_model, filename)

        # Then
        with open("noise_model.json", "r") as f:
            data = json.loads(f.read())
        self.assertEqual(data["module_name"], "qeqiskit.utils")
        self.assertEqual(data["function_name"], "load_qiskit_noise_model")
        self.assertIsInstance(data["data"], dict)

        # Cleanup
        subprocess.run(["rm", "noise_model.json"])
Ejemplo n.º 9
0
def get_noise(prob_1, prob_2, qc):

    # Error probabilities
    #    prob_1 = 0.001  # 1-qubit gate
    #    prob_2 = 0.01   # 2-qubit gate

    # Depolarizing quantum errors
    error_1 = noise.depolarizing_error(prob_1, 1)
    error_2 = noise.depolarizing_error(prob_2, 2)

    # Add errors to noise model
    noise_model = noise.NoiseModel()
    noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3'])
    noise_model.add_all_qubit_quantum_error(error_2, ['cx'])

    # Get basis gates from noise model
    basis_gates = noise_model.basis_gates

    # Make a circuit
    # Perform a noise simulation
    new_result = execute(qc,
                         Aer.get_backend('qasm_simulator'),
                         basis_gates=basis_gates,
                         noise_model=noise_model).result()
    if np.empty_like(new_result) == 0:
        new_counts = new_result.get_counts(0)
        plot_histogram(new_counts)
        return [noise_model, new_counts]
    else:
        return noise_model
Ejemplo n.º 10
0
    def test_measurement_error_mitigation_with_diff_qubit_order_ignis(
            self, fitter_str):
        """measurement error mitigation with different qubit order"""
        algorithm_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],
                                                            [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        fitter_cls = (CompleteMeasFitter_IG if fitter_str
                      == "CompleteMeasFitter" else TensoredMeasFitter_IG)
        backend = Aer.get_backend("aer_simulator")
        quantum_instance = QuantumInstance(
            backend=backend,
            seed_simulator=1679,
            seed_transpiler=167,
            shots=1000,
            noise_model=noise_model,
            measurement_error_mitigation_cls=fitter_cls,
            cals_matrix_refresh_period=0,
        )
        # circuit
        qc1 = QuantumCircuit(2, 2)
        qc1.h(0)
        qc1.cx(0, 1)
        qc1.measure(0, 0)
        qc1.measure(1, 1)
        qc2 = QuantumCircuit(2, 2)
        qc2.h(0)
        qc2.cx(0, 1)
        qc2.measure(1, 0)
        qc2.measure(0, 1)

        if fitter_cls == TensoredMeasFitter_IG:
            with self.assertWarnsRegex(DeprecationWarning, r".*ignis.*"):
                self.assertRaisesRegex(
                    QiskitError,
                    "TensoredMeasFitter doesn't support subset_fitter.",
                    quantum_instance.execute,
                    [qc1, qc2],
                )
        else:
            # this should run smoothly
            with self.assertWarnsRegex(DeprecationWarning, r".*ignis.*"):
                quantum_instance.execute([qc1, qc2])

        self.assertGreater(quantum_instance.time_taken, 0.0)
        quantum_instance.reset_execution_results()

        # failure case
        qc3 = QuantumCircuit(3, 3)
        qc3.h(2)
        qc3.cx(1, 2)
        qc3.measure(2, 1)
        qc3.measure(1, 2)

        self.assertRaises(QiskitError, quantum_instance.execute, [qc1, qc3])
Ejemplo n.º 11
0
 def test_empty_circuit_noise(self, method, device):
     """Test simulation with empty circuit and noise model."""
     backend = self.backend(method=method, device=device)
     noise_model = noise.NoiseModel()
     noise_model.add_all_qubit_quantum_error(noise.depolarizing_error(0.1, 1), ['x'])
     result = backend.run(
         QuantumCircuit(), shots=1, noise_model=noise_model).result()
     self.assertSuccess(result)
Ejemplo n.º 12
0
def none(backend):
    if backend.name() == 'qasm_simulator':
        noise_model = noise.NoiseModel()
    else:
        print('SimulationError: Invalid option for noisy simulator')
        sys.exit()

    return noise_model
Ejemplo n.º 13
0
    def test_measurement_error_mitigation_with_diff_qubit_order(self):
        """measurement error mitigation with different qubit order"""
        try:
            from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
            from qiskit import Aer
            from qiskit.providers.aer import noise
        except ImportError as ex:
            self.skipTest(
                "Package doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return

        algorithm_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],
                                                            [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        backend = Aer.get_backend("aer_simulator")
        quantum_instance = QuantumInstance(
            backend=backend,
            seed_simulator=1679,
            seed_transpiler=167,
            shots=1000,
            noise_model=noise_model,
            measurement_error_mitigation_cls=CompleteMeasFitter,
            cals_matrix_refresh_period=0,
        )
        # circuit
        qc1 = QuantumCircuit(2, 2)
        qc1.h(0)
        qc1.cx(0, 1)
        qc1.measure(0, 0)
        qc1.measure(1, 1)
        qc2 = QuantumCircuit(2, 2)
        qc2.h(0)
        qc2.cx(0, 1)
        qc2.measure(1, 0)
        qc2.measure(0, 1)

        # this should run smoothly
        quantum_instance.execute([qc1, qc2])
        self.assertGreater(quantum_instance.time_taken, 0.0)
        quantum_instance.reset_execution_results()

        # failure case
        qc3 = QuantumCircuit(3, 3)
        qc3.h(2)
        qc3.cx(1, 2)
        qc3.measure(2, 1)
        qc3.measure(1, 2)

        self.assertRaises(QiskitError, quantum_instance.execute, [qc1, qc3])
Ejemplo n.º 14
0
    def run_simulation(self, shots=8192, error_prob=0, target_state='0'):
        # add noise
        error_1 = noise.depolarizing_error(error_prob, 1)
        noise_model = noise.NoiseModel()
        noise_model.add_all_qubit_quantum_error(error_1, ['x', 'z'])

        # run simulation
        self.qc.measure(0, 0)
        emulator = Aer.get_backend('qasm_simulator')
        job = execute(self.qc, emulator, noise_model=noise_model, shots=shots)
        hist = job.result().get_counts()
        print(hist)
Ejemplo n.º 15
0
def noisy_model(prob_one, prob_two):
    # Depolarizing quantum errors
    error_1 = noise.depolarizing_error(prob_one, 1)
    error_2 = noise.depolarizing_error(prob_two, 2)

    # Add errors to noise model
    noise_model = noise.NoiseModel()
    noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2', 'u3'])
    noise_model.add_all_qubit_quantum_error(error_2, ['cx'])
    basis_gates = noise_model.basis_gates

    return (noise_model, basis_gates)
Ejemplo n.º 16
0
    def test_measurement_error_mitigation_with_diff_qubit_order(self):
        """ measurement error mitigation with different qubit order"""
        # pylint: disable=import-outside-toplevel
        try:
            from qiskit import Aer
            from qiskit.providers.aer import noise
        except ImportError as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return

        aqua_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],
                                                            [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        backend = Aer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(
            backend=backend,
            seed_simulator=1679,
            seed_transpiler=167,
            shots=1000,
            noise_model=noise_model,
            measurement_error_mitigation_cls=CompleteMeasFitter,
            cals_matrix_refresh_period=0)
        # circuit
        qc1 = QuantumCircuit(2, 2)
        qc1.h(0)
        qc1.cx(0, 1)
        qc1.measure(0, 0)
        qc1.measure(1, 1)
        qc2 = QuantumCircuit(2, 2)
        qc2.h(0)
        qc2.cx(0, 1)
        qc2.measure(1, 0)
        qc2.measure(0, 1)

        # this should run smoothly
        quantum_instance.execute([qc1, qc2])

        # failure case
        qc3 = QuantumCircuit(3, 3)
        qc3.h(2)
        qc3.cx(1, 2)
        qc3.measure(2, 1)
        qc3.measure(1, 2)

        self.assertRaises(AquaError, quantum_instance.execute, [qc1, qc3])
Ejemplo n.º 17
0
def randbin3(data, F):  # simulator --- WORKS with reversed probabilities
    #error_1 = noise.depolarizing_error(data.phase_err, 1)
    error_1 = noise.phase_amplitude_damping_error(param_phase=data.phase_err,
                                                  param_amp=data.amp_err)
    error_2 = noise.thermal_relaxation_error(data.T_1,
                                             data.T_2,
                                             data.t * 10**(6),
                                             excited_state_population=0)
    noise_model = noise.NoiseModel()
    noise_model.add_all_qubit_quantum_error(error_2, ['rz'])
    basis_gates = noise_model.basis_gates

    phi = data.const * F * data.t * data.F_degree

    q = QuantumRegister(1)
    c = ClassicalRegister(1)

    # Create a Quantum Circuit acting on the q register
    circuit = QuantumCircuit(q, c)

    circuit.h(q)
    circuit.rz(phi, q)
    circuit.h(q)

    # Map the quantum measurement to the classical bits
    circuit.measure(q, c)

    # Execute the circuit on the qasm simulator
    job = execute(circuit,
                  simulator,
                  basis_gates=basis_gates,
                  noise_model=noise_model,
                  shots=data.num_of_repetitions)
    #job_monitor(job)

    # Grab results from the job
    result = job.result()

    # Returns counts
    counts = result.get_counts(circuit)
    #print(counts, 'for sim')

    #return counts

    try:
        if counts['1'] < counts['0']:  # LOWEST BECAUSE PROBS ARE REVERSED!!!
            return 1
        else:
            return 0
    except Exception:
        return abs(int(list(counts.keys())[0]) - 1)
    def test_backend_options_cleaned(self):
        """Test that the backend options are cleared upon new Aer device
        initialization."""
        noise_model = noise.NoiseModel()
        bit_flip = noise.pauli_error([('X', 1), ('I', 0)])

        # Create a noise model where the RX operation always flips the bit
        noise_model.add_all_qubit_quantum_error(bit_flip, ["rx"])

        dev = qml.device('qiskit.aer', wires=2, noise_model=noise_model)
        assert 'noise_model' in dev.backend.options

        dev2 = qml.device('qiskit.aer', wires=2)
        assert 'noise_model' not in dev2.backend.options
    def test_backend_options_cleaned(self):
        """Test that the backend options are cleared upon new Aer device
        initialization."""
        noise_model = noise.NoiseModel()
        bit_flip = noise.pauli_error([("X", 1), ("I", 0)])

        # Create a noise model where the RX operation always flips the bit
        noise_model.add_all_qubit_quantum_error(bit_flip, ["rx"])

        dev = qml.device("qiskit.aer", wires=2, noise_model=noise_model)
        assert dev.backend.options.get("noise_model") is not None

        dev2 = qml.device("qiskit.aer", wires=2)
        assert dev2.backend.options.get("noise_model") is None
Ejemplo n.º 20
0
    def test_measurement_error_mitigation_auto_refresh(self):
        """ measurement error mitigation auto refresh test """
        try:
            # pylint: disable=import-outside-toplevel
            from qiskit import Aer
            from qiskit.providers.aer import noise
        except ImportError as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return

        aqua_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],
                                                            [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        backend = Aer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(
            backend=backend,
            seed_simulator=1679,
            seed_transpiler=167,
            noise_model=noise_model,
            measurement_error_mitigation_cls=CompleteMeasFitter,
            cals_matrix_refresh_period=0)
        oracle = LogicalExpressionOracle('a & b & c')
        grover = Grover(oracle)
        _ = grover.run(quantum_instance)
        self.assertGreater(quantum_instance.time_taken, 0.)
        quantum_instance.reset_execution_results()
        cals_matrix_1, timestamp_1 = quantum_instance.cals_matrix(
            qubit_index=[0, 1, 2])

        time.sleep(15)
        aqua_globals.random_seed = 2
        quantum_instance.set_config(seed_simulator=111)
        _ = grover.run(quantum_instance)
        cals_matrix_2, timestamp_2 = quantum_instance.cals_matrix(
            qubit_index=[0, 1, 2])

        diff = cals_matrix_1 - cals_matrix_2
        total_diff = np.sum(np.abs(diff))

        self.assertGreater(total_diff, 0.0)
        self.assertGreater(timestamp_2, timestamp_1)
Ejemplo n.º 21
0
    def test_measurement_error_mitigation_with_vqe(self):
        """ measurement error mitigation test with vqe """
        try:
            # pylint: disable=import-outside-toplevel
            from qiskit import Aer
            from qiskit.providers.aer import noise
        except ImportError as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return

        aqua_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],
                                                            [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        backend = Aer.get_backend('qasm_simulator')

        quantum_instance = QuantumInstance(
            backend=backend,
            seed_simulator=167,
            seed_transpiler=167,
            noise_model=noise_model,
            measurement_error_mitigation_cls=CompleteMeasFitter)

        h2_hamiltonian = -1.052373245772859 * (I ^ I) \
            + 0.39793742484318045 * (I ^ Z) \
            - 0.39793742484318045 * (Z ^ I) \
            - 0.01128010425623538 * (Z ^ Z) \
            + 0.18093119978423156 * (X ^ X)
        optimizer = SPSA(maxiter=200)
        var_form = EfficientSU2(2, reps=1)

        vqe = VQE(
            var_form=var_form,
            operator=h2_hamiltonian,
            quantum_instance=quantum_instance,
            optimizer=optimizer,
        )
        result = vqe.compute_minimum_eigenvalue()
        self.assertGreater(quantum_instance.time_taken, 0.)
        quantum_instance.reset_execution_results()
        self.assertAlmostEqual(result.eigenvalue.real, -1.86, places=2)
Ejemplo n.º 22
0
    def test_measurement_error_mitigation(self):
        """ measurement error mitigation test """
        try:
            # pylint: disable=import-outside-toplevel
            from qiskit import Aer
            from qiskit.providers.aer import noise
        except ImportError as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return

        aqua_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],
                                                            [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        backend = Aer.get_backend('qasm_simulator')
        quantum_instance = QuantumInstance(backend=backend,
                                           seed_simulator=167,
                                           seed_transpiler=167,
                                           noise_model=noise_model)

        qi_with_mitigation = \
            QuantumInstance(backend=backend,
                            seed_simulator=167,
                            seed_transpiler=167,
                            noise_model=noise_model,
                            measurement_error_mitigation_cls=CompleteMeasFitter)
        oracle = LogicalExpressionOracle('a & b & c')
        grover = Grover(oracle)

        result_wo_mitigation = grover.run(quantum_instance)
        self.assertGreater(quantum_instance.time_taken, 0.)
        quantum_instance.reset_execution_results()
        prob_top_meas_wo_mitigation = result_wo_mitigation.measurement[
            result_wo_mitigation.top_measurement]

        result_w_mitigation = grover.run(qi_with_mitigation)
        prob_top_meas_w_mitigation = \
            result_w_mitigation.measurement[result_w_mitigation.top_measurement]

        self.assertGreaterEqual(prob_top_meas_w_mitigation,
                                prob_top_meas_wo_mitigation)
Ejemplo n.º 23
0
    def __get_counts(self,
                     params: List[float or int],
                     shots: int = 1000) -> dict:
        """
		Here we run the circuit according to the given parameters for each gate and return the counts for each state.

		:param params: List of the parameters of the RY and RX gates of the circuit.
		:param shots: Total number of shots the circuit must execute
		"""
        # Error probabilities
        prob_1 = 0.001  # 1-qubit gate
        prob_2 = 0.01  # 2-qubit gate

        # Depolarizing quantum errors
        error_1 = noise.depolarizing_error(prob_1, 1)
        error_2 = noise.depolarizing_error(prob_2, 2)

        # Add errors to noise model
        noise_model = noise.NoiseModel()
        noise_model.add_all_qubit_quantum_error(error_1, ['u1', 'u2'])
        noise_model.add_all_qubit_quantum_error(error_2, ['cx'])

        # Get basis gates from noise model
        basis_gates = noise_model.basis_gates

        # Make a circuit
        circ = QuantumCircuit(2, 2)

        # Set gates and measurement
        circ.ry(params[0], 0)
        circ.rx(params[1], 1)
        circ.cx(0, 1)
        circ.measure([0, 1], [0, 1])

        # Perform a noisy simulation and get the counts
        # noinspection PyTypeChecker
        result = execute(circ,
                         Aer.get_backend('qasm_simulator'),
                         basis_gates=basis_gates,
                         noise_model=noise_model,
                         shots=shots).result()
        counts = result.get_counts(0)

        return counts
Ejemplo n.º 24
0
    def test_measurement_error_mitigation_with_vqe(self):
        """measurement error mitigation test with vqe"""
        try:
            from qiskit.ignis.mitigation.measurement import CompleteMeasFitter
            from qiskit import Aer
            from qiskit.providers.aer import noise
        except ImportError as ex:
            self.skipTest(
                "Package doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return

        algorithm_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],
                                                            [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        backend = Aer.get_backend("aer_simulator")

        quantum_instance = QuantumInstance(
            backend=backend,
            seed_simulator=167,
            seed_transpiler=167,
            noise_model=noise_model,
            measurement_error_mitigation_cls=CompleteMeasFitter,
        )

        h2_hamiltonian = (-1.052373245772859 * (I ^ I) + 0.39793742484318045 *
                          (I ^ Z) - 0.39793742484318045 * (Z ^ I) -
                          0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 *
                          (X ^ X))
        optimizer = SPSA(maxiter=200)
        ansatz = EfficientSU2(2, reps=1)

        vqe = VQE(ansatz=ansatz,
                  optimizer=optimizer,
                  quantum_instance=quantum_instance)
        result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian)
        self.assertGreater(quantum_instance.time_taken, 0.0)
        quantum_instance.reset_execution_results()
        self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05)
    def test_measurement_error_mitigation_with_vqe(self, config):
        """measurement error mitigation test with vqe"""
        if _ERROR_MITIGATION_IMPORT_ERROR is not None:
            self.skipTest(
                f"Package doesn't appear to be installed. Error: '{_ERROR_MITIGATION_IMPORT_ERROR}'"
            )
            return

        fitter_str, mit_pattern = config
        algorithm_globals.random_seed = 0

        # build noise model
        noise_model = noise.NoiseModel()
        read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1],
                                                            [0.25, 0.75]])
        noise_model.add_all_qubit_readout_error(read_err)

        fitter_cls = (CompleteMeasFitter if fitter_str == "CompleteMeasFitter"
                      else TensoredMeasFitter)
        backend = Aer.get_backend("aer_simulator")
        quantum_instance = QuantumInstance(
            backend=backend,
            seed_simulator=167,
            seed_transpiler=167,
            noise_model=noise_model,
            measurement_error_mitigation_cls=fitter_cls,
            mit_pattern=mit_pattern,
        )

        h2_hamiltonian = (-1.052373245772859 * (I ^ I) + 0.39793742484318045 *
                          (I ^ Z) - 0.39793742484318045 * (Z ^ I) -
                          0.01128010425623538 * (Z ^ Z) + 0.18093119978423156 *
                          (X ^ X))
        optimizer = SPSA(maxiter=200)
        ansatz = EfficientSU2(2, reps=1)

        vqe = VQE(ansatz=ansatz,
                  optimizer=optimizer,
                  quantum_instance=quantum_instance)
        result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian)
        self.assertGreater(quantum_instance.time_taken, 0.0)
        quantum_instance.reset_execution_results()
        self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05)
Ejemplo n.º 26
0
    def test_batch_transpile_options_integrated(self):
        """
        The goal is to verify that not only `_trasnpiled_circuits` works well
        (`test_batch_transpiled_circuits` takes care of it) but that it's correctly called within
        the entire flow of `BaseExperiment.run`.
        """
        backend = Aer.get_backend("aer_simulator")
        noise_model = noise.NoiseModel()
        noise_model.add_all_qubit_quantum_error(
            noise.depolarizing_error(0.5, 2), ["cx", "swap"])

        expdata = self.batch2.run(backend, noise_model=noise_model, shots=1000)
        expdata.block_for_results()

        self.assertEqual(expdata.child_data(0).analysis_results(0).value, 8)
        self.assertEqual(
            expdata.child_data(1).child_data(0).analysis_results(0).value, 16)
        self.assertEqual(
            expdata.child_data(1).child_data(1).analysis_results(0).value, 4)
Ejemplo n.º 27
0
class NoisySimulationTest(unittest.TestCase):
    """Base class that contains methods and attributes
    for doing tests of readout error noise with flexible
    readout errors.
    """

    sim = QasmSimulator()

    # Example max qubit number
    num_qubits = 4

    # Create readout errors
    readout_errors = []
    for i in range(num_qubits):
        p_error1 = (i + 1) * 0.002
        p_error0 = 2 * p_error1
        ro_error = noise.ReadoutError([[1 - p_error0, p_error0], [p_error1, 1 - p_error1]])
        readout_errors.append(ro_error)
    # TODO: Needs 2q errors?

    # Readout Error only
    noise_model = noise.NoiseModel()
    for i in range(num_qubits):
        noise_model.add_readout_error(readout_errors[i], [i])
    seed_simulator = 100

    shots = 10000

    tolerance = 0.05

    def execute_circs(self, qc_list: List[QuantumCircuit],
                      noise_model=None) -> Result:
        """Run circuits with the readout noise defined in this class
        """
        backend = self.sim
        qobj = assemble(transpile(qc_list, backend=backend),
                        backend=backend, shots=self.shots,
                        seed_simulator=self.seed_simulator,
                        noise_model=None if noise_model is None else self.noise_model,
                        method='density_matrix')

        return backend.run(qobj).result()
Ejemplo n.º 28
0
    def run_simulation(self, shots=8192, error_prob=0, target_state='000'):
        # add noise
        error_1 = noise.depolarizing_error(error_prob, 1)
        noise_model = noise.NoiseModel()
        noise_model.add_all_qubit_quantum_error(error_1, ['x', 'z'])

        # run simulation
        self.qc.measure([0, 1, 2], [4, 3, 2])
        emulator = Aer.get_backend('qasm_simulator')
        job = execute(self.qc, emulator, noise_model=noise_model, shots=shots)
        hist = job.result().get_counts()
        # print(hist)

        # print statistics
        successes = 0
        first_three = [n[0:3] for n in list(hist.keys())]
        for i in range(len(first_three)):
            if (first_three[i] == target_state):
                successes += hist.get(list(hist.keys())[i])
        # print("success rate:", successes/shots)
        return successes / shots
Ejemplo n.º 29
0
    def test_noise_model_io_using_core_functions(self):
        # Given
        noise_model = AerNoise.NoiseModel()
        quantum_error = AerNoise.depolarizing_error(0.0, 1)
        coherent_error = np.asarray([
            np.asarray(
                [0.87758256 - 0.47942554j, 0.0 + 0.0j, 0.0 + 0.0j,
                 0.0 + 0.0j]),
            np.asarray(
                [0.0 + 0.0j, 0.87758256 + 0.47942554j, 0.0 + 0.0j,
                 0.0 + 0.0j]),
            np.asarray(
                [0.0 + 0.0j, 0.0 + 0.0j, 0.87758256 + 0.47942554j,
                 0.0 + 0.0j]),
            np.asarray(
                [0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j,
                 0.87758256 - 0.47942554j]),
        ])
        noise_model.add_quantum_error(
            AerNoise.coherent_unitary_error(coherent_error), ["cx"], [0, 1])
        noise_model_data = noise_model.to_dict(serializable=True)
        module_name = "qeqiskit.utils"
        function_name = "load_qiskit_noise_model"
        filename = "noise_model.json"

        # When
        save_noise_model(noise_model_data, module_name, function_name,
                         filename)
        new_noise_model = load_noise_model(filename)

        # Then
        self.assertEqual(
            noise_model.to_dict(serializable=True),
            new_noise_model.to_dict(serializable=True),
        )

        # Cleanup
        subprocess.run(["rm", "noise_model.json"])
Ejemplo n.º 30
0
def randbin3(data, F, theta_sphere, phi_sphere=0): # simulator --- WORKS
    prob_1 = 0.3
    error_1 = noise.depolarizing_error(prob_1, 1)
    noise_model = noise.NoiseModel()
    noise_model.add_all_qubit_quantum_error(error_1, ['u3'])
    basis_gates = noise_model.basis_gates


    phi = data.const * F * data.t * data.F_degree

    q = QuantumRegister(1)
    c = ClassicalRegister(1)

    # Create a Quantum Circuit acting on the q register
    circuit = QuantumCircuit(q, c)

    rotate_angle = math.pi - 2*phi
    circuit.u3(theta_sphere, phi_sphere, 0, q)
    circuit.rz(2*phi, q)
    circuit.h(q)

    # Map the quantum measurement to the classical bits
    circuit.measure(q, c)

    # Execute the circuit on the qasm simulator
    job = execute(circuit, Aer.get_backend('qasm_simulator'),
                 basis_gates=basis_gates,
                 noise_model=noise_model, shots=1)
    #job_monitor(job)

    # Grab results from the job
    result = job.result()

    # Returns counts
    counts = result.get_counts(circuit)

    return int(list(counts.keys())[0])