def generate_mitigator(num_qubits, noisy, shots=1024):
    meas_calibs, state_labels = complete_meas_cal(range(num_qubits))
    experiments = transpile(meas_calibs, backend=noisy, optimization_level=3)
    job = noisy.run(assemble(experiments, shots=shots))
    cal_results = job.result()
    meas_fitter = CompleteMeasFitter(cal_results, state_labels)
    return job, meas_fitter.filter
Пример #2
0
def mitigated_results(circuit, backend, results):
    # Import the required methods
    from qiskit.providers.aer.noise import NoiseModel
    from qiskit.ignis.mitigation.measurement import (complete_meas_cal,
                                                     CompleteMeasFitter)

    # Get noise model for backend
    noise_model = NoiseModel.from_backend(backend)

    # Create the measurement fitter
    qr = QuantumRegister(circuit.num_qubits)
    meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
    job = execute(meas_calibs,
                  backend=Aer.get_backend('qasm_simulator'),
                  shots=8192,
                  noise_model=noise_model)
    cal_results = job.result()
    meas_fitter = CompleteMeasFitter(cal_results,
                                     state_labels,
                                     circlabel='mcal')
    #print(meas_fitter.cal_matrix)

    # Plot the calibration matrix
    print("Calibration matrix")
    meas_fitter.plot_calibration()

    # Get the filter object
    meas_filter = meas_fitter.filter

    # Results with mitigation
    mitigated_results = meas_filter.apply(results)
    mitigated_counts = mitigated_results.get_counts(0)
    print("Mitigated", backend, "results:\n", mitigated_counts)
    return (mitigated_counts)
Пример #3
0
def meas_calib_circ_creation():
    """
    create measurement calibration circuits and a GHZ state circuit for the tests

    Returns:
        QuantumCircuit: the measurement calibrations circuits
        list[str]: the mitigation pattern
        QuantumCircuit: ghz circuit with 5 qubits (3 are used)

    """
    qubit_list = [1, 2, 3]
    total_number_of_qubit = 5
    meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list,
                                                  qr=total_number_of_qubit)

    # Choose 3 qubits
    qubit_1 = qubit_list[0]
    qubit_2 = qubit_list[1]
    qubit_3 = qubit_list[2]
    ghz = qiskit.QuantumCircuit(total_number_of_qubit, len(qubit_list))
    ghz.h(qubit_1)
    ghz.cx(qubit_1, qubit_2)
    ghz.cx(qubit_1, qubit_3)
    for i in qubit_list:
        ghz.measure(i, i - 1)
    return meas_calibs, state_labels, ghz
def mitigated_results(backend,circuit,results,results_sim):
    from qiskit import Aer, execute
    from qiskit import QuantumRegister
    # Import the required methods
    from qiskit.providers.aer.noise import NoiseModel
    from qiskit.ignis.mitigation.measurement import (complete_meas_cal,CompleteMeasFitter)
    from qiskit.tools.visualization import plot_histogram
    import numpy
    numpy.set_printoptions(formatter={'float': lambda x: "{0:0.2f}".format(x)})
    
    # Get noise model for backend
    noise_model = NoiseModel.from_backend(backend)
    
    # Create the measurement fitter
    qr = QuantumRegister(circuit.num_qubits)
    meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
    job = execute(meas_calibs, backend=Aer.get_backend('qasm_simulator'), shots=8192, noise_model=noise_model)
    cal_results = job.result()
    meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
    print(meas_fitter.cal_matrix)

    # Get the filter object
    meas_filter = meas_fitter.filter
    
    # Results with mitigation
    mitigated_results = meas_filter.apply(results)
    mitigated_counts = mitigated_results.get_counts(0)
    
    title = "Mitigated Grover on "+str(ibmqbackend.name())
    display(plot_histogram([results_sim.get_counts(),results.get_counts(), mitigated_counts], title=title, legend=['sim','noisy', 'mitigated']))
    return(mitigated_counts)
Пример #5
0
def _qiskit_generate_samples_MEM(self: QiskitDevice) -> np.array:
    """
        This function is used to overrite the default QiskitDevice.generate_samples method.
        It adds a simple mechanism to perform measurement error mitigation on the results of
        the computation.
    """
    # branch out depending on the type of backend
    if self.backend_name in self._state_backends:
        # software simulator: need to sample from probabilities
        return super().generate_samples()

    # hardware or hardware simulator

    # ***here we actully perform the measurement error mitigation***
    meas_calibs, state_labels = complete_meas_cal(qr=self._reg, circlabel="mcal")
    mitigation_run_args = self.run_args.copy()
    mitigation_run_args["shots"] = NUMBER_OF_SHOTS_FOR_QISKIT_ERROR_MITIGATION
    meas_job = qiskit.execute(meas_calibs, backend=self.backend, **mitigation_run_args)

    # TODO: Adding a cache here is a free performance boost
    meas_fitter = CompleteMeasFitter(meas_job.result(), state_labels, circlabel="mcal")
    mitigated_results = meas_fitter.filter.apply(self._current_job.result())
    current_job_shots = sum(self._current_job.result().get_counts().values())
    summed_counts = sum(mitigated_results.get_counts().values())
    probs = [value / summed_counts for value in mitigated_results.get_counts().values()]
    samples = np.random.choice(
        np.array(list(mitigated_results.get_counts().keys())),
        current_job_shots,
        p=probs,
        replace=True,
    )

    # reverse qubit order to match PennyLane convention
    return np.vstack([np.array([int(i) for i in s[::-1]]) for s in samples])
Пример #6
0
def matricaZaGreske(brojQubita, noise_model):
    qr = QuantumRegister(brojQubita)
    meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
    backend = Aer.get_backend('qasm_simulator')
    job = execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model)
    cal_results = job.result()
    meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
    return(meas_fitter.cal_matrix)
Пример #7
0
def build_measurement_error_mitigation_circuits(qubit_list,
                                                fitter_cls,
                                                backend,
                                                backend_config=None,
                                                compile_config=None):
    """Build measurement error mitigation circuits
    Args:
        qubit_list (list[int]): list of ordered qubits used in the algorithm
        fitter_cls (callable): CompleteMeasFitter or TensoredMeasFitter
        backend (BaseBackend): backend instance
        backend_config (dict, optional): configuration for backend
        compile_config (dict, optional): configuration for compilation
    Returns:
        QasmQobj: the Qobj with calibration circuits at the beginning
        list[str]: the state labels for build MeasFitter
        list[str]: the labels of the calibration circuits
    Raises:
        QiskitError: when the fitter_cls is not recognizable.
        MissingOptionalLibraryError: Qiskit-Ignis not installed
    """
    try:
        from qiskit.ignis.mitigation.measurement import (
            complete_meas_cal,
            CompleteMeasFitter,
            TensoredMeasFitter,
        )
    except ImportError as ex:
        raise MissingOptionalLibraryError(
            libname="qiskit-ignis",
            name="build_measurement_error_mitigation_qobj",
            pip_install="pip install qiskit-ignis",
        ) from ex

    circlabel = "mcal"

    if not qubit_list:
        raise QiskitError("The measured qubit list can not be [].")

    if fitter_cls == CompleteMeasFitter:
        meas_calibs_circuits, state_labels = complete_meas_cal(
            qubit_list=range(len(qubit_list)), circlabel=circlabel)
    elif fitter_cls == TensoredMeasFitter:
        # TODO support different calibration
        raise QiskitError("Does not support TensoredMeasFitter yet.")
    else:
        raise QiskitError("Unknown fitter {}".format(fitter_cls))

    # the provided `qubit_list` would be used as the initial layout to
    # assure the consistent qubit mapping used in the main circuits.

    tmp_compile_config = copy.deepcopy(compile_config)
    tmp_compile_config["initial_layout"] = qubit_list
    t_meas_calibs_circuits = compiler.transpile(meas_calibs_circuits, backend,
                                                **backend_config,
                                                **tmp_compile_config)
    return t_meas_calibs_circuits, state_labels, circlabel
Пример #8
0
    def measured_qubits(self, qc):

        measure_list = []
        for op in qc.get_instructions('measure'):
            measure_list.append(op[1][0]._index)

        meas_calibs, state_labels = complete_meas_cal(qubit_list=measure_list)

        info_list = [meas_calibs, state_labels, measure_list]

        return info_list
Пример #9
0
    def initialize_meas_calibration(self, N_qubits, layout):
        """ Set up the confusion matrix needed for measurement error mitigation.
            This is basically just boilerplate code from the Ignis Github
            https://github.com/Qiskit/qiskit-ignis
        """
        if layout is None:
            cal_q = QuantumRegister(N_qubits)
            meas_cals, state_labels = complete_meas_cal(qr=cal_q)
        else:
            meas_cals, state_labels = complete_meas_cal(qubit_list=layout)

        # Run the calibration circuits with the device noise model
        backend = Aer.get_backend('qasm_simulator')
        job = execute(meas_cals,
                      backend=backend,
                      shots=10000,
                      noise_model=self.noise_model)
        cal_results = job.result()

        return CompleteMeasFitter(cal_results, state_labels).filter
Пример #10
0
def generate_error_mitigation_filter(q_list, noise_model):
    backend = get_sim_backend_from_name("qasm_simulator")
    qr = QuantumRegister(5)
    meas_cals, state_labels = complete_meas_cal(qubit_list=q_list, qr=qr)
    calibration_job = execute(meas_cals,
                              backend=backend,
                              shots=8192,
                              noise_model=noise_model)
    cal_results = calibration_job.result()
    meas_fitter = CompleteMeasFitter(cal_results, state_labels)
    em_filter = meas_fitter.filter
    return em_filter
def add_measurement_error_mitigation_to_qobj(qobj,
                                             fitter_cls,
                                             backend,
                                             backend_config=None,
                                             compile_config=None,
                                             run_config=None,
                                             new_qobj=False):
    """
        Args:
            qobj (QasmQobj): QasmQobj of the algorithm
            fitter_cls (callable): CompleteMeasFitter or TensoredMeasFitter
            backend (BaseBackend): backend instance
            backend_config (dict, optional): configuration for backend
            compile_config (dict, optional): configuration for compilation
            run_config (RunConfig, optional): configuration for running a circuit
            new_qobj (bool, optional): whether or not combine qobj to the input qobj

        Returns:
            QasmQobj: the Qobj with calibration circuits at the beginning
            list[str]: the state labels for build MeasFitter
            list[str]: the labels of the calibration circuits

        Raises:
            AquaError: when the fitter_cls is not recognizable.
        """

    circlabel = 'mcal'
    qubits = get_measured_qubits_from_qobj(qobj)

    if len(qubits) == 0:
        raise AquaError("The measured qubits can not be [].")

    if fitter_cls == CompleteMeasFitter:
        meas_calibs_circuits, state_labels = complete_meas_cal(
            qubit_list=qubits, circlabel=circlabel)
    elif fitter_cls == TensoredMeasFitter:
        # TODO support different calibration
        raise AquaError("Does not support TensoredMeasFitter yet.")
    else:
        raise AquaError("Unknown fitter {}".format(fitter_cls))

    cals_qobj = compile_circuits(meas_calibs_circuits, backend, backend_config,
                                 compile_config, run_config)

    if new_qobj:
        qobj = cals_qobj
    else:
        qobj.experiments[0:0] = cals_qobj.experiments

    return qobj, state_labels, circlabel
Пример #12
0
def measurement_error_mitigator(systemsize,
                                sim,
                                quantum_com_choice_results,
                                shots=8192):
    if sim == "noisy_qasm":
        backend, coupling_map, noise_model = quantum_com_choice_results[sim]

        qr = QuantumRegister(systemsize)
        meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
        print('Calibrating POVM Matrix')
        job = execute(meas_calibs,
                      backend=backend,
                      shots=shots,
                      noise_model=noise_model,
                      coupling_map=coupling_map)
        cal_results = job.result()
        meas_fitter = CompleteMeasFitter(cal_results,
                                         state_labels,
                                         circlabel='mcal')
        meas_filter = meas_fitter.filter
        print("Provider backend: ", backend)
        return meas_filter
    elif sim == "real":
        backend = quantum_com_choice_results[sim]

        qr = QuantumRegister(systemsize)
        meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
        print('Calibrating POVM Matrix')
        job = execute(meas_calibs, backend=backend, shots=shots)
        job_monitor(job, interval=2)
        cal_results = job.result()
        meas_fitter = CompleteMeasFitter(cal_results,
                                         state_labels,
                                         circlabel='mcal')
        meas_filter = meas_fitter.filter
        print("Provider backend: ", backend)
        return meas_filter
Пример #13
0
def build_measurement_error_mitigation_qobj(qubit_list,
                                            fitter_cls,
                                            backend,
                                            backend_config=None,
                                            compile_config=None,
                                            run_config=None):
    """
        Args:
            qubit_list (list[int]): list of ordered qubits used in the algorithm
            fitter_cls (callable): CompleteMeasFitter or TensoredMeasFitter
            backend (BaseBackend): backend instance
            backend_config (dict, optional): configuration for backend
            compile_config (dict, optional): configuration for compilation
            run_config (RunConfig, optional): configuration for running a circuit

        Returns:
            QasmQobj: the Qobj with calibration circuits at the beginning
            list[str]: the state labels for build MeasFitter
            list[str]: the labels of the calibration circuits

        Raises:
            AquaError: when the fitter_cls is not recognizable.
        """

    circlabel = 'mcal'

    if not qubit_list:
        raise AquaError("The measured qubit list can not be [].")

    if fitter_cls == CompleteMeasFitter:
        meas_calibs_circuits, state_labels = \
            complete_meas_cal(qubit_list=range(len(qubit_list)), circlabel=circlabel)
    elif fitter_cls == TensoredMeasFitter:
        # TODO support different calibration
        raise AquaError("Does not support TensoredMeasFitter yet.")
    else:
        raise AquaError("Unknown fitter {}".format(fitter_cls))

    # the provided `qubit_list` would be used as the initial layout to
    # assure the consistent qubit mapping used in the main circuits.

    tmp_compile_config = copy.deepcopy(compile_config)
    tmp_compile_config['initial_layout'] = qubit_list
    t_meas_calibs_circuits = compiler.transpile(meas_calibs_circuits, backend,
                                                **backend_config,
                                                **tmp_compile_config)
    cals_qobj = compiler.assemble(t_meas_calibs_circuits, backend,
                                  **run_config.to_dict())
    return cals_qobj, state_labels, circlabel
Пример #14
0
    def circuits(self, backend=None):
        if backend is None:
            backend = FakeValencia()
            sys.stderr.write('MeasurementErrorExperiment: Using FakeValencia for backend\n')
            
        qreg = QuantumRegister(len(self.physical_qubits))

        circuits, state_labels = complete_meas_cal(qubit_list=list(range(qreg.size)), qr=qreg, circlabel='mcal')
        for circuit, state_label in zip(circuits, state_labels):
            circuit.metadata = {
                'experiment_type': self._type,
                'physical_qubits': self.physical_qubits,
                'state_label': state_label
            }

        return circuits * self.circuits_per_state
Пример #15
0
def generate_calibration_circuits(noisy,
                                  simulator,
                                  max_depth,
                                  pc_cirq,
                                  plot=0):
    global shots
    num_qubits = len(noisy.properties().qubits)
    training, _ = complete_meas_cal(range(num_qubits))
    for i in range(1, max_depth):
        for _ in range(100 * num_qubits):
            training.append(random_gated_circuit(noisy, i, 0))

    experiments = transpile(training, backend=noisy)
    expected_all = execute(experiments, simulator, shots=shots).result()
    actual_all = execute(experiments, noisy, shots=shots).result()

    errors = []
    keys = get_hex_keys(num_qubits)
    for i in range(len(training)):
        expected = clean_result(expected_all.data(i)['counts'], keys, shots)
        actual = clean_result(actual_all.data(i)['counts'], keys, shots)
        errors.append([(expected[key] - actual[key])**2 for key in keys])

    errors = np.array(errors)
    pca = PCA(n_components=math.ceil(2**num_qubits))
    pca.fit(errors)

    test_cirq_indexes = []
    for i in range(num_qubits):
        get_proj = lambda e: np.dot(pca.components_[i], e) / np.linalg.norm(e)
        projs = [abs(get_proj(error)) for error in errors]

        start_len = len(test_cirq_indexes)
        pc_sorted = np.argsort(projs)
        i = -1
        while len(test_cirq_indexes) - start_len < pc_cirq:
            ind = pc_sorted[i]
            if ind not in test_cirq_indexes:
                test_cirq_indexes.append(ind)
            i -= 1

    if plot != 0:
        plot_errors(num_qubits, pca, pc_cirq, errors, test_cirq_indexes, plot)

    return [training[ind] for ind in test_cirq_indexes]
Пример #16
0
def meas_calibration_circ_execution(nqunits: int, shots: int, seed: int):
    """
    create measurement calibration circuits and simulates them with noise
    Args:
        nqunits (int): number of qubits to run the measurement calibration on
        shots (int): number of shots per simulation
        seed (int): the seed to use in the simulations

    Returns:
        list: list of Results of the measurement calibration simulations
        list: list of all the possible states with this amount of qubits
        dict: dictionary of results counts of bell circuit simulation with measurement errors
    """
    # define the circuits
    qr = qiskit.QuantumRegister(nqunits)
    meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='test')
    # define noise
    prob = 0.2
    error_meas = pauli_error([('X', prob), ('I', 1 - prob)])
    noise_model = NoiseModel()
    noise_model.add_all_qubit_quantum_error(error_meas, "measure")

    # run the circuits multiple times
    backend = qiskit.Aer.get_backend('qasm_simulator')
    cal_results = qiskit.execute(meas_calibs,
                                 backend=backend,
                                 shots=shots,
                                 noise_model=noise_model,
                                 seed_simulator=seed).result()

    # create bell state and get it's results
    qc = qiskit.QuantumCircuit(nqunits, nqunits)
    qc.h(0)
    qc.cx(0, 1)
    qc.cx(0, 2)
    qc.measure(qc.qregs[0], qc.cregs[0])

    bell_results = qiskit.execute(qc,
                                  backend=backend,
                                  shots=shots,
                                  noise_model=noise_model,
                                  seed_simulator=seed).result().get_counts()

    return cal_results, state_labels, bell_results
Пример #17
0
def get_correction_matrix(qpu, max_age, access_token, used_qubits):
    """Return a correction matrix for the given QPU whit the maximum age in minutes"""
    app.logger.info('Getting calibration matrix for QPU ' + qpu + ' with max age of ' + str(max_age) + ' minutes')

    # Check for existing calibration matrix
    existing_matrix = calibration_matrixes.get(qpu)
    if existing_matrix is not None:
        age = datetime.now() - existing_matrix['Date']
        app.logger.info('Calibration matrix for this QPU exists with age ' + str(age))
        if age.total_seconds() < max_age * 60:
            app.logger.info('Returning existing calibration matrix!')
            return existing_matrix['Calibration_Matrix']

    if access_token is None:
        app.logger.error('Unable to create new correction matrix without access key...')
        return None

    # Load account to enable execution of calibration circuits
    IBMQ.save_account(access_token, overwrite=True)
    IBMQ.load_account()

    provider = IBMQ.get_provider(group='open')
    backend = provider.get_backend(qpu)

    # Generate a calibration circuit for each state
    qr = qiskit.QuantumRegister(used_qubits)
    meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')

    # Execute each calibration circuit and store results
    app.logger.info('Executing ' + str(len(meas_calibs)) + ' circuits to create calibration matrix...')
    cal_results = []
    for circuit in meas_calibs:
        app.logger.info('Executing circuit ' + circuit.name)
        cal_results.append(execute_job(circuit, backend))

    # Generate calibration matrix out of measurement results
    meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
    app.logger.info('Calibration matrix:')
    app.logger.info(meas_fitter.cal_matrix)

    # Store calibration matrix for later reuse
    calibration_matrixes[qpu] = {"Date": datetime.now(), "Calibration_Matrix": meas_fitter.filter}
    return meas_fitter.filter
Пример #18
0
def build_measurement_error_mitigation_qobj(qubit_list,
                                            fitter_cls,
                                            backend,
                                            backend_config=None,
                                            compile_config=None,
                                            run_config=None):
    """
        Args:
            qubit_list (list[int]): list of qubits used in the algorithm
            fitter_cls (callable): CompleteMeasFitter or TensoredMeasFitter
            backend (BaseBackend): backend instance
            backend_config (dict, optional): configuration for backend
            compile_config (dict, optional): configuration for compilation
            run_config (RunConfig, optional): configuration for running a circuit

        Returns:
            QasmQobj: the Qobj with calibration circuits at the beginning
            list[str]: the state labels for build MeasFitter
            list[str]: the labels of the calibration circuits

        Raises:
            AquaError: when the fitter_cls is not recognizable.
        """

    circlabel = 'mcal'

    if not qubit_list:
        raise AquaError("The measured qubit list can not be [].")

    if fitter_cls == CompleteMeasFitter:
        meas_calibs_circuits, state_labels = \
            complete_meas_cal(qubit_list=qubit_list, circlabel=circlabel)
    elif fitter_cls == TensoredMeasFitter:
        # TODO support different calibration
        raise AquaError("Does not support TensoredMeasFitter yet.")
    else:
        raise AquaError("Unknown fitter {}".format(fitter_cls))

    cals_qobj = compile_circuits(meas_calibs_circuits, backend, backend_config,
                                 compile_config, run_config)

    return cals_qobj, state_labels, circlabel
Пример #19
0
def get_measurement_fitter(l, backend, device, shots):
    qb = QuantumRegister(l)
    qubit_list = list(range(l))
    meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list,
                                                  qr=qb,
                                                  circlabel='mcal')

    # Execute calibration circuits
    job = execute(meas_calibs,
                  backend=backend,
                  shots=shots,
                  noise_model=device.noise_model,
                  coupling_map=device.coupling_map,
                  basis_gates=device.basis_gates)
    cal_results = job.result()

    meas_fitter = CompleteMeasFitter(cal_results,
                                     state_labels,
                                     circlabel='mcal')
    #meas_filter = meas_fitter.filter
    #mitigated_results = meas_filter.apply(results)
    #mitigated_counts = mitigated_results.get_counts(0)
    return meas_fitter
Пример #20
0
    def apply_readout_correction(self, counts, qubit_list=None, **kwargs):
        if self.readout_correction_filter is None:

            for key in counts.keys():
                num_qubits = len(key)
                break

            if qubit_list is None or qubit_list == {}:
                qubit_list = [i for i in range(num_qubits)]

            qr = QuantumRegister(num_qubits)
            meas_cals, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qr)

            # Execute the calibration circuits
            job = self.execute_with_retries(meas_cals, self.n_samples)
            cal_results = job.result()

            # Make a calibration matrix
            meas_fitter = CompleteMeasFitter(cal_results, state_labels)
            # Create a measurement filter from the calibration matrix
            self.readout_correction_filter = meas_fitter.filter

        mitigated_counts = self.readout_correction_filter.apply(counts)
        return mitigated_counts
Пример #21
0
from qiskit.ignis.mitigation.measurement import (complete_meas_cal,
                                                 CompleteMeasFitter,
                                                 MeasurementFilter)
import qiskit.execute

# Generates noise model for qubits (percentages?).
aer_noise_model = noise.NoiseModel()
error = [[0.75, 0.25], [0.1, 0.9]]
for qb in range(5):
    readout_error = noise.errors.readout_error.ReadoutError(error)
    aer_noise_model.add_readout_error(readout_error, [qb])

# Generates measurement calibration circuits for running measurement error
#  mitigation.
q_register = QuantumRegister(5)
calibration_circuits, state_labels = complete_meas_cal(qubit_list=[2, 3, 4],
                                                       qr=q_register)

# Executes calibration circuits.
qasm_backend = Aer.get_backend("qasm_simulator")  # simulates circuit
job = qiskit.execute(calibration_circuits,
                     backend=qasm_backend,
                     shots=1000,
                     noise_model=aer_noise_model)
calibration_results = job.result()

# Makes calibration matrix.
measure_fitter = CompleteMeasFitter(calibration_results, state_labels)

# Makes a 3-qubit GHZ state (a particular entangled state, at least 3 qubits).
# 1. applies Hadamard, putting qubit into superposition
# 2. applies CX (CNOT), putting qubits into Bell state
Пример #22
0
            if label1[l][i] == 1 and label2[l][i] == 0:
                drive_idx = 1
                target_idx = 0 
                flip_drive = True
                backend_sim = qiskit.providers.aer.PulseSimulator()
#                experiments10 = cr_drive_experiments(drive_idx, target_idx, flip_drive)
               # compute frequencies from the Hamiltonian
#                qubit_lo_freq10 = two_qubit_model.hamiltonian.get_qubit_lo_from_drift()
                #assemble qobj 1
                rabifit_result = RabiFitter(result1, amps1, qubits, fit_p0 = [0.5,0.5,0.6,1.5])
                if l == trainidx[0] and i == 0:
                #if flag != 1:
                    # Generate the calibration circuits
                    qr = qiskit.QuantumRegister(2)
                    qubit_list = [0,1]
                    meas_calibs, state_labels = complete_meas_cal(qubit_list=qubit_list, qr=qr, circlabel='mcal')
                    job = qiskit.execute(meas_calibs, backend=backend, shots=10, noise_model=noise_model)
                    cal_results = job.result()
                    meas_fitter = CompleteMeasFitter(cal_results, state_labels)
#                    meas_fitter.cal_matrix = np.kron(meas_fitter.cal_matrices[1],meas_fitter.cal_matricesc[0])
                    meas_fitter.cal_matrix
                    plt.figure(figsize=(15, 10))
                    for qubit in qubits:
                        ax = plt.subplot(2, 2, qubit + 1)
                        #Xvmin, Xvmax = ax.xaxis.get_data_interval()
                        #Yvmin, Yvmax = ax.yaxis.get_data_interval()
                        #print(Xvmin, Xvmax,Yvmin, Yvmax)
                        Xvmin = multiplier * np.floor(0.1 / multiplier)
                        Xvmax = multiplier * np.ceil(0.5 / multiplier)
                        ax.set_xlim([Xvmin, Xvmax])
                        rabifit_result.plot(qubit, ax=ax)
Пример #23
0
                    print('\nOptimization level must be an integer between 0 and 3, inclusive. Higher levels generate more optimized circuits, at the expense of longer transpilation time.\n')
                    exit(1)
            except:
                print('\nOptimization level must be an integer between 0 and 3, inclusive. Higher levels generate more optimized circuits, at the expense of longer transpilation time.\n')
                exit(1)
        else:
            opt_level = 1
   
        U_f = get_U_f(func_in, n)
        list_y = []
        
        circuit = simon_program(U_f, n)
        circuit.measure(range(n), range(n))

        # Calibration Matrix
        meas_calibs, state_labels = complete_meas_cal(qubit_list=range(n), circlabel='mcal')
        cal_job = execute(meas_calibs, backend=backend, shots=8192)
        cal_results = cal_job.result()
        meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
        
        start = time.time()
        circuit = transpile(circuit, backend, optimization_level=opt_level)
        transpiletime = time.time() - start

        if trials*n > 2048:
            trial_list = [8192]*((trials*n)//2048) + [(4*trials*n)%8192]
        else:
            trial_list = [4*trials*n]
        
        job = []
        for t in trial_list:
Пример #24
0
    def test_ideal_meas_cal(self):
        """Test ideal execution, without noise."""
        for nq in self.nq_list:
            print("Testing %d qubit measurement calibration" % nq)

            for pattern_type in range(1, 2**nq):

                # Generate the quantum register according to the pattern
                qubits, weight = self.choose_calibration(nq, pattern_type)

                # Generate the calibration circuits
                meas_calibs, state_labels = \
                    complete_meas_cal(qubit_list=qubits,
                                      circlabel='test')

                # Perform an ideal execution on the generated circuits
                backend = Aer.get_backend('qasm_simulator')
                job = qiskit.execute(meas_calibs,
                                     backend=backend,
                                     shots=self.shots)
                cal_results = job.result()

                # Make a calibration matrix
                meas_cal = CompleteMeasFitter(cal_results,
                                              state_labels,
                                              circlabel='test')

                # Assert that the calibration matrix is equal to identity
                IdentityMatrix = np.identity(2**weight)
                self.assertListEqual(
                    meas_cal.cal_matrix.tolist(), IdentityMatrix.tolist(),
                    'Error: the calibration matrix is \
                                     not equal to identity')

                # Assert that the readout fidelity is equal to 1
                self.assertEqual(
                    meas_cal.readout_fidelity(), 1.0,
                    'Error: the average fidelity  \
                                 is not equal to 1')

                # Generate ideal (equally distributed) results
                results_dict, results_list = \
                    self.generate_ideal_results(state_labels, weight)

                # Output the filter
                meas_filter = meas_cal.filter

                # Apply the calibration matrix to results
                # in list and dict forms using different methods
                results_dict_1 = meas_filter.apply(results_dict,
                                                   method='least_squares')
                results_dict_0 = meas_filter.apply(results_dict,
                                                   method='pseudo_inverse')
                results_list_1 = meas_filter.apply(results_list,
                                                   method='least_squares')
                results_list_0 = meas_filter.apply(results_list,
                                                   method='pseudo_inverse')

                # Assert that the results are equally distributed
                self.assertListEqual(results_list, results_list_0.tolist())
                self.assertListEqual(results_list,
                                     np.round(results_list_1).tolist())
                self.assertDictEqual(results_dict, results_dict_0)
                round_results = {}
                for key, val in results_dict_1.items():
                    round_results[key] = np.round(val)
                self.assertDictEqual(results_dict, round_results)
Пример #25
0
def all_methods_data(interested_qubits,
                     backend,
                     itr,
                     QDT_correlated,
                     shots_per_point=1024,
                     file_address=''):
    """Collect data for our method, Qiskit method, QDT, and standard Bayesian.

    Args:
      interested_qubits:
        an array of ints. REMEBER TO FOLLOW THE ORDER [LAST QUBIT, ..., FIRST QUBIT]
      backend:
        backend from provider.get_backend().
      itr:
        number of iterations of job submission in our method only.
      QDT_correlated:
        True if want qubits corrlected in QDT method.
      file_address:
        file address, string ends with '/' if not empty

    Returns:
      None
    """
    with open(file_address + 'interested_qubits.csv', mode='w',
              newline='') as sgm:
        param_writer = csv.writer(sgm,
                                  delimiter=',',
                                  quotechar='"',
                                  quoting=csv.QUOTE_MINIMAL)
        param_writer.writerow(interested_qubits)

    # Record data for filters (ourmethod)
    print('Our method')
    collect_filter_data(backend,
                        itr=itr,
                        shots=8192,
                        if_monitor_job=True,
                        if_write=True,
                        file_address=file_address)

    # Qiskit Method
    print('Qiskit Method')
    qr = QuantumRegister(len(interested_qubits))
    meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
    for i in range(len(meas_calibs)):
        meas_calibs[i] = transpile(meas_calibs[i],
                                   backend,
                                   initial_layout=interested_qubits[::-1])

    job = execute(meas_calibs,
                  backend=backend,
                  shots=8192,
                  optimization_level=0)
    job_monitor(job)

    cal_results = job.result()
    meas_fitter = CompleteMeasFitter(cal_results,
                                     state_labels,
                                     circlabel='mcal')
    meas_filter = meas_fitter.filter
    cal_matrix = meas_fitter.cal_matrix

    with open(file_address + 'cal_matrix.csv', mode='w', newline='') as sgm:
        param_writer = csv.writer(sgm,
                                  delimiter=',',
                                  quotechar='"',
                                  quoting=csv.QUOTE_MINIMAL)
        for row in cal_matrix:
            param_writer.writerow(row)
    with open(file_address + 'state_labels.csv', mode='w', newline='') as sgm:
        param_writer = csv.writer(sgm,
                                  delimiter=',',
                                  quotechar='"',
                                  quoting=csv.QUOTE_MINIMAL)
        param_writer.writerow(state_labels)

    # QDT
    print('QDT, correlation = ', QDT_correlated)
    if QDT_correlated:
        qdt_qubit_indices = interested_qubits
        qdt_probe_kets = povmtools.pauli_probe_eigenkets
        qdt_calibration_circuits = detector_tomography_circuits(
            qdt_qubit_indices, qdt_probe_kets)

        print('Number of Circuits needed is ', len(qdt_calibration_circuits))

        # We then execute them on backend prepared earlier.
        shots_number = 8192

        # Perform a noisy simulation
        job = execute(qdt_calibration_circuits,
                      backend=backend,
                      shots=shots_number,
                      optimization_level=0)
        job_monitor(job)
        result = job.result()

        dtf = DetectorTomographyFitter()
        calibration_setup = QDTCalibrationSetup.from_qiskit_results(
            [result], qdt_probe_kets)
        ml_povm_estimator = dtf.get_maximum_likelihood_povm_estimator(
            calibration_setup)

        mitigator = QDTErrorMitigator()
        mitigator.prepare_mitigator(ml_povm_estimator)
        trans_mat = mitigator.transition_matrix

        with open(file_address + 'trans_matrix.csv', mode='w',
                  newline='') as sgm:
            param_writer = csv.writer(sgm,
                                      delimiter=',',
                                      quotechar='"',
                                      quoting=csv.QUOTE_MINIMAL)
            for row in trans_mat:
                param_writer.writerow(row)
    else:
        for q in interested_qubits:
            qdt_qubit_indices = [q]
            qdt_probe_kets = povmtools.pauli_probe_eigenkets
            qdt_calibration_circuits = detector_tomography_circuits(
                qdt_qubit_indices, qdt_probe_kets)

            print('Number of Circuits needed is ',
                  len(qdt_calibration_circuits))

            # We then execute them on backend prepared earlier.
            shots_number = 8192

            # Perform a noisy simulation
            job = execute(qdt_calibration_circuits,
                          backend=backend,
                          shots=shots_number,
                          optimization_level=0)
            job_monitor(job)
            result = job.result()

            # Create Mitigator

            dtf = DetectorTomographyFitter()
            calibration_setup = QDTCalibrationSetup.from_qiskit_results(
                [result], qdt_probe_kets)
            ml_povm_estimator = dtf.get_maximum_likelihood_povm_estimator(
                calibration_setup)

            mitigator = QDTErrorMitigator()
            mitigator.prepare_mitigator(ml_povm_estimator)

            trans_mat = mitigator.transition_matrix

            with open(file_address + 'trans_matrix' + str(q) + '.csv',
                      mode='w',
                      newline='') as sgm:
                param_writer = csv.writer(sgm,
                                          delimiter=',',
                                          quotechar='"',
                                          quoting=csv.QUOTE_MINIMAL)
                for row in trans_mat:
                    param_writer.writerow(row)

    # Data for Standard Bayesian
    # Read data to for measurement error while input is |0>
    print('Write data for standard Bayesian')
    prop_dict = backend.properties().to_dict()
    with open(file_address + 'given_params.csv', mode='w', newline='') as sgm:
        param_writer = csv.writer(sgm,
                                  delimiter=',',
                                  quotechar='"',
                                  quoting=csv.QUOTE_MINIMAL)
        for q in interested_qubits:
            p0m0 = 1 - prop_dict['qubits'][q][5]['value']
            if p0m0 == 1 or p0m0 < 0.7:
                p0m0 = 0.9
            p1m1 = 1 - prop_dict['qubits'][q][4]['value']
            if p1m1 == 1 or p1m1 < 0.7:
                p1m1 = 0.9
            param_writer.writerow([p0m0, p1m1])

    with open(file_address + 'Filter_data.csv', mode='r') as measfile:
        reader = csv.reader(measfile)
        cali01 = np.asarray([row for row in reader][0])

    Data = cali01
    for q in interested_qubits:
        y = getData0(Data, itr * int(8192 / shots_per_point), q)
        with open(file_address + 'Qubit{}.csv'.format(q), mode='w',
                  newline='') as sgr:
            read_writer = csv.writer(sgr,
                                     delimiter=',',
                                     quotechar='"',
                                     quoting=csv.QUOTE_MINIMAL)
            read_writer.writerow(['x', 'y'])
            for i in range(len(y)):
                read_writer.writerow([0.5, y[i]])
Пример #26
0
    MeasurementFilter)

provider = IBMQ.load_account()

backend = provider.get_backend('ibmqx2')  # calibrate using real hardware
layout = [2, 3, 0, 4]
chip_qubits = 5

# Transpiled circuit for the real hardware
qc_qa_cx = transpile(qc, backend=backend, initial_layout=layout)

# The next step is to create the extra circuits used to mitigate the readout errors<sup>[[3]](#readouterr)</sup>.

# In[18]:

meas_cals, state_labels = complete_meas_cal(qubit_list=layout,
                                            qr=QuantumRegister(chip_qubits))
qcs = meas_cals + [qc_qa_cx]

job = backend.run(qcs, shots=10)

# The following plot<sup>[[5]](#tridi)</sup>, shows the results from running the circuit above on real hardware for $10$ different initial states. The $x$-axis represents the angle $\theta$ defining the initial state in each case. The results where obtained after mitigating the readout error and then extrapolating the errors arising during the run of the circuit from the results with the circuits with $1$, $3$ and $5$ CNOTs.
#
# <img src="images/norm_public.png">
#
# Compare to the results without error mitigation nor extrapolation from the CNOTs<sup>[5](#tridi)</sup>.
#
# <img src="images/noerrmit_public.png">

# ## 8. Problems<a id='problems'></a>

# ##### Real hardware:
    register_token()

    qubits = 4

    circuit = QuantumCircuit(qubits, qubits)
    circuit.h(0)
    circuit.cx(0, 1)
    circuit.cx(1, 2)
    circuit.measure([0, 1, 2, 3], [0, 1, 2, 3])
    circuit.draw(output='mpl')

    simulator = Aer.get_backend('qasm_simulator')
    sim_result = execute(circuit, backend=simulator, shots=1024).result()

    plot_histogram(sim_result.get_counts(circuit))

    IBMQ.load_account()
    provider = IBMQ.get_provider(hub='ibm-q')
    device = provider.get_backend('ibmqx2')

    job = execute(circuit, backend=device, shots=1024)
    print("Job ID:", job.job_id())

    job_monitor(job)

    device_result = job.result()
    plot_histogram(device_result.get_counts(circuit))

    cal_circuits, state_labels = complete_meas_cal(
        qr=circuit.qregs[0], circlabel='measerrormitigationcal')
    cal_circuits[2].draw(output='mpl')
Пример #28
0
    def test_meas_cal_on_circuit(self):
        """Test an execution on a circuit."""
        print("Testing measurement calibration on a circuit")

        # Choose 3 qubits
        q1 = 1
        q2 = 2
        q3 = 3

        # Generate the quantum register according to the pattern
        qr = qiskit.QuantumRegister(5)
        # Generate the calibration circuits
        meas_calibs, state_labels = \
            complete_meas_cal(qubit_list=[1, 2, 3],
                              qr=qr)

        # Run the calibration circuits
        backend = Aer.get_backend('qasm_simulator')
        job = qiskit.execute(meas_calibs, backend=backend, shots=self.shots)
        cal_results = job.result()

        # Make a calibration matrix
        meas_cal = CompleteMeasFitter(cal_results, state_labels)
        # Calculate the fidelity
        fidelity = meas_cal.readout_fidelity()

        # Make a 3Q GHZ state
        cr = ClassicalRegister(3)
        ghz = QuantumCircuit(qr, cr)
        ghz.h(qr[q1])
        ghz.cx(qr[q1], qr[q2])
        ghz.cx(qr[q2], qr[q3])
        ghz.measure(qr[q1], cr[0])
        ghz.measure(qr[q2], cr[1])
        ghz.measure(qr[q3], cr[2])

        job = qiskit.execute([ghz], backend=backend, shots=self.shots)
        results = job.result()

        # Predicted equally distributed results
        predicted_results = {'000': 0.5, '111': 0.5}

        meas_filter = meas_cal.filter

        # Calculate the results after mitigation
        output_results_pseudo_inverse = meas_filter.apply(
            results, method='pseudo_inverse').get_counts(0)
        output_results_least_square = meas_filter.apply(
            results, method='least_squares').get_counts(0)

        # Compare with expected fidelity and expected results
        self.assertAlmostEqual(fidelity, 1.0)
        self.assertAlmostEqual(output_results_pseudo_inverse['000'] /
                               self.shots,
                               predicted_results['000'],
                               places=1)

        self.assertAlmostEqual(output_results_least_square['000'] / self.shots,
                               predicted_results['000'],
                               places=1)

        self.assertAlmostEqual(output_results_pseudo_inverse['111'] /
                               self.shots,
                               predicted_results['111'],
                               places=1)

        self.assertAlmostEqual(output_results_least_square['111'] / self.shots,
                               predicted_results['111'],
                               places=1)
def create_qpt_experiment(target_circuits: List[QuantumCircuit],
                          control: int,
                          target: int,
                          backend: BaseBackend,
                          mit_readout: bool = True,
                          inst_map: InstructionScheduleMap = None,
                          basis_gate: List[str] = None,
                          sanity_check: bool = False,
                          shots: int = 2048,
                          return_schedule=False)\
        -> Tuple[Union[PulseQobj, Schedule], List[List[QuantumCircuit]], List[str]]:
    """ Create circuits and schedules for QPT.

    Args:
        target_circuits: List of target circuits for QPT experiment.
        control: index of control qubit.
        target: index of target qubit.
        backend: Target quantum system.
        mit_readout: If use readout mitigation.
        inst_map: instruction mapping object.
        basis_gate: basis gates.
        sanity_check: check memory slot mapping of generated qobj.
        shots: Number of shots.
        return_schedule: set ``True`` when return schedule object instead of qobj.

    Returns:
        Qobj, Schedules, Quantum circuits, Measurement labels

    Additional Information:
        Bit ordering is little endian as a convention of computational science community,
        as the rest of qiskit does. When you measure the CR process tomography of q0 and q1,
        you will observe XZ (ZX) interaction when q0 (q1) is control qubit.
    """
    qubits = sorted([control, target])

    back_config = backend.configuration()
    back_defaults = backend.defaults()

    if inst_map is None:
        inst_map = back_defaults.circuit_instruction_map

    if basis_gate is None:
        basis_gate = back_config.basis_gates

    if isinstance(target_circuits, QuantumCircuit):
        target_circuits = [target_circuits]

    exp_circs = []

    # create the measurement circuits for error mitigation, optional
    qr = target_circuits[0].qregs[0]
    if mit_readout:
        meas_circs, meas_labels = mit.complete_meas_cal(qubit_list=qubits,
                                                        qr=qr,
                                                        circlabel='mcal')
        exp_circs.extend(meas_circs)
    else:
        meas_labels = []

    # create qpt circuit
    qpt_qcs_list = []
    for target_circuit in target_circuits:
        # extract quantum registers from target circuit
        qr = target_circuit.qregs[0]
        qr0 = qr[qubits[0]]
        qr1 = qr[qubits[1]]
        qpt_qcs = tomo.process_tomography_circuits(target_circuit,
                                                   measured_qubits=[qr0, qr1])
        qpt_qcs_list.append(qpt_qcs)
        exp_circs.extend(qpt_qcs)

    # transpile
    exp_circs = qiskit.transpile(exp_circs, backend, basis_gates=basis_gate)

    # schedule with measure alignment
    exp_scheds = align_measures(qiskit.schedule(exp_circs,
                                                backend=backend,
                                                inst_map=inst_map),
                                inst_map=inst_map)

    if return_schedule:
        return exp_scheds, qpt_qcs_list, meas_labels

    # assemble pulse qobj
    qobj = qiskit.assemble(exp_scheds,
                           backend=backend,
                           meas_level=2,
                           shots=shots)

    # sanity check
    if sanity_check:
        for experiment in qobj.experiments:
            for inst in experiment.instructions:
                if inst.name == 'acquire':
                    memory_slot_map = inst.memory_slot
                    if memory_slot_map[qubits[0]] != __reserved_registers[0] or \
                            memory_slot_map[qubits[0]] != __reserved_registers[1]:
                        warnings.warn('Wrong memory slots are assigned. '
                                      'QPT fitter may return invalid result.')

        assert len(qobj.experiments) <= back_config.max_experiments

    return qobj, qpt_qcs_list, meas_labels
def parametri(N):   
    res =[ ele for ele in itertools.product([0,1,2,3], repeat = N)]
    return res
par=parametri(n)
def merX(kpom,i):
    kpom.h(i)
    return kpom

def merY(kpom,i):
    kpom.s(i)
    kpom.h(i)
    return kpom
#Pravim matricu M
qr = QuantumRegister(5)
meas_calibs, state_labels = complete_meas_cal(qr=qr, circlabel='mcal')
noise_model = get_noise(0.1)
backend = Aer.get_backend('qasm_simulator')
job = execute(meas_calibs, backend=backend, shots=1000, noise_model=noise_model)
cal_results = job.result()
meas_fitter = CompleteMeasFitter(cal_results, state_labels, circlabel='mcal')
M=meas_fitter.cal_matrix
#Pravim Kolo
for i in range(4**n):
    q.append(QuantumRegister(n))
    c.append(ClassicalRegister(n))
    wKolo.append(QuantumCircuit(q[i],c[i]))
    #ovde stavljamo gejtove
    wKolo[i].x(q[i][1])
    wKolo[i].ry(1.37,q[i][3])
    wKolo[i].cx(q[i][3],q[i][1])