Esempio n. 1
0
    def run(self, qobj):
        """Main job in simulator"""
        if HAS_AER:
            if qobj.type == "PULSE":
                from qiskit.providers.aer.pulse import PulseSystemModel

                system_model = PulseSystemModel.from_backend(self)
                sim = aer.Aer.get_backend("pulse_simulator")
                job = sim.run(qobj, system_model)
            else:
                sim = aer.Aer.get_backend("qasm_simulator")
                if self.properties():
                    from qiskit.providers.aer.noise import NoiseModel

                    noise_model = NoiseModel.from_backend(self, warnings=False)
                    job = sim.run(qobj, noise_model=noise_model)
                else:
                    job = sim.run(qobj)

            out_job = fake_job.FakeLegacyJob(self, job.job_id, None)
            out_job._future = job._future
        else:
            if qobj.type == "PULSE":
                raise QiskitError("Unable to run pulse schedules without " "qiskit-aer installed")
            warnings.warn("Aer not found using BasicAer and no noise", RuntimeWarning)

            def run_job():
                sim = basicaer.BasicAer.get_backend("qasm_simulator")
                return sim.run(qobj).result()

            job_id = uuid.uuid4()
            out_job = fake_job.FakeLegacyJob(self, job_id, run_job)
            out_job.submit()
        return out_job
 def run(self, qobj):
     """Main job in simulator"""
     if HAS_AER:
         if qobj.type == 'PULSE':
             from qiskit.providers.aer.pulse import PulseSystemModel
             system_model = PulseSystemModel.from_backend(self)
             sim = Aer.get_backend('pulse_simulator')
             job = sim.run(qobj, system_model)
         else:
             sim = Aer.get_backend('qasm_simulator')
             if self.properties():
                 from qiskit.providers.aer.noise import NoiseModel
                 noise_model = NoiseModel.from_backend(self, warnings=False)
                 job = sim.run(qobj, noise_model=noise_model)
             else:
                 job = sim.run(qobj)
     else:
         if qobj.type == 'PULSE':
             raise QiskitError("Unable to run pulse schedules without "
                               "qiskit-aer installed")
         warnings.warn("Aer not found using BasicAer and no noise",
                       RuntimeWarning)
         sim = BasicAer.get_backend('qasm_simulator')
         job = sim.run(qobj)
     return job
 def test_simulator_with_noise_model(self, backend):
     """Test using simulator with a noise model."""
     noise_model = NoiseModel.from_backend(backend)
     result = self.sim_backend.run(
         transpile(ReferenceCircuits.bell(), backend=self.sim_backend),
         noise_model=noise_model).result()
     self.assertTrue(result)
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)
Esempio n. 5
0
def simulate_qc(qc, shots=1000, bname='qasm_simulator', noise=None):
    '''simulates a quantum circuit, and
       returns a dictionary with the keys being
       the binary representation of the measurement
       and the values being the number of counts that
       measurement recieved. The total number of counts
       equals shots
    '''

    if noise == None:
        job = execute(qc, Aer.get_backend(bname), shots=shots)
    else:
        backend = noise()
        noise_model = NoiseModel.from_backend(backend)
        coupling_map = backend.configuration().coupling_map
        basis_gates = noise_model.basis_gates
        job = execute(qc,
                      Aer.get_backend(bname),
                      shots=shots,
                      coupling_map=coupling_map,
                      basis_gates=basis_gates,
                      noise_model=noise_model)

    result = job.result()
    counts = result.get_counts(qc)
    return counts
    def test_zz(self):
        """
        Run the simulator with unitary noise.
        Then verify that the calculated ZZ matches the zz parameter.
        """

        num_of_gates = np.arange(0, 60, 10)
        gate_time = 0.1
        qubits = [0]
        spectators = [1]

        # Generate experiments
        circs, xdata, osc_freq = zz_circuits(num_of_gates,
                                             gate_time,
                                             qubits,
                                             spectators,
                                             nosc=2)

        # Set the simulator with ZZ
        zz_expected = 0.1
        zz_unitary = np.eye(4, dtype=complex)
        zz_unitary[3, 3] = np.exp(1j * 2 * np.pi * zz_expected * gate_time)
        error = coherent_unitary_error(zz_unitary)
        noise_model = NoiseModel()
        noise_model.add_nonlocal_quantum_error(error, 'id', [0], [0, 1])

        # Run the simulator
        backend = qiskit.Aer.get_backend('qasm_simulator')
        shots = 100
        # For demonstration purposes split the execution into two jobs
        backend_result = qiskit.execute(circs,
                                        backend,
                                        shots=shots,
                                        noise_model=noise_model).result()

        initial_a = 0.5
        initial_c = 0.5
        initial_f = osc_freq
        initial_phi = 0.0

        ZZFitter(backend_result,
                 xdata,
                 qubits,
                 spectators,
                 fit_p0=[initial_a, initial_f, initial_phi, initial_c],
                 fit_bounds=([-0.5, 0, -np.pi,
                              -0.5], [1.5, 2 * osc_freq, np.pi, 1.5]))
def zz_circuit_execution() -> Tuple[qiskit.result.Result,
                                    np.array,
                                    List[int],
                                    List[int],
                                    float,
                                    float]:
    """
    Create ZZ circuits and simulate them.

    Returns:
        *   Backend result.
        *   xdata.
        *   Qubits for the ZZ measurement.
        *   Spectators.
        *   ZZ parameter that used in the circuit creation
        *   Frequency.
    """

    num_of_gates = np.arange(0, 60, 10)
    gate_time = 0.1
    qubits = [0]
    spectators = [1]

    # Generate experiments
    circs, xdata, omega = zz_circuits(num_of_gates,
                                      gate_time, qubits,
                                      spectators, nosc=2)

    # Set the simulator with ZZ
    zz_value = 0.1
    zz_unitary = np.eye(4, dtype=complex)
    zz_unitary[3, 3] = np.exp(1j*2*np.pi*zz_value*gate_time)
    error = coherent_unitary_error(zz_unitary)
    noise_model = NoiseModel()
    noise_model.add_nonlocal_quantum_error(error, 'id', [0], [0, 1])

    # Run the simulator
    backend = qiskit.Aer.get_backend('qasm_simulator')
    shots = 100

    backend_result = qiskit.execute(circs, backend,
                                    shots=shots,
                                    seed_simulator=SEED,
                                    noise_model=noise_model,
                                    optimization_level=0).result()

    return backend_result, xdata, qubits, spectators, zz_value, omega
Esempio n. 8
0
def generate_data_noisy():
    """generaete a noisy data pickle"""
    seed_accreditation = 1435754
    seed_simulator = 877924554

    accsys = make_accred_system(seed=seed_accreditation)
    simulator = qiskit.Aer.get_backend('qasm_simulator')
    noise_model = NoiseModel()
    p1q = 0.002
    noise_model.add_all_qubit_quantum_error(depolarizing_error(p1q, 1), 'u1')
    noise_model.add_all_qubit_quantum_error(depolarizing_error(p1q, 1), 'u2')
    noise_model.add_all_qubit_quantum_error(depolarizing_error(p1q, 1), 'u3')
    p2q = 0.02
    noise_model.add_all_qubit_quantum_error(depolarizing_error(p2q, 2), 'cx')

    basis_gates = ['u1', 'u2', 'u3', 'cx']
    # Number of runs
    d = 20
    v = 10

    test_3 = AccreditationFitter()
    all_results = []
    all_postp_list = []
    all_v_zero = []
    all_acc = []
    for run in range(d):
        print([run, d])
        # Create target and trap circuits with random Pauli gates
        circuit_list, postp_list, v_zero = accsys.generate_circuits(v)
        # Implement all these circuits with noise
        job = execute(circuit_list,
                      simulator,
                      noise_model=noise_model,
                      basis_gates=basis_gates,
                      shots=1,
                      seed_simulator=seed_simulator + run)
        all_results.append(job.result())
        all_postp_list.append(postp_list)
        all_v_zero.append(v_zero)
        # Post-process the outputs and see if the protocol accepts
        test_3.single_protocol_run(job.result(), postp_list, v_zero)
        all_acc.append(test_3.flag)

    theta = 5 / 100
    test_3.bound_variation_distance(theta)
    bound = test_3.bound
    outputdict = {
        'all_results': all_results,
        'all_postp_list': all_postp_list,
        'all_v_zero': all_v_zero,
        'all_acc': all_acc,
        'theta': theta,
        'bound': bound
    }
    f = open('accred_noisy_results.pkl', 'wb')
    pickle.dump(outputdict, f)
    f.close()
Esempio n. 9
0
    def test_noise_models_not_equal(self):
        """Test two noise models are not equal"""
        error = pauli_error([['X', 1]])

        model1 = NoiseModel()
        model1.add_all_qubit_quantum_error(error, ['u3'], False)

        model2 = NoiseModel(basis_gates=['u3', 'cx'])
        model2.add_all_qubit_quantum_error(error, ['u3'], False)
Esempio n. 10
0
    def test_noise_model_from_invalid_t2_backend(self):
        """Test if issue user warning when creating a noise model from invalid t2 backend"""
        from qiskit.providers.models.backendproperties import BackendProperties, Gate, Nduv
        import datetime

        t1_ns, invalid_t2_ns = 75_1000, 200_1000
        u3_time_ns = 320
        frequency = 4919.96800692

        class InvalidT2Fake1Q(mock.FakeBackend):
            def __init__(self):
                mock_time = datetime.datetime.now()
                dt = 1.3333
                configuration = BackendProperties(
                    backend_name="invalid_t2",
                    backend_version="0.0.0",
                    num_qubits=1,
                    basis_gates=["u3"],
                    qubits=[
                        [
                            Nduv(date=mock_time, name="T1", unit="µs", value=t1_ns/1000),
                            Nduv(date=mock_time, name="T2", unit="µs", value=invalid_t2_ns/1000),
                            Nduv(date=mock_time, name="frequency", unit="MHz", value=frequency),
                        ],
                    ],
                    gates=[
                        Gate(
                            gate="u3",
                            name="u3_0",
                            qubits=[0],
                            parameters=[
                                Nduv(date=mock_time, name="gate_error", unit="", value=0.001),
                                Nduv(date=mock_time, name="gate_length", unit="ns", value=u3_time_ns),
                            ],
                        ),
                    ],
                    last_update_date=mock_time,
                    general=[],
                )
                super().__init__(configuration)

            def defaults(self):
                """defaults == configuration"""
                return self._configuration

            def properties(self):
                """properties == configuration"""
                return self._configuration

        backend = InvalidT2Fake1Q()
        with self.assertWarns(UserWarning):
            noise_model = NoiseModel.from_backend(backend, gate_error=False)
            expected = thermal_relaxation_error(
                t1=t1_ns,
                t2=2*t1_ns,
                time=u3_time_ns,
                excited_state_population=_excited_population(frequency, temperature=0)
            )
            self.assertEqual(expected, noise_model._local_quantum_errors["u3"][(0, )])
def t2_star_noise_model(gate_time=0.1, t=[70.5, 85.0, 80.0, 90.5, 77.5]):
    """
    Return a NoiseModel object for T2*.
    
    Parameters
        - gate_time: gate time (in microseconds) for a single-qubit gate
        - t: simulated times (in microseconds) for a set of five qubits 
    """

    t2_star_noise_model = NoiseModel()
    error = [0 for i in range(5)]

    for i in range(5):
        error[i] = thermal_relaxation_error(np.inf, t[i], gate_time, 0.5)
        t2_star_noise_model.add_quantum_error(error[i], 'id', [i])

    return t2_star_noise_model
Esempio n. 12
0
 def test_option_order_basis_gates(self, method):
     """Test order of setting method and noise model gives same basis gates"""
     noise_model = NoiseModel(basis_gates=['id', 'sx', 'x', 'cx'])
     sim1 = self.backend(method=method, noise_model=noise_model)
     basis_gates1 = sim1.configuration().basis_gates
     sim2 = self.backend(noise_model=noise_model, method=method)
     basis_gates2 = sim2.configuration().basis_gates
     self.assertEqual(sorted(basis_gates1), sorted(basis_gates2))
Esempio n. 13
0
def f_average(params, shots = NB_SHOTS, noise_model = NoiseModel()):
    """  estimate of the fidelity"""
    if np.ndim(params) >1 : res = np.array([f_average(p, shots=shots, noise_model=noise_model) for p in params])
    else: 
        res = qcirc.F(params, shots = shots, noise_model=noise_model)
        print(res)
        res = 1 - np.atleast_1d(res)
    return res
Esempio n. 14
0
    def test_auto_method_nonclifford_circuit_and_kraus_noise(self):
        """Test statevector method is used for Clifford circuit"""
        # Noise Model
        error = amplitude_damping_error(0.5)
        noise_model = NoiseModel()
        noise_model.add_all_qubit_quantum_error(
            error, ['id', 'x', 'y', 'z', 'h', 's', 'sdg'])
        backend = self.backend(noise_model=noise_model)

        # Test circuits
        shots = 100
        circuits = ref_non_clifford.ccx_gate_circuits_deterministic(
            final_measure=True)
        result = backend.run(circuits, shots=shots).result()
        success = getattr(result, 'success', False)
        self.compare_result_metadata(result, circuits, 'method',
                                     "density_matrix")
Esempio n. 15
0
    def test_auto_method_clifford_circuits_and_unitary_noise(self):
        """Test statevector method is used for Clifford circuit"""
        # Noise Model
        error = mixed_unitary_error([(Pauli('XX').to_matrix(), 0.5),
                                     (Pauli('II').to_matrix(), 0.5)])
        noise_model = NoiseModel()
        noise_model.add_all_qubit_quantum_error(error, ['cz', 'cx'])
        backend = self.backend(noise_model=noise_model)

        # Test circuits
        shots = 100
        circuits = ref_2q_clifford.cz_gate_circuits_deterministic(
            final_measure=True)
        result = backend.run(circuits, shots=shots).result()
        success = getattr(result, 'success', False)
        self.compare_result_metadata(result, circuits, 'method',
                                     "density_matrix")
    def _test_noise_model(self, backend_properties: BackendProperties):
        noise_model: NoiseModel = NoiseModel()
        for qubits, error in basic_device_readout_errors(backend_properties):
            noise_model.add_readout_error(error, qubits)
        for name, qubits, error in basic_device_gate_errors(properties=backend_properties):
            noise_model.add_quantum_error(error, name, qubits)

        LOG.info(noise_model)
    def test_measure_sampling_with_readouterror(self):
        """Test QasmSimulator measure with deterministic counts with sampling and readout-error"""
        readout_error = [0.01, 0.1]
        noise_model = NoiseModel()
        readout = [[1.0 - readout_error[0], readout_error[0]],
                   [readout_error[1], 1.0 - readout_error[1]]]
        noise_model.add_all_qubit_readout_error(ReadoutError(readout))

        shots = 1000
        circuits = ref_measure.measure_circuits_deterministic(
            allow_sampling=True)
        targets = ref_measure.measure_counts_deterministic(shots)
        qobj = assemble(circuits, self.SIMULATOR, shots=shots)
        result = self.SIMULATOR.run(qobj,
                                    noise_model=noise_model,
                                    **self.BACKEND_OPTS).result()
        self.assertSuccess(result)
Esempio n. 18
0
    def __init__(self,
                 make_circuit,
                 nbqbits,
                 nbparams,
                 backend,
                 cbuilder=qkBuilder,
                 noise_model=None,
                 coupling_map=None,
                 noise_backend=None,
                 save_path=None):
        super().__init__(make_circuit, nbqbits, nbparams, cbuilder)

        self.save_path = save_path

        if isinstance(backend, Backends):
            self.__backend__ = backend
            self.backend = self.__backend__.backends
            self.noise_model = self.__backend__.noise_models
            self.coupling_map = self.__backend__.coupling_maps
            self.job_limit = backend.job_limit

        else:
            backend = backend if isinstance(backend, list) else [backend]
            try:
                self.job_limit = min(map(lambda x: x.job_limit(), backend))
            except AttributeError:
                self.job_limit = None
            self.backend = cycle(backend)

            if noise_model is not None and noise_backend is not None:
                raise ValueError(
                    "Only one between 'noise_model' and 'noise_backend' can \
be passed to the constructor")

            if isinstance(noise_model, list):
                self.noise_model = cycle(noise_model)
            else:
                self.noise_model = cycle([noise_model])

            if isinstance(coupling_map, list):
                self.coupling_map = cycle(coupling_map)
            else:
                self.coupling_map = cycle([coupling_map])

            if noise_backend is not None:
                _noise_back = noise_backend
                if not isinstance(noise_backend, list):
                    _noise_back = [noise_backend]

                self.noise_model = cycle([
                    NoiseModel.from_backend(_backend)
                    for _backend in _noise_back
                ])
                self.coupling_map = cycle([
                    _backend.configuration().coupling_map
                    for _backend in _noise_back
                ])
Esempio n. 19
0
    def get_noise_model(self, name):
        if name in IBMQ_NAMES:
            backend = self.provider.get_backend(name)
            self.properties = backend.properties()
            noise_model = NoiseModel.from_backend(backend)
        else:
            noise_model = None

        return noise_model
Esempio n. 20
0
    def test_nonlocal_quantum_errors(self):
        qr = QuantumRegister(3, 'qr')
        circuit = QuantumCircuit(qr)
        circuit.x(qr[0])
        circuit.x(qr[2])

        error_x = pauli_error([('Y', 0.25), ('I', 0.75)])
        noise_model = NoiseModel()
        noise_model.add_nonlocal_quantum_error(error_x, 'x', [0], [1])

        target_circuit = QuantumCircuit(qr)
        target_circuit.x(qr[0])
        target_circuit.append(error_x.to_instruction(), [qr[1]])
        target_circuit.x(qr[2])

        result_circuit = insert_noise(circuit, noise_model)

        self.assertEqual(target_circuit, result_circuit)
Esempio n. 21
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
Esempio n. 22
0
def get_noise(p_meas, p_gate):
    error_meas = pauli_error([('X', p_meas), ('I', 1 - p_meas)])
    error_gate1 = depolarizing_error(p_gate, 1)
    error_gate2 = error_gate1.tensor(error_gate1)

    noise_model = NoiseModel()
    noise_model.add_all_qubit_quantum_error(error_meas, "measure")
    noise_model.add_all_qubit_quantum_error(error_gate1, ["x"])
    noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"])

    return noise_model
Esempio n. 23
0
    def test_w_noise(self):
        """with noise test"""
        # build noise model
        # Asymmetric readout error on qubit-0 only
        try:
            from qiskit.providers.aer.noise import NoiseModel
            from qiskit import Aer

            self.backend = Aer.get_backend("qasm_simulator")
        except ImportError as ex:
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return

        probs_given0 = [0.9, 0.1]
        probs_given1 = [0.3, 0.7]
        noise_model = NoiseModel()
        noise_model.add_readout_error([probs_given0, probs_given1], [0])

        quantum_instance = QuantumInstance(
            self.backend,
            seed_transpiler=self.random_seed,
            seed_simulator=self.random_seed,
            shots=1024,
            noise_model=noise_model,
        )
        res_w_noise = quantum_instance.execute(self.qc).get_counts(self.qc)

        quantum_instance.skip_qobj_validation = True
        res_w_noise_skip_validation = quantum_instance.execute(
            self.qc).get_counts(self.qc)
        self.assertTrue(_compare_dict(res_w_noise,
                                      res_w_noise_skip_validation))

        # BasicAer should fail:
        with self.assertRaises(QiskitError):
            _ = QuantumInstance(BasicAer.get_backend("qasm_simulator"),
                                noise_model=noise_model)

        with self.assertRaises(QiskitError):
            quantum_instance = QuantumInstance(
                BasicAer.get_backend("qasm_simulator"))
            quantum_instance.set_config(noise_model=noise_model)
Esempio n. 24
0
def gate_error_noise_model(dev_name):
    # regular noise model for the backend
    device = provider.get_backend(dev_name)
    properties = device.properties()
    gate_lengths = noise.device.parameters.gate_length_values(properties)
    noise_model = NoiseModel.from_backend(properties,
                                          gate_lengths=gate_lengths)
    basis_gates = noise_model.basis_gates
    coupling_map = device.configuration().coupling_map
    return device, noise_model, basis_gates, coupling_map
Esempio n. 25
0
    def test_readout_error_all_qubit(self):
        """Test 100% readout error on all qubits"""

        # Test circuit: ideal bell state
        qr = QuantumRegister(2, 'qr')
        cr = ClassicalRegister(2, 'cr')
        circuit = QuantumCircuit(qr, cr)
        circuit.h(qr[0])
        circuit.cx(qr[0], qr[1])
        # Ensure qubit 0 is measured before qubit 1
        circuit.barrier(qr)
        circuit.measure(qr[0], cr[0])
        circuit.barrier(qr)
        circuit.measure(qr[1], cr[1])
        backend = QasmSimulator()

        # Asymetric readout error on qubit-0 only
        probs_given0 = [0.9, 0.1]
        probs_given1 = [0.3, 0.7]
        noise_model = NoiseModel()
        noise_model.add_all_qubit_readout_error([probs_given0, probs_given1])

        # Expected counts
        shots = 2000
        p00 = 0.5 * (probs_given0[0]**2 + probs_given1[0]**2)
        p01 = 0.5 * (probs_given0[0] * probs_given0[1] +
                     probs_given1[0] * probs_given1[1])
        p10 = 0.5 * (probs_given0[0] * probs_given0[1] +
                     probs_given1[0] * probs_given1[1])
        p11 = 0.5 * (probs_given0[1]**2 + probs_given1[1]**2)
        target = target = {
            '0x0': p00 * shots,
            '0x1': p01 * shots,
            '0x2': p10 * shots,
            '0x3': p11 * shots
        }
        qobj = compile([circuit],
                       backend,
                       shots=shots,
                       basis_gates=noise_model.basis_gates)
        result = backend.run(qobj, noise_model=noise_model).result()
        self.is_completed(result)
        self.compare_counts(result, [circuit], [target], delta=0.05 * shots)
Esempio n. 26
0
    def test_w_noise(self):
        # build noise model
        # Asymetric readout error on qubit-0 only
        probs_given0 = [0.9, 0.1]
        probs_given1 = [0.3, 0.7]
        noise_model = NoiseModel()
        noise_model.add_readout_error([probs_given0, probs_given1], [0])

        quantum_instance = QuantumInstance(self.backend,
                                           seed_mapper=self.random_seed,
                                           run_config=self.run_config,
                                           noise_model=noise_model)
        res_w_noise = quantum_instance.execute(self.qc).get_counts(self.qc)

        quantum_instance.skip_qobj_validation = True
        res_w_noise_skip_validation = quantum_instance.execute(
            self.qc).get_counts(self.qc)
        self.assertTrue(_compare_dict(res_w_noise,
                                      res_w_noise_skip_validation))
Esempio n. 27
0
    def test_auto_method_clifford_circuits_and_reset_noise(self):
        """Test statevector method is used for Clifford circuit"""
        # Test noise model
        noise_circs = [Reset(), IGate()]
        noise_probs = [0.5, 0.5]
        error = QuantumError(zip(noise_circs, noise_probs))
        noise_model = NoiseModel()
        noise_model.add_all_qubit_quantum_error(
            error, ['id', 'x', 'y', 'z', 'h', 's', 'sdg'])
        backend = self.backend(noise_model=noise_model)

        # Test circuits
        shots = 100
        circuits = ref_2q_clifford.cz_gate_circuits_deterministic(
            final_measure=True)
        result = backend.run(circuits, shots=shots).result()
        success = getattr(result, 'success', False)
        self.assertTrue(success)
        self.compare_result_metadata(result, circuits, 'method', 'stabilizer')
Esempio n. 28
0
def get_noise(p_meas, p_gate):
    """Define a noise model."""
    error_meas = pauli_error([("X", p_meas), ("I", 1 - p_meas)])
    error_gate1 = depolarizing_error(p_gate, 1)
    error_gate2 = error_gate1.tensor(error_gate1)

    noise_model = NoiseModel()
    noise_model.add_all_qubit_quantum_error(error_meas, "measure")
    noise_model.add_all_qubit_quantum_error(error_gate1, ["u1", "u2", "u3"])
    noise_model.add_all_qubit_quantum_error(error_gate2, ["cx"])

    return noise_model
Esempio n. 29
0
    def test_t2(self):
        """
        Run the simulator with dephasing noise.
        Then verify that the calculated T2 matches the dephasing parameter.
        """

        # 25 numbers ranging from 1 to 200, linearly spaced
        num_of_gates = (np.linspace(1, 300, 35)).astype(int)
        gate_time = 0.11
        num_of_qubits = 2
        qubit = 0

        circs, xdata = circuits.t2(num_of_gates, gate_time, num_of_qubits, qubit)

        expected_t2 = 20
        gamma = 1 - np.exp(-2*gate_time/expected_t2)
        error = phase_damping_error(gamma)
        noise_model = NoiseModel()
        noise_model.add_all_qubit_quantum_error(error, 'id')
        # TODO: Include SPAM errors

        backend = qiskit.Aer.get_backend('qasm_simulator')
        shots = 300
        backend_result = qiskit.execute(circs, backend,
                                        shots=shots,
                                        backend_options={'max_parallel_experiments': 0},
                                        noise_model=noise_model).result()

        initial_t2 = expected_t2
        initial_a = 1
        initial_c = 0.5*(-1)

        fit = T2Fitter(backend_result, shots, xdata, num_of_qubits, qubit,
                       fit_p0=[initial_a, initial_t2, initial_c],
                       fit_bounds=([0, 0, -1], [2, expected_t2*1.2, 1]))

        print(fit.time)
        print(fit.time_err)

        self.assertAlmostEqual(fit.time, expected_t2, delta=4,
                               msg='Calculated T2 is inaccurate')
        self.assertTrue(fit.time_err < 5,
                        'Confidence in T2 calculation is too low: ' + str(fit.time_err))
def RXDataset(angle_step=10, probability_step=10, shots=1024, save_dir=None):
    # define constants
    basis_gates = ['u3']
    simulator = QasmSimulator()
    df = pd.DataFrame()

    # generate circuits
    for angle in np.linspace(0, np.pi, angle_step, endpoint=True):
        # define circuit
        circ = QuantumCircuit(1, 1)
        rotate = RXGate(angle)
        circ.append(rotate, [0])
        circ.measure(0, 0)
        new_circ = qiskit.compiler.transpile(circ,
                                             basis_gates=basis_gates,
                                             optimization_level=0)
        print(new_circ)

        # generate noise models:
        for probability in np.linspace(0, 1, probability_step, endpoint=True):
            # add noise
            noise_model = NoiseModel()
            error = depolarizing_error(probability, 1)
            noise_model.add_all_qubit_quantum_error(error,
                                                    ['x', 'u1', 'u2', 'u3'])

            # execution - Noisy
            job = execute(new_circ,
                          simulator,
                          shots=shots,
                          noise_model=noise_model)
            result = job.result()

            # add to Pandas DF
            data = {
                'rx_theta': angle,
                'p': probability,
                'E': result.get_counts(0).get('0', 0) / shots
            }
            df = df.append(data, ignore_index=True)
    df = df[['rx_theta', 'E', 'p']]
    df.to_csv(save_dir + "/dataframe_RX.csv")
    return df