示例#1
0
    def __init__(self, backend, backend_name, local=True):
        """FakeBackend initializer.

        Args:
            backend (IBMQBackend): IBMQBackend instance
            backend_name (str): The name to give the backend.
            local (bool): Determines if Aer of IBMQ simulator should be used.
        """
        if backend.configuration().open_pulse:
            config = PulseBackendConfiguration.from_dict(backend.configuration().to_dict())
        else:
            config = QasmBackendConfiguration.from_dict(backend.configuration().to_dict())
        super().__init__(config)
        self._credentials = _Credentials()
        self._properties = backend.properties()
        self._configuration.simulator = True
        self._configuration.local = local
        self._configuration.backend_name = backend_name
        if AER_VERSION >= 60000:
            self.noise_model = NoiseModel.from_backend(self, warnings=False)
        else:
            self.noise_model = NoiseModel.from_backend(self)
        if local:
            self.sim = Aer.get_backend('qasm_simulator')
        else:
            pro = IBMQ.get_provider(hub='ibm-q', group='open', project='main')
            self.sim = pro.backends.ibmq_qasm_simulator
示例#2
0
def generate_nm(noise_model=None, backend=None, xtalk_prop=None):
    """
    args: 
        noise_model: NoiseModel
        backend: backend_name(str) or IBMQBackend or FakeBackend
        xtalk_prop: dict
            e.g. {(0, 1): {(2, 3): 1.2, (3, 4): 2.7}}
    return:
        NoiseModel
    """

    nm = noise_model

    # noise_model from backend
    if not nm:
        # define backend
        if isinstance(backend, str):
            backend = choose_fakebackend(backend)
        elif isinstance(backend, FakeBackend):
            pass
        elif isinstance(backend, IBMQBackend):
            pass
        else:
            raise BackendError("backend is not correct")
        nm = NoiseModel.from_backend(backend)
示例#3
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)
def applyNoise(qc):
    gate_lengths = [('u1', None, 0), ('u2', None, 100), ('u3', None, 200),
                    ('cx', [1, 0], 678), ('cx', [1, 2], 547),
                    ('cx', [2, 3], 721), ('cx', [4, 3], 733),
                    ('cx', [4, 10], 721), ('cx', [5, 4], 800),
                    ('cx', [5, 6], 800), ('cx', [5, 9], 895),
                    ('cx', [6, 8], 895), ('cx', [7, 8], 640),
                    ('cx', [9, 8], 895), ('cx', [9, 10], 800),
                    ('cx', [11, 10], 721), ('cx', [11, 3], 634),
                    ('cx', [12, 2], 773), ('cx', [13, 1], 2286),
                    ('cx', [13, 12], 1504), ('cx', [], 800)]
    noise_model = NoiseModel.from_backend(properties,
                                          gate_lengths=gate_lengths)
    #noise_model = noise.device.basic_device_noise_model(properties, gate_lengths=gate_lengths)
    #print(noise_model)

    basis_gates = noise_model.basis_gates
    #simulator = Aer.get_backend('qasm_simulator')

    result_noise = execute(qc,
                           backend_sim,
                           shots=10000,
                           noise_model=noise_model,
                           coupling_map=coupling_map,
                           basis_gates=basis_gates).result()
    counts_noise = result_noise.get_counts(qc)
    return counts_noise
示例#5
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
示例#6
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.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
示例#7
0
 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 __init__(
        self,
        noise_model_name,
        n_epochs,
        noise_total_prob=None,
        ignored_ops=('id', 'kraus', 'reset'),
        prob_schedule=None,
        prob_schedule_separator=None,
        factor=None,
        add_thermal=True,
    ):
        self.noise_model_name = noise_model_name
        provider = get_provider(backend_name=noise_model_name)
        backend = provider.get_backend(noise_model_name)

        self.noise_model = NoiseModel.from_backend(
            backend, thermal_relaxation=add_thermal)
        self.noise_model_dict = self.noise_model.to_dict()
        self.is_add_noise = True
        self.v_c_reg_mapping = None
        self.p_c_reg_mapping = None
        self.p_v_reg_mapping = None
        self.orig_noise_total_prob = noise_total_prob
        self.noise_total_prob = noise_total_prob
        self.mode = 'train'
        self.ignored_ops = ignored_ops

        self.parsed_dict = self.parse_noise_model_dict(self.noise_model_dict)
        self.parsed_dict = self.clean_parsed_noise_model_dict(
            self.parsed_dict, ignored_ops)
        self.n_epochs = n_epochs
        self.prob_schedule = prob_schedule
        self.prob_schedule_separator = prob_schedule_separator
        self.factor = factor
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)
示例#10
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
示例#11
0
    def __init__(self,
                 noise_model_name,
                 mean=0.,
                 std=1.,
                 n_epochs=200,
                 prob_schedule=None,
                 prob_schedule_separator=None,
                 factor=None):
        super().__init__(mean=mean,
                         std=std,
                         n_epochs=n_epochs,
                         prob_schedule=prob_schedule,
                         prob_schedule_separator=prob_schedule_separator,
                         factor=factor)
        provider = get_provider(backend_name=noise_model_name)
        backend = provider.get_backend(noise_model_name)

        self.noise_model = NoiseModel.from_backend(backend)
        self.noise_model_dict = self.noise_model.to_dict()
        self.is_add_noise = True
        self.v_c_reg_mapping = None
        self.p_c_reg_mapping = None
        self.p_v_reg_mapping = None

        self.parsed_dict = NoiseModelTQ.parse_noise_model_dict(
            self.noise_model_dict)
示例#12
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, )])
示例#13
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
示例#14
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
                ])
示例#15
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
示例#16
0
    def test_truncate_non_measured_qubits(self):
        """Test truncation of non-measured uncoupled qubits."""
        noise_model = NoiseModel.from_backend(self.device_backend())
        backend = self.backend(noise_model=noise_model)
        circuit = transpile(self.create_circuit_for_truncate(), backend)

        result = backend.run(circuit, shots=1).result()
        metadata = result.results[0].metadata
        self.assertEqual(metadata["num_qubits"], 2)
        self.assertEqual(metadata["active_input_qubits"], [0, 1])
示例#17
0
    def test_noise_model_from_mumbai(self):
        circ = QuantumCircuit(2)
        circ.x(0)
        circ.x(1)
        circ.measure_all()

        backend = mock.FakeMumbai()
        noise_model = NoiseModel.from_backend(backend)
        circ = transpile(circ, backend, optimization_level=0)
        result = AerSimulator().run(circ, noise_model=noise_model).result()
        self.assertTrue(result.success)
示例#18
0
def main():
    # Parse all command line arguments
    args = parser.parse_args()
    shots = args.shots
    seed = args.seed
    basis = args.bell
    logfile = args.logfile
    verbose = args.verbose

    # Define the logger
    logger = logging.getLogger('task2')
    if logfile:
        logger.addHandler(logging.FileHandler(logfile))
    if verbose:
        logger.addHandler(logging.StreamHandler())
    logger.setLevel(logging.DEBUG)

    np.random.seed(seed=seed)

    # Get the noise model
    device_backend = FakeVigo()
    noise_model = NoiseModel.from_backend(device_backend)
    coupling_map = device_backend.configuration().coupling_map
    basis_gates = noise_model.basis_gates

    backend = Aer.get_backend('qasm_simulator')
    statevector_backend = Aer.get_backend('statevector_simulator')

    circuit = build_circuit(measure=basis)
    circuit_for_counts = build_circuit(measure='computational')
    unmeasured_circuit = build_circuit(measure=None)

    # qiskit's COBYLA can't take args to pass to the objective function, so we freeze them with functools.partial
    optimizer = COBYLA(maxiter=1000, tol=1e-8, disp=True)

    for nshots in shots:
        logger.debug('====================================================================================')
        logger.debug(f'\nShots per iteration: {nshots}')
        logger.debug(circuit)

        partial_objective_function = partial(objective_function, circuit=circuit, shots=nshots, backend=backend, bell_basis=(basis == 'bell'),
                                            noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates)
        ret = optimizer.optimize(num_vars=2, objective_function=partial_objective_function, 
                                initial_point=np.random.rand(len(circuit.parameters))*4*np.pi - 2*np.pi)


        params = ret[0]
        logger.debug(f'\nParameters:\n{params}')
        logger.debug(f'\nStatevector:\n{execute_circuit(unmeasured_circuit, params, statevector_backend).result().get_statevector()}')
        logger.debug(f'\nSimulated results:\n{execute_circuit(circuit_for_counts, params, backend, nshots, noise_model, coupling_map, basis_gates).result().get_counts()}')
        logger.debug('====================================================================================\n')

    sys.exit(ExitStatus.success)
示例#19
0
    def test_noise_model_from_rochester(self):
        circ = QuantumCircuit(2)
        circ.x(0)
        circ.x(1)
        circ.measure_all()

        backend = mock.FakeRochester()
        noise_model = NoiseModel.from_backend(backend)
        qobj = assemble(transpile(circ, backend), backend)
        sim = QasmSimulator()
        result = sim.run(qobj, noise_model=noise_model).result()
        self.assertTrue(result.success)
示例#20
0
    def test_noise_model_from_backend_singapore(self):
        circ = QuantumCircuit(2)
        circ.x(0)
        circ.x(1)
        circ.measure_all()

        backend = mock.FakeSingapore()
        noise_model = NoiseModel.from_backend(backend)
        qobj = assemble(transpile(circ, backend, optimization_level=0),
                        backend)
        sim = QasmSimulator()
        result = sim.run(qobj, noise_model=noise_model).result()
        self.assertTrue(result.success)
示例#21
0
def runGame():

    noiseless_new_position = new_position = position = getRandomLocation()

    # Get Noise levels from Melbourne Q Computer
    provider = IBMQ.load_account()
    backend = provider.get_backend('ibmq_16_melbourne')
    noise_model = NoiseModel.from_backend(backend)

    while True:  # main game loop

        DISPLAYSURF.fill(BGCOLOR)
        drawGrid()
        drawPosition(new_position)

        position_binary = toBinary(position)

        # Key control
        for event in pygame.event.get():  # event handling loop
            if event.type == QUIT:
                terminate()

            elif event.type == KEYDOWN:
                if (event.key == K_LEFT or event.key == K_a):
                    new_position = calculateQuantumPosition(
                        position, 1, "sub", noise_model)
                    noiseless_new_position = position - 1
                elif (event.key == K_RIGHT or event.key == K_d):
                    new_position = calculateQuantumPosition(
                        position, 1, "add", noise_model)
                    noiseless_new_position = position + 1
                elif (event.key == K_UP or event.key == K_w):
                    new_position = calculateQuantumPosition(
                        position, 16, "sub", noise_model)
                    noiseless_new_position = position - 16
                elif (event.key == K_DOWN or event.key == K_s):
                    new_position = calculateQuantumPosition(
                        position, 16, "add", noise_model)
                    noiseless_new_position = position + 16
                elif event.key == K_ESCAPE:
                    terminate()

        if (new_position != noiseless_new_position):
            print("Error due to Noise! Wanted: ", noiseless_new_position,
                  " Got: ", new_position)

        drawPosition(new_position)
        position = new_position

        pygame.display.update()
        FPSCLOCK.tick(FPS)
示例#22
0
    def run(self, run_input, **kwargs):
        """Main job in simulator"""
        circuits = run_input
        pulse_job = None
        if isinstance(circuits, (pulse.Schedule, pulse.ScheduleBlock)):
            pulse_job = True
        elif isinstance(circuits, circuit.QuantumCircuit):
            pulse_job = False
        elif isinstance(circuits, list):
            if circuits:
                if all(
                        isinstance(x, (pulse.Schedule, pulse.ScheduleBlock))
                        for x in circuits):
                    pulse_job = True
                elif all(
                        isinstance(x, circuit.QuantumCircuit)
                        for x in circuits):
                    pulse_job = False
        if pulse_job is None:
            raise QiskitError("Invalid input object %s, must be either a "
                              "QuantumCircuit, Schedule, or a list of either" %
                              circuits)
        if _optionals.HAS_AER:
            from qiskit.providers import aer

            if pulse_job:
                from qiskit.providers.aer.pulse import PulseSystemModel

                system_model = PulseSystemModel.from_backend(self)
                sim = aer.Aer.get_backend("pulse_simulator")
                job = sim.run(circuits, system_model=system_model, **kwargs)
            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(circuits, noise_model=noise_model, **kwargs)
                else:
                    job = sim.run(circuits, **kwargs)
        else:
            if pulse_job:
                raise QiskitError(
                    "Unable to run pulse schedules without qiskit-aer installed"
                )
            warnings.warn("Aer not found using BasicAer and no noise",
                          RuntimeWarning)
            sim = basicaer.BasicAer.get_backend("qasm_simulator")
            job = sim.run(circuits, **kwargs)
        return job
示例#23
0
    def __init__(self):
        self.py = Parameter("θ_y")
        self.px = Parameter("θ_x")
        self.ansatz = self.make_ansatz()
        self.backend = Aer.get_backend("qasm_simulator")

        # Get noise model
        vigo_backend = FakeVigo()
        self.noise_model = NoiseModel.from_backend(vigo_backend)
        self.coupling_map = vigo_backend.configuration().coupling_map
        self.basis_gates = self.noise_model.basis_gates

        # Extra arrays for debugging
        self.cost_history = []
示例#24
0
    def _setup_sim(self):
        if _optionals.HAS_AER:
            from qiskit.providers import aer
            from qiskit.providers.aer.noise import NoiseModel

            self.sim = aer.AerSimulator()
            if self.properties():
                noise_model = NoiseModel.from_backend(self, warnings=False)
                self.sim.set_options(noise_model=noise_model)
                # Update fake backend default options too to avoid overwriting
                # it when run() is called
                self.set_options(noise_model=noise_model)
        else:
            self.sim = basicaer.QasmSimulatorPy()
示例#25
0
    def __init__(self,
                 protocol='Bell_teleport',
                 device='qasm_simulator',
                 live=False,
                 qasm_sim=False,
                 noise_model=None,
                 shots=1024,
                 save_results=False,
                 directory=None):  # QIP_Task initialisation function

        # Stores protocol information
        self.protocol = protocol
        self.live = live
        self.shots = shots
        self.save_results = save_results
        self.directory = directory

        if device == 'qasm_simulator':  # Defines settings for qasm_simulator use only
            self.qasm_sim = False
            self.backend = Aer.get_backend('qasm_simulator')
            self.device = self.backend
            self.coupling_map = None
            if noise_model:
                self.noise_model = noise_model
                self.basis_gates = self.noise_model.basis_gates
            else:
                self.noise_model = None
                self.basis_gates = None
        else:  # Defines settings for processor use
            self.qasm_sim = qasm_sim
            provider = IBMQ.get_provider(group='open')
            self.device = provider.get_backend(device)
            if save_results:
                plot_error_map(self.device).savefig('{}/error_map.svg'.format(
                    self.directory),
                                                    format='svg')
            if self.live:  # Defines settings for live simulations
                self.backend = self.device
                self.coupling_map = None
                self.noise_model = None
                self.basis_gates = None
            else:  # Defines settings for artificial simulations
                from qiskit.providers.aer.noise import NoiseModel

                self.backend = Aer.get_backend('qasm_simulator')
                self.properties = self.device.properties()
                self.coupling_map = self.device.configuration().coupling_map
                self.noise_model = NoiseModel.from_backend(self.properties)
                self.basis_gates = self.noise_model.basis_gates
示例#26
0
def noise_sim(cir):
    provider = qk.IBMQ.get_provider('ibm-q-hub-ntu')
    backend = provider.get_backend('ibmq_cambridge')
    noise_model = NoiseModel.from_backend(backend, gate_error=False)

    coupling_map = backend.configuration().coupling_map
    basis_gates = noise_model.basis_gates
    result = qk.execute(cir,
                        qk.Aer.get_backend('qasm_simulator'),
                        coupling_map=coupling_map,
                        basis_gates=basis_gates,
                        noise_model=noise_model,
                        shots=8192).result()
    counts = result.get_counts()
    return counts
示例#27
0
def quantumsimulation(qc1,
                      n,
                      shots,
                      backend,
                      plotcircuit=False,
                      cedges=False,
                      depthweightcnots=False,
                      provider=False,
                      noise=False):
    if (depthweightcnots):
        qc1 = transpile(qc1,
                        basis_gates=['u1', 'u2', 'u3', 'cx'],
                        optimization_level=3)
        if (len(cedges) == 0):
            cnots = 0
        else:
            #cnots = 0
            cnots = qc1.count_ops()['cx']
        depth = qc1.depth()

    qc1.measure(range(n), range(n))
    if (plotcircuit):
        display(qc1.draw('mpl'))

    if (str(backend) == "qasm_simulator"):
        if (noise):
            backend2 = provider.get_backend('ibmq_santiago')
            noise_model = NoiseModel.from_backend(backend2)
            coupling_map = backend2.configuration().coupling_map
            basis_gates = noise_model.basis_gates
            simulate = execute(qc1,
                               backend=backend,
                               shots=shots,
                               coupling_map=coupling_map,
                               basis_gates=basis_gates,
                               noise_model=noise_model)
        else:
            simulate = execute(qc1, backend=backend, shots=shots)

    else:
        simulate = execute(qc1, backend=backend, shots=shots)

    result = simulate.result()

    if (depthweightcnots):
        return result, cnots, depth
    else:
        return result
    def test_truncate_disable_noise(self):
        """Test explicitly disabling truncation with noise model option"""
        coupling_map = [  # 10-qubit device
            [0, 1], [1, 2], [2, 3], [3, 4], [4, 5],
            [5, 6], [6, 7], [7, 8], [8, 9], [9, 0]
        ]
        noise_model = NoiseModel.from_backend(self.device_properties())
        backend = self.backend(noise_model=noise_model, enable_truncation=False)
        circuit = transpile(
            self.create_circuit_for_truncate(),
            backend, coupling_map=coupling_map)

        result = backend.run(circuit, shots=100).result()
        metadata = result.results[0].metadata
        self.assertEqual(metadata["num_qubits"], 10)
        self.assertEqual(metadata["active_input_qubits"], list(range(4)))      
示例#29
0
    def test_truncate_default(self):
        """Test truncation with noise model option"""
        coupling_map = [  # 10-qubit device
            [0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8],
            [8, 9], [9, 0]
        ]
        noise_model = NoiseModel.from_backend(self.device_backend())
        backend = self.backend(noise_model=noise_model)
        circuit = transpile(self.create_circuit_for_truncate(),
                            backend,
                            coupling_map=coupling_map)

        result = backend.run(circuit, shots=1).result()
        metadata = result.results[0].metadata
        self.assertEqual(metadata["num_qubits"], 2)
        self.assertEqual(metadata["active_input_qubits"], [0, 1])
示例#30
0
def get_device_info(token, hub, group, project, device_name, fields, datetime):
    dirname = "./devices/%s" % datetime.date()
    filename = "%s/%s.pckl" % (dirname, device_name)
    _device_info = read_dict(filename=filename)
    if len(_device_info) == 0:
        if not os.path.exists(dirname):
            os.makedirs(dirname)
        else:
            subprocess.run(["rm", "-r", dirname])
            os.makedirs(dirname)
        provider = load_IBMQ(token=token,
                             hub=hub,
                             group=group,
                             project=project)
        for x in provider.backends():
            if "simulator" not in str(x):
                device = provider.get_backend(str(x))
                properties = device.properties(datetime=datetime)
                num_qubits = device.configuration().n_qubits
                print("Download device_info for %d-qubit %s" % (num_qubits, x))
                coupling_map = CouplingMap(device.configuration().coupling_map)
                noise_model = NoiseModel.from_backend(device)
                basis_gates = device.configuration().basis_gates
                _device_info = {
                    "properties": properties,
                    "coupling_map": coupling_map,
                    "noise_model": noise_model,
                    "basis_gates": basis_gates,
                }
                pickle.dump(_device_info,
                            open("%s/%s.pckl" % (dirname, str(x)), "wb"))
            print("-" * 50)
        _device_info = read_dict(filename=filename)
    device_info = {}
    for field in fields:
        if field == "device":
            provider = load_IBMQ(token=token,
                                 hub=hub,
                                 group=group,
                                 project=project)
            device = provider.get_backend(device_name)
            device_info[field] = device
        else:
            device_info[field] = _device_info[field]
    return device_info, filename