コード例 #1
0
def run_on_backend(backend,
                   qobj,
                   backend_options=None,
                   noise_config=None,
                   skip_qobj_validation=False):
    if skip_qobj_validation:
        job_id = str(uuid.uuid4())
        if is_simulator_backend(backend):
            if is_aer_provider(backend):
                job = backend.run(qobj, **backend_options, **noise_config)
            else:
                job = SimulatorsJob(backend, job_id, backend._run_job, qobj)
                job._future = job._executor.submit(job._fn, job._job_id,
                                                   job._qobj)
        elif is_ibmq_provider(backend):
            job = IBMQJob(backend,
                          None,
                          backend._api,
                          not is_simulator_backend(backend),
                          qobj=qobj)
            job._future = job._executor.submit(job._fn, job._job_id, job._qobj)
        else:
            logger.info(
                "Can not skip qobj validation for the third-party provider.")
            job = backend.run(qobj, **backend_options, **noise_config)
        return job
    else:
        job = backend.run(qobj, **backend_options, **noise_config)
        return job
コード例 #2
0
def run_on_backend(backend,
                   qobj,
                   backend_options=None,
                   noise_config=None,
                   skip_qobj_validation=False):
    if skip_qobj_validation:
        job_id = str(uuid.uuid4())
        if is_aer_provider(backend):
            from qiskit.providers.aer.aerjob import AerJob
            temp_backend_options = backend_options[
                'backend_options'] if backend_options != {} else None
            temp_noise_config = noise_config[
                'noise_model'] if noise_config != {} else None
            job = AerJob(backend, job_id, backend._run_job, qobj,
                         temp_backend_options, temp_noise_config, False)
            job._future = job._executor.submit(job._fn, job._job_id, job._qobj,
                                               *job._args)
        elif is_basicaer_provider(backend):
            backend._set_options(qobj_config=qobj.config, **backend_options)
            job = BasicAerJob(backend, job_id, backend._run_job, qobj)
            job._future = job._executor.submit(job._fn, job._job_id, job._qobj)
        elif is_ibmq_provider(backend):
            # TODO: IBMQJob performs validation during the constructor. the following lines does not
            # skip validation but run as is.
            from qiskit.providers.ibmq.ibmqjob import IBMQJob
            job = IBMQJob(backend, None, backend._api, qobj=qobj)
            job._future = job._executor.submit(job._submit_callback)
        else:
            logger.info(
                "Can't skip qobj validation for the third-party provider.")
            job = backend.run(qobj, **backend_options, **noise_config)
        return job
    else:
        job = backend.run(qobj, **backend_options, **noise_config)
        return job
コード例 #3
0
 def set_config(self, **kwargs):
     """Set configurations for the quantum instance."""
     for k, v in kwargs.items():
         if k in QuantumInstance.RUN_CONFIG:
             setattr(self._run_config, k, v)
         elif k in QuantumInstance.QJOB_CONFIG:
             self._qjob_config[k] = v
         elif k in QuantumInstance.COMPILE_CONFIG:
             self._compile_config[k] = v
         elif k in QuantumInstance.BACKEND_CONFIG:
             self._backend_config[k] = v
         elif k in QuantumInstance.BACKEND_OPTIONS:
             if is_ibmq_provider(self._backend):
                 logger.info(
                     "backend_options can not used with the backends in IBMQ provider."
                 )
             else:
                 if k in QuantumInstance.BACKEND_OPTIONS_QASM_ONLY and self.is_statevector:
                     logger.info(
                         "'{}' is only applicable for qasm simulator but "
                         "statevector simulator is used. Skip the setting.")
                 else:
                     if 'backend_options' not in self._backend_options:
                         self._backend_options['backend_options'] = {}
                     self._backend_options['backend_options'][k] = v
         elif k in QuantumInstance.NOISE_CONFIG:
             self._noise_config[k] = v
         else:
             raise ValueError("unknown setting for the key ({}).".format(k))
コード例 #4
0
ファイル: run_circuits.py プロジェクト: sergey55568/quantum
def _safe_submit_qobj(qobj, backend, backend_options, noise_config, skip_qobj_validation):
    # assure get job ids
    while True:
        try:
            job = run_on_backend(backend, qobj, backend_options=backend_options,
                                 noise_config=noise_config,
                                 skip_qobj_validation=skip_qobj_validation)
            job_id = job.job_id()
            break
        except QiskitError as ex:
            logger.warning("FAILURE: Can not get job id, Resubmit the qobj to get job id. "
                           "Terra job error: %s ", ex)
            if is_ibmq_provider(backend) and 'Error code: 3458' in str(ex):
                # TODO Use IBMQBackendJobLimitError when new IBM Q provider is released.
                oldest_running = backend.jobs(limit=1, descending=False,
                                              status=['QUEUED', 'VALIDATING', 'RUNNING'])
                if oldest_running:
                    oldest_running = oldest_running[0]
                    logger.warning("Job limit reached, waiting for job %s to finish "
                                   "before submitting the next one.", oldest_running.job_id())
                    oldest_running.wait_for_final_state(timeout=300)
        except Exception as ex:  # pylint: disable=broad-except
            logger.warning("FAILURE: Can not get job id, Resubmit the qobj to get job id."
                           "Error: %s ", ex)

    return job, job_id
コード例 #5
0
def _safe_submit_qobj(qobj: QasmQobj, backend: Union[Backend, BaseBackend],
                      backend_options: Dict, noise_config: Dict,
                      skip_qobj_validation: bool) -> Tuple[BaseJob, str]:
    # assure get job ids
    while True:
        try:
            job = run_on_backend(backend,
                                 qobj,
                                 backend_options=backend_options,
                                 noise_config=noise_config,
                                 skip_qobj_validation=skip_qobj_validation)
            job_id = job.job_id()
            break
        except QiskitError as ex:
            failure_warn = True
            if is_ibmq_provider(backend):
                try:
                    from qiskit.providers.ibmq import IBMQBackendJobLimitError
                except ImportError as ex1:
                    raise MissingOptionalLibraryError(
                        libname='qiskit-ibmq-provider',
                        name='_safe_submit_qobj',
                        pip_install='pip install qiskit-ibmq-provider'
                    ) from ex1
                if isinstance(ex, IBMQBackendJobLimitError):

                    oldest_running = backend.jobs(
                        limit=1,
                        descending=False,
                        status=['QUEUED', 'VALIDATING', 'RUNNING'])
                    if oldest_running:
                        oldest_running = oldest_running[0]
                        logger.warning(
                            "Job limit reached, waiting for job %s to finish "
                            "before submitting the next one.",
                            oldest_running.job_id())
                        failure_warn = False  # Don't issue a second warning.
                        try:
                            oldest_running.wait_for_final_state(timeout=300)
                        except Exception:  # pylint: disable=broad-except
                            # If the wait somehow fails or times out, we'll just re-try
                            # the job submit and see if it works now.
                            pass
            if failure_warn:
                logger.warning(
                    "FAILURE: Can not get job id, Resubmit the qobj to get job id. "
                    "Terra job error: %s ", ex)
        except Exception as ex:  # pylint: disable=broad-except
            logger.warning(
                "FAILURE: Can not get job id, Resubmit the qobj to get job id."
                "Error: %s ", ex)

    return job, job_id
コード例 #6
0
    def __init__(self,
                 backend,
                 shots=1024,
                 seed=None,
                 max_credits=10,
                 basis_gates=None,
                 coupling_map=None,
                 initial_layout=None,
                 pass_manager=None,
                 seed_mapper=None,
                 backend_options=None,
                 noise_model=None,
                 timeout=None,
                 wait=5,
                 circuit_cache=None,
                 skip_qobj_validation=False):
        """Constructor.

        Args:
            backend (BaseBackend): instance of selected backend
            shots (int, optional): number of repetitions of each circuit, for sampling
            seed (int, optional): random seed for simulators
            max_credits (int, optional): maximum credits to use
            basis_gates (list[str], optional): list of basis gate names supported by the
                                                target. Default: ['u1','u2','u3','cx','id']
            coupling_map (list[list]): coupling map (perhaps custom) to target in mapping
            initial_layout (dict, optional): initial layout of qubits in mapping
            pass_manager (PassManager, optional): pass manager to handle how to compile the circuits
            seed_mapper (int, optional): the random seed for circuit mapper
            backend_options (dict, optional): all running options for backend, please refer to the provider.
            noise_model (qiskit.provider.aer.noise.noise_model.NoiseModel, optional): noise model for simulator
            timeout (float, optional): seconds to wait for job. If None, wait indefinitely.
            wait (float, optional): seconds between queries to result
            circuit_cache (CircuitCache, optional): A CircuitCache to use when calling compile_and_run_circuits
            skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time
        """
        self._backend = backend
        # setup run config
        run_config = RunConfig(shots=shots, max_credits=max_credits)
        if seed:
            run_config.seed = seed

        if getattr(run_config, 'shots', None) is not None:
            if self.is_statevector and run_config.shots != 1:
                logger.info(
                    "statevector backend only works with shot=1, change "
                    "shots from {} to 1.".format(run_config.shots))
                run_config.shots = 1

        self._run_config = run_config

        # setup backend config
        basis_gates = basis_gates or backend.configuration().basis_gates
        coupling_map = coupling_map or getattr(backend.configuration(),
                                               'coupling_map', None)
        self._backend_config = {
            'basis_gates': basis_gates,
            'coupling_map': coupling_map
        }

        # setup noise config
        noise_config = None
        if noise_model is not None:
            if is_aer_provider(self._backend):
                if not self.is_statevector:
                    noise_config = noise_model
                else:
                    logger.info(
                        "The noise model can be only used with Aer qasm simulator. "
                        "Change it to None.")
            else:
                logger.info(
                    "The noise model can be only used with Qiskit Aer. "
                    "Please install it.")
        self._noise_config = {} if noise_config is None else {
            'noise_model': noise_config
        }

        # setup compile config
        if initial_layout is not None and not isinstance(
                initial_layout, Layout):
            initial_layout = Layout(initial_layout)
        self._compile_config = {
            'pass_manager': pass_manager,
            'initial_layout': initial_layout,
            'seed_mapper': seed_mapper
        }

        # setup job config
        self._qjob_config = {'timeout': timeout} if self.is_local \
            else {'timeout': timeout, 'wait': wait}

        # setup backend options for run
        self._backend_options = {}
        if is_ibmq_provider(self._backend):
            logger.info(
                "backend_options can not used with the backends in IBMQ provider."
            )
        else:
            self._backend_options = {} if backend_options is None \
                else {'backend_options': backend_options}

        self._shared_circuits = False
        self._circuit_summary = False
        self._circuit_cache = circuit_cache
        self._skip_qobj_validation = skip_qobj_validation

        logger.info(self)
コード例 #7
0
ファイル: quantum_instance.py プロジェクト: Travis-S/aqua
    def __init__(self, backend, run_config=None, initial_layout=None, pass_manager=None, seed_mapper=None,
                 backend_options=None, noise_model=None, timeout=None, wait=5, circuit_cache=None,
                 skip_qobj_validation=False):
        """Constructor.

        Args:
            backend (BaseBackend): instance of selected backend
            run_config (RunConfig): the run config see https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/qobj/run_config.py
            initial_layout (dict): initial layout of qubits in mapping
            pass_manager (PassManager): pass manager to handle how to compile the circuits
            seed_mapper (int): the random seed for circuit mapper
            backend_options (dict): all config setting for backend
            noise_model (qiskit.provider.aer.noise.noise_model.NoiseModel): noise model for simulator
            timeout (float or None): seconds to wait for job. If None, wait indefinitely.
            wait (float): seconds between queries to result
            circuit_cache (CircuitCache): A CircuitCache to use when calling compile_and_run_circuits
            skip_qobj_validation (bool): Bypass Qobj validation to decrease submission time
        """
        self._backend = backend
        # setup run config
        if run_config is None:
            run_config = RunConfig(shots=1024, max_credits=10, memory=False)

        if getattr(run_config, 'shots', None) is not None:
            if self.is_statevector and run_config.shots == 1:
                logger.info("statevector backend only works with shot=1, change "
                            "shots from {} to 1.".format(run_config.shots))
                run_config.shots = 1

        if getattr(run_config, 'memory', None) is not None:
            if not self.is_simulator and run_config.memory is True:
                logger.info("The memory flag only supports simulator rather than real device. "
                            "Change it to from {} to False.".format(run_config.memory))
                run_config.memory = False
        self._run_config = run_config

        # setup backend config
        coupling_map = getattr(backend.configuration(), 'coupling_map', None)
        # TODO: basis gates will be [str] rather than comma-separated str
        basis_gates = backend.configuration().basis_gates
        if isinstance(basis_gates, str):
            basis_gates = basis_gates.split(',')

        self._backend_config = {
            'basis_gates': basis_gates,
            'coupling_map': coupling_map
        }

        # setup noise config
        noise_config = None
        if noise_model is not None:
            if is_aer_provider(self._backend):
                if not self.is_statevector:
                    noise_config = noise_model
                else:
                    logger.info("The noise model can be only used with Aer qasm simulator. "
                                "Change it to None.")
            else:
                logger.info("The noise model can be only used with Qiskit Aer. "
                            "Please install it.")
        self._noise_config = {} if noise_config is None else {'noise_model': noise_config}

        # setup compile config
        self._compile_config = {
            'pass_manager': pass_manager,
            'initial_layout': initial_layout,
            'seed_mapper': seed_mapper,
            'qobj_id': None
        }

        # setup job config
        self._qjob_config = {'timeout': timeout} if self.is_local \
            else {'timeout': timeout, 'wait': wait}

        # setup backend options for run
        self._backend_options = {}
        if is_ibmq_provider(self._backend):
            logger.info("backend_options can not used with the backends in IBMQ provider.")
        else:
            self._backend_options = {} if backend_options is None \
                else {'backend_options': backend_options}

        self._shared_circuits = False
        self._circuit_summary = False
        self._circuit_cache = circuit_cache
        self._skip_qobj_validation = skip_qobj_validation

        logger.info(self)