Ejemplo n.º 1
0
def test_statevector():
    qc: qiskit.QuantumCircuit = qiskit.QuantumCircuit(2, 2)
    qc.h(0)
    qc.cx(0, 1)
    # addition of a measure gate "locks" the bit in qiskit-aer's
    # statevector simulator such that
    # the statevector measured after that has that bit "locked".
    # This is not how quasar works, so we will focus on gates without
    # measurements
    provider = QcwareProvider()
    sv1 = qiskit.execute(qc, backend=provider.get_backend(
        'local_statevector')).result().data()['statevector']
    aer_backend = AerSimulator(method="statevector")
    c = qc.copy()
    c.save_state("final_statevector")
    sv2 = qiskit.execute(c, aer_backend).result().data()['final_statevector']
    assert (numpy.allclose(sv1, sv2))
    def test_batch_exp(self):
        """Test batch state tomography experiment with measurement_qubits kwarg"""
        # Subsystem unitaries
        seed = 1111
        nq = 3
        ops = [qi.random_unitary(2, seed=seed + i) for i in range(nq)]

        # Preparation circuit
        circuit = QuantumCircuit(nq)
        for i, op in enumerate(ops):
            circuit.append(op, [i])

        # Component experiments
        exps = []
        targets = []
        for i in range(nq):
            targets.append(qi.Statevector(ops[i].to_instruction()))
            exps.append(StateTomography(circuit, measurement_qubits=[i]))

        # Run batch experiments
        backend = AerSimulator(seed_simulator=9000)
        batch_exp = BatchExperiment(exps)
        batch_data = batch_exp.run(backend)
        batch_data.block_for_results()

        # Check target fidelity of component experiments
        f_threshold = 0.95
        for i in range(batch_exp.num_experiments):
            results = batch_data.component_experiment_data(
                i).analysis_results()

            # Check state is density matrix
            state = filter_results(results, "state").value
            self.assertTrue(isinstance(state, qi.DensityMatrix),
                            msg="fitted state is not density matrix")

            # Check fit state fidelity
            fid = filter_results(results, "state_fidelity").value
            self.assertGreater(fid, f_threshold, msg="fit fidelity is low")

            # Manually check fidelity
            target_fid = qi.state_fidelity(state, targets[i], validate=False)
            self.assertAlmostEqual(fid,
                                   target_fid,
                                   places=6,
                                   msg="result fidelity is incorrect")
Ejemplo n.º 3
0
def run():
    cmA = qct.CircuitManager(2, measures=['PreMeasure'], qMeasures=["Qubit A", "Qubit B"])

    circuit = cmA.circuit

    circuit.h(0)
    cmA.measure(0,'PreMeasure')
    cmA.measureAll(barrier=True)

    cmA.simulate(AerSimulator(), 1000)

    # Draw the circuit
    circuit.draw(output='mpl')
    pyplot.get_current_fig_manager().set_window_title('Circuit A')
    cmA.printEntanglementTable()
    cmA.printEntanglements()
    pyplot.show(block=False)
Ejemplo n.º 4
0
def _generate_rb_fitter_data(dir_name: str, rb_exp_name: str,
                             exp_attributes: dict):
    """
    Executing standard RB experiment and storing its data in json format.
    The json is composed of a list that the first element is a dictionary containing
    the experiment attributes and the second element is a list with all the experiment
    data.
    Args:
        dir_name: The json file name that the program write the data to.
        rb_exp_name: The experiment name for naming the output files.
        exp_attributes: attributes to config the RB experiment.
    """
    gate_error_ratio = {
        ((0, ), "id"): 1,
        ((0, ), "rz"): 0,
        ((0, ), "sx"): 1,
        ((0, ), "x"): 1,
        ((0, 1), "cx"): 1,
    }
    transpiled_base_gate = ["cx", "sx", "x"]
    results_file_path = os.path.join(dir_name,
                                     str(rb_exp_name + "_output_data.json"))
    analysis_file_path = os.path.join(
        dir_name, str(rb_exp_name + "_output_analysis.json"))
    noise_model = create_depolarizing_noise_model()
    backend = AerSimulator(seed_simulator=exp_attributes["seed"])
    print("Generating RB experiment")
    rb_exp = StandardRB(
        exp_attributes["physical_qubits"],
        exp_attributes["lengths"],
        num_samples=exp_attributes["num_samples"],
        seed=exp_attributes["seed"],
    )
    rb_exp.analysis.set_options(gate_error_ratio=gate_error_ratio)
    print("Running experiment")
    experiment_obj = rb_exp.run(backend,
                                noise_model=noise_model,
                                basis_gates=transpiled_base_gate)
    experiment_obj.block_for_results()
    print("Done running experiment")
    exp_results = experiment_obj.data()
    with open(results_file_path, "w") as json_file:
        joined_list_data = [exp_attributes, exp_results]
        json_file.write(json.dumps(joined_list_data))
    _analysis_save(experiment_obj.analysis_results(), analysis_file_path)
Ejemplo n.º 5
0
    def test_standard_case(self):
        """Test a standard use case."""
        circuit = RealAmplitudes(3)
        operator = Z ^ I ^ Z
        initial_point = np.random.random(circuit.num_parameters)
        optimizer = {"name": "SPSA", "maxiter": 100}
        backend = AerSimulator()

        vqe = VQEProgram(
            ansatz=circuit,
            optimizer=optimizer,
            initial_point=initial_point,
            backend=backend,
            provider=self.provider,
        )
        result = vqe.compute_minimum_eigenvalue(operator)

        self.assertIsInstance(result, VQEResult)
Ejemplo n.º 6
0
    def test_parallel_exp(self):
        """Test parallel process tomography experiment"""
        # Subsystem unitaries
        seed = 1221
        nq = 4
        ops = [qi.random_unitary(2, seed=seed + i) for i in range(nq)]

        # Component experiments
        exps = []
        targets = []
        for i in range(nq):
            exps.append(ProcessTomography(ops[i], qubits=[i]))
            targets.append(ops[i])

        # Run batch experiments
        backend = AerSimulator(seed_simulator=9000)
        par_exp = ParallelExperiment(exps)
        par_data = par_exp.run(backend)
        self.assertExperimentDone(par_data)

        # Check target fidelity of component experiments
        f_threshold = 0.95
        for i in range(par_exp.num_experiments):
            results = par_data.child_data(i).analysis_results()

            # Check state is density matrix
            state = filter_results(results, "state").value
            self.assertTrue(isinstance(state, qi.Choi),
                            msg="fitted state is not a Choi matrix")

            # Check fit state fidelity
            fid = filter_results(results, "process_fidelity").value
            self.assertGreater(fid, f_threshold, msg="fit fidelity is low")

            # Manually check fidelity
            target_fid = qi.process_fidelity(state,
                                             targets[i],
                                             require_tp=False,
                                             require_cp=False)
            self.assertAlmostEqual(fid,
                                   target_fid,
                                   places=6,
                                   msg="result fidelity is incorrect")
Ejemplo n.º 7
0
    def test_full_exp_measurement_qubits(self, meas_qubits):
        """Test subset state tomography generation"""
        # Subsystem unitaries
        seed = 1111
        nq = 3
        ops = [qi.random_unitary(2, seed=seed + i) for i in range(nq)]

        # Target state
        target_circ = QuantumCircuit(len(meas_qubits))
        for i, qubit in enumerate(meas_qubits):
            target_circ.append(ops[qubit], [i])
        target = qi.Statevector(target_circ)

        # Preparation circuit
        circ = QuantumCircuit(nq)
        for i, op in enumerate(ops):
            circ.append(op, [i])

        # Run
        backend = AerSimulator(seed_simulator=9000)
        exp = StateTomography(circ, measurement_qubits=meas_qubits)
        expdata = exp.run(backend)
        self.assertExperimentDone(expdata)
        results = expdata.analysis_results()

        # Check result
        f_threshold = 0.95

        # Check state is density matrix
        state = filter_results(results, "state").value
        self.assertTrue(isinstance(state, qi.DensityMatrix),
                        msg="fitted state is not density matrix")

        # Check fit state fidelity
        fid = filter_results(results, "state_fidelity").value
        self.assertGreater(fid, f_threshold, msg="fit fidelity is low")

        # Manually check fidelity
        target_fid = qi.state_fidelity(state, target, validate=False)
        self.assertAlmostEqual(fid,
                               target_fid,
                               places=6,
                               msg="result fidelity is incorrect")
    def test_full_qst(self, num_qubits):
        """Test QST experiment"""
        seed = 1234
        shots = 5000
        f_threshold = 0.99

        # Generate tomography data without analysis
        backend = AerSimulator(seed_simulator=seed, shots=shots)
        target = qi.random_statevector(2**num_qubits, seed=seed)
        exp = StateTomography(target)
        expdata = exp.run(backend, analysis=None)
        self.assertExperimentDone(expdata)

        # Run each tomography fitter analysis as a subtest so
        # we don't have to re-run simulation data for each fitter
        for fitter in FITTERS:
            with self.subTest(fitter=fitter):
                if fitter:
                    exp.analysis.set_options(fitter=fitter)
                fitdata = exp.analysis.run(expdata)
                self.assertExperimentDone(fitdata)
                results = expdata.analysis_results()

                # Check state is density matrix
                state = filter_results(results, "state").value
                self.assertTrue(
                    isinstance(state, qi.DensityMatrix),
                    msg=f"{fitter} fitted state is not density matrix",
                )

                # Check fit state fidelity
                fid = filter_results(results, "state_fidelity").value
                self.assertGreater(fid,
                                   f_threshold,
                                   msg=f"{fitter} fit fidelity is low")

                # Manually check fidelity
                target_fid = qi.state_fidelity(state, target, validate=False)
                self.assertAlmostEqual(
                    fid,
                    target_fid,
                    places=6,
                    msg=f"{fitter} result fidelity is incorrect")
Ejemplo n.º 9
0
def create_qv_data_low_hop(dir_path: str):
    """
    create quantum volume experiment_data using seed, and save it as a json
    the circuit is generated with high noise, so the mean hop is below 2/3
    Args:
        dir_path(str): The directory which the data will be saved to.
    """
    num_of_qubits = 4
    backend = AerSimulator(seed_simulator=SEED)
    basis_gates = ["id", "rz", "sx", "x", "cx", "reset"]
    noise = create_high_noise_model()

    qv_exp = QuantumVolume(range(num_of_qubits), seed=SEED)
    qv_exp.set_transpile_options(basis_gates=basis_gates)
    qv_data = qv_exp.run(backend, noise_model=noise, basis_gates=basis_gates)
    qv_data.block_for_results()

    result_file_path = os.path.join(dir_path, "qv_data_high_noise.json")
    with open(result_file_path, "w") as json_file:
        json.dump(qv_data.data(), json_file, cls=ExperimentEncoder)
    def test_parallel_exp(self):
        """Test parallel state tomography experiment"""
        # Subsystem unitaries
        seed = 1221
        nq = 4
        ops = [qi.random_unitary(2, seed=seed + i) for i in range(nq)]

        # Component experiments
        exps = []
        targets = []
        for i in range(nq):
            exps.append(StateTomography(ops[i], qubits=[i]))
            targets.append(qi.Statevector(ops[i].to_instruction()))

        # Run batch experiments
        backend = AerSimulator(seed_simulator=9000)
        par_exp = ParallelExperiment(exps)
        par_data = par_exp.run(backend)
        par_data.block_for_results()

        # Check target fidelity of component experiments
        f_threshold = 0.95
        for i in range(par_exp.num_experiments):
            results = par_data.component_experiment_data(i).analysis_results()

            # Check state is density matrix
            state = filter_results(results, "state").value
            self.assertTrue(isinstance(state, qi.DensityMatrix),
                            msg="fitted state is not density matrix")

            # Check fit state fidelity
            fid = filter_results(results, "state_fidelity").value
            self.assertGreater(fid, f_threshold, msg="fit fidelity is low")

            # Manually check fidelity
            target_fid = qi.state_fidelity(state, targets[i], validate=False)
            self.assertAlmostEqual(fid,
                                   target_fid,
                                   places=6,
                                   msg="result fidelity is incorrect")
Ejemplo n.º 11
0
    def test_qst_teleport(self):
        """Test subset state tomography generation"""
        # NOTE: This test breaks transpiler. I think it is a bug with
        # conditionals in Terra.

        # Teleport qubit 0 -> 2
        backend = AerSimulator(seed_simulator=9000)
        exp = StateTomography(teleport_circuit(), measurement_qubits=[2])
        expdata = exp.run(backend)
        results = expdata.analysis_results()

        # Check result
        f_threshold = 0.95

        # Check state is density matrix
        state = filter_results(results, "state").value
        self.assertTrue(isinstance(state, qi.DensityMatrix),
                        msg="fitted state is not a density matrix")

        # Manually check fidelity
        fid = qi.state_fidelity(state, qi.Statevector([1, 0]), validate=False)
        self.assertGreater(fid,
                           f_threshold,
                           msg="fitted state fidelity is low")
Ejemplo n.º 12
0
def supported_devices(func):
    """ddt decorator for iterative over supported devices on current system."""
    devices = AerSimulator().available_devices()
    return ddt.data(*devices)(func)
Ejemplo n.º 13
0
 def __init__(self, freq_shift: float, sx_duration: int = 160):
     super().__init__()
     self.freq_shift = freq_shift
     self.dt = self.configuration().dt
     self.sx_duration = sx_duration
     self.simulator = AerSimulator(method="automatic")
Ejemplo n.º 14
0
 def backend(self, **options):
     """Return AerSimulator backend using current class options"""
     sim_options = self.OPTIONS.copy()
     for key, val in options.items():
         sim_options[key] = val
     return AerSimulator(**sim_options)
Ejemplo n.º 15
0
    def setUp(self):
        super().setUp()

        # specify quantum instances
        self.sv_quantum_instance = QuantumInstance(StatevectorSimulator())
        self.qasm_quantum_instance = QuantumInstance(AerSimulator(), shots=100)
Ejemplo n.º 16
0
    def calculate_expectation(self, pauli_string_object):
        # previous_expectation_vals = self.previous_expectation_vals
        # initial_state_object = self.initial_state_object
        # sim = self.sim
        # backend = self.backend
        # coupling_map = self.coupling_map
        # meas_error_mitigate = self.meas_error_mitigate
        # meas_filter = self.meas_filter
        # noise_model = self.noise_model
        # num_shots = self.num_shots

        pauli_string_strform = pauli_string_object.get_string_for_hash()
        pauli_string_coeff = pauli_string_object.return_coefficient()
        # print(pauli_string_coeff)
        pauli_string = pauli_string_strform
        if pauli_string in self.previous_expectation_vals.keys():
            return pauli_string_coeff * self.previous_expectation_vals[
                pauli_string]
        qc = self.make_qc_to_measure_pstring(self.initial_state_object,
                                             pauli_string)

        if self.sim == "noisy_qasm":
            '''NEED TO MAKE SOME CHANGES HERE FOR ARTIFICIAL NOISE MODEL: JON'''
            #results = execute(qc, backend=self.backend, shots = self.num_shots, coupling_map = self.coupling_map, noise_model = self.noise_model).result()
            '''Changes Here'''
            sim_noise = AerSimulator(noise_model=self.noise_model)
            circ_noise = transpile(qc,
                                   sim_noise,
                                   coupling_map=self.coupling_map)
            results = sim_noise.run(circ_noise, shots=self.num_shots).result()

            if self.meas_error_mitigate == True:
                results = self.meas_filter.apply(results)
            counts = results.get_counts()
        elif self.sim == "noiseless_qasm":
            counts = execute(qc, backend=self.backend,
                             shots=self.num_shots).result().get_counts()
        elif self.sim == "real":
            job = execute(qc, backend=self.backend, shots=self.num_shots)
            job_monitor(job, interval=2)
            results = job.result()
            if self.meas_error_mitigate == True:
                results = self.meas_filter.apply(results)
            counts = results.get_counts()
        #print("Finished shots")

        frequency_dict = dict()
        total_num_of_counts = sum(counts.values())
        for key, value in counts.items():
            frequency_dict[key] = value / total_num_of_counts
        ans = 0 + 0j
        #since we did measurement in Z basis, we must change our pauli_string.
        #Note that when we did "make qc to measure p_string", we have already
        #reversed the p_string there.  for the "counts" object, note that the
        #bitstrings are in qiskit order, i.e the rightmost bit is the 1st
        #qubit.
        new_pauli_string = []
        for char in pauli_string:
            new_pauli_string.append(
                "1") if char != "0" else new_pauli_string.append(char)
        new_pauli_string = "".join(new_pauli_string)
        for key, value in frequency_dict.items():
            # print(key)
            coeff = np.base_repr(int(key, 2) & int(new_pauli_string, 2),
                                 base=2).count("1")  #bitwise and
            ans += (-1)**coeff * value
        # print(pauli_string, ans)
        self.previous_expectation_vals[pauli_string] = ans
        return ans * pauli_string_coeff


# def make_expectation_calculator(initial_state_object, sim, quantum_com_choice_results, num_shots = 8192, meas_error_mitigate = False, meas_filter = None):
#     """
#     This upper function has a dictionary that stores the previously calculated expectation values, so we don't do any re-calculation.

#     sim can be either noisy_qasm, noiseless_qasm, or real.
#     """
#     if sim == "noisy_qasm" or sim == "real":
#         if meas_error_mitigate == True and meas_filter == None:
#             raise(RuntimeError("no meas_filter specified, so no measurement error mitigation can be done!"))
#     if sim == "noisy_qasm":
#         backend, coupling_map, noise_model = quantum_com_choice_results[sim]
#     elif sim == "real" or sim == "noiseless_qasm":
#         backend = quantum_com_choice_results[sim]
#     previous_expectation_vals = dict()

#     def expectation_calculator(pauli_string_object):
#         pauli_string_strform = pauli_string_object.get_string_for_hash()
#         pauli_string_coeff = pauli_string_object.return_coefficient()
#         # print(pauli_string_coeff)
#         pauli_string = pauli_string_strform
#         if pauli_string in previous_expectation_vals.keys():
#             return pauli_string_coeff * previous_expectation_vals[pauli_string]
#         qc = make_qc_to_measure_pstring(initial_state_object, pauli_string)

#         if sim == "noisy_qasm":
#             results = execute(qc, backend=backend, shots = num_shots, coupling_map = coupling_map, noise_model = noise_model).result()
#             if meas_error_mitigate == True:
#                 results = meas_filter.apply(results)
#             counts = results.get_counts()
#         elif sim == "noiseless_qasm":
#             counts = execute(qc, backend=backend, shots = num_shots).result().get_counts()
#         elif sim == "real":
#             job = execute(qc, backend = backend, shots = num_shots)
#             job_monitor(job, interval = 2)
#             results = job.result()
#             if meas_error_mitigate == True:
#                 results = meas_filter.apply(results)
#             counts = results.get_counts()
#         #print("Finished shots")

#         frequency_dict = dict()
#         total_num_of_counts = sum(counts.values())
#         for key,value in counts.items():
#             frequency_dict[key] = value/total_num_of_counts
#         ans = 0 + 0j
#         #since we did measurement in Z basis, we must change our pauli_string.
#         #Note that when we did "make qc to measure p_string", we have already
#         #reversed the p_string there.  for the "counts" object, note that the
#         #bitstrings are in qiskit order, i.e the rightmost bit is the 1st
#         #qubit.
#         new_pauli_string = []
#         for char in pauli_string:
#             new_pauli_string.append("1") if char != "0" else new_pauli_string.append(char)
#         new_pauli_string = "".join(new_pauli_string)
#         for key, value in frequency_dict.items():
#             # print(key)
#             coeff = np.base_repr(int(key,2) & int(new_pauli_string, 2), base = 2).count("1") #bitwise and
#             ans += (-1)**coeff * value
#         # print(pauli_string, ans)
#         previous_expectation_vals[pauli_string] = ans
#         return ans * pauli_string_coeff
#     return expectation_calculator

#%% Testing
# if __name__ == "__main__":
#     num_qubits = 2
#     quantum_computer = "ibmq_rome"

#     sim = "noisy_qasm"
#     num_shots = 8192

#     # sim = "noiseless_qasm"
#     # num_shots = 100000

#     test_pstring = "23"
#     pauli_string_object = pcp.paulistring(num_qubits, test_pstring, -1j)
#     initial_state_object = acp.Initialstate(num_qubits, "efficient_SU2", 123, 3)

#     initial_statevector = initial_state_object.get_statevector()
#     print("the matrix multiplication result is",initial_statevector.conj().T @ pauli_string_object.get_matrixform() @ initial_statevector)

#     quantum_computer_choice_results = choose_quantum_computer("ibm-q-nus", group = "default", project = "reservations", quantum_com = quantum_computer)

#     #Noisy QASM
#     meas_filter = measurement_error_mitigator(num_qubits, sim, quantum_computer_choice_results, shots = num_shots)
#     expectation_calculator = make_expectation_calculator(initial_state_object, sim, quantum_computer_choice_results, meas_error_mitigate = True, meas_filter = meas_filter)

#     #Noiseless QASM
#     # expectation_calculator = make_expectation_calculator(initial_state_object, sim, quantum_computer_choice_results, meas_error_mitigate = False)

#     print("the quantum result is",expectation_calculator(pauli_string_object))

# import Qiskit_helperfunctions_kh as qhf #IBMQ account is loaded here in this import
# hub, group, project = "ibm-q-nus", "default", "reservations"
# quantum_com = "ibmq_rome"

# #Other parameters for running on the quantum computer
# sim = "noisy_qasm"
# num_shots = 8192

# quantum_computer_choice_results = qhf.choose_quantum_computer(hub, group, project, quantum_com)
# mitigate_meas_error = True
# meas_filter = qhf.measurement_error_mitigator(num_qubits, sim, quantum_computer_choice_results, shots = num_shots)

# expectation_calculator = qhf.make_expectation_calculator(initial_state, sim, quantum_computer_choice_results, meas_error_mitigate = mitigate_meas_error, meas_filter = meas_filter)
Ejemplo n.º 17
0
                        MemorySlot(0)) << schedule.duration

    return model, schedule


if __name__ == '__main__':
    # Run Aer simulator
    shots = 4000
    circuits = grovers_circuit(final_measure=True, allow_sampling=True)
    targets = [{
        '0x0': 5 * shots / 8,
        '0x1': shots / 8,
        '0x2': shots / 8,
        '0x3': shots / 8
    }]
    simulator = AerSimulator()
    result = simulator.run(transpile(circuits, simulator),
                           shots=shots).result()
    assert result.status == 'COMPLETED'
    assert result.success is True
    compare_counts(result, circuits, targets, delta=0.05 * shots)

    # Run qasm simulator
    simulator = QasmSimulator()
    result = simulator.run(transpile(circuits, simulator),
                           shots=shots).result()
    assert result.status == 'COMPLETED'
    assert result.success is True
    compare_counts(result, circuits, targets, delta=0.05 * shots)

    # Run statevector simulator
Ejemplo n.º 18
0
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
Base class of Qiskit Aer Benchmarking
"""
import sys
import numpy as np
from time import time
from qiskit.compiler import transpile, assemble
from qiskit.providers.aer import AerSimulator, UnitarySimulator
from qiskit.providers.aer.noise import NoiseModel, amplitude_damping_error, depolarizing_error

from benchmark.circuit_library_circuits import CircuitLibraryCircuits

QOBJS = {}
SIMULATOR = AerSimulator()


class SimulatorBenchmarkSuite(CircuitLibraryCircuits):

    RUNTIME_STATEVECTOR_CPU = 'statevector'
    RUNTIME_STATEVECTOR_GPU = 'statevector_gpu'
    RUNTIME_MPS_CPU = 'matrix_product_state'
    RUNTIME_DENSITY_MATRIX_CPU = 'density_matrix'
    RUNTIME_DENSITY_MATRIX_GPU = 'density_matrix_gpu'
    RUNTIME_STABILIZER_CPU = 'stabilizer'
    RUNTIME_EXTENDED_STABILIZER_CPU = 'extended_stabilizer'
    RUNTIME_UNITARY_MATRIX_CPU = 'unitary_matrix'
    RUNTIME_UNITARY_MATRIX_GPU = 'unitary_matrix_gpu'

    RUNTIME_CPU = [
Ejemplo n.º 19
0
def aer_probability_vector(circuit: qiskit.QuantumCircuit):
    backend = AerSimulator(method="statevector")
    c = circuit.copy()
    c.save_state("final_statevector")
    sv = qiskit.execute(c, backend).result().data()['final_statevector']
    return abs(sv)
Ejemplo n.º 20
0
def ibmsim(circ):
    sim = AerSimulator()

    compiled = transpile(circ, sim)
    return sim.run(compiled, shots=100000).result()