예제 #1
0
    def apply(self):
        try:
            level_name = self._levelCombo.get()
            levels = [
                key for key, value in PreferencesDialog._LOG_LEVELS.items()
                if value == level_name
            ]
            loglevel = levels[0]

            preferences = Preferences()
            self._credentialsview.apply(preferences)
            self._packagesPage.apply(preferences)
            preferences.save()

            logging_config = build_logging_config(loglevel)

            preferences = Preferences()
            preferences.set_logging_config(logging_config)
            preferences.save()

            set_logging_config(logging_config)

            uipreferences = UIPreferences()
            populate = self._populateDefaults.get()
            uipreferences.set_populate_defaults(False if populate ==
                                                0 else True)
            uipreferences.save()

            self._controller.get_available_backends()
        except Exception as e:
            self.controller.outputview.write_line(str(e))
예제 #2
0
    def register_and_get_operational_backends(*args,
                                              provider_class=IBMQProvider,
                                              **kwargs):
        try:
            for provider in q_registered_providers():
                if isinstance(provider, provider_class):
                    q_unregister(provider)
                    logger.debug(
                        "Provider '{}' unregistered with Qiskit successfully.".
                        format(provider_class))
                    break
        except Exception as e:
            logger.debug(
                "Failed to unregister provider '{}' with Qiskit: {}".format(
                    provider_class, str(e)))

        preferences = Preferences()
        if args or kwargs or preferences.get_token() is not None:
            try:
                q_register(*args, provider_class=provider_class, **kwargs)
                logger.debug(
                    "Provider '{}' registered with Qiskit successfully.".
                    format(provider_class))
            except Exception as e:
                logger.debug(
                    "Failed to register provider '{}' with Qiskit: {}".format(
                        provider_class, str(e)))

        backends = available_backends()
        backends = [
            x for x in backends
            if x not in QuantumAlgorithm.UNSUPPORTED_BACKENDS
        ]
        return backends
예제 #3
0
def _get_logging_names():
    names = OrderedDict()
    names['qiskit_aqua'] = None
    preferences = AquaPreferences()
    packages = preferences.get_packages([])
    for package in packages:
        names[package] = None

    return list(names.keys())
예제 #4
0
    def register_and_get_operational_backends():
        # update registration info using internal methods because:
        # at this point I don't want to save to or removecredentials from disk
        # I want to update url, proxies etc without removing token and
        # re-adding in 2 methods

        ibmq_backends = []
        try:
            credentials = None
            preferences = Preferences()
            url = preferences.get_url()
            token = preferences.get_token()
            if url is not None and url != '' and token is not None and token != '':
                credentials = Credentials(token,
                                          url,
                                          proxies=preferences.get_proxies({}))
            if credentials is not None:
                qiskit.IBMQ._accounts[
                    credentials.unique_id()] = IBMQSingleProvider(
                        credentials, qiskit.IBMQ)
                logger.debug("Registered with Qiskit successfully.")
                ibmq_backends = [
                    x.name()
                    for x in qiskit.IBMQ.backends(url=url, token=token)
                ]
        except Exception as e:
            logger.debug("Failed to register with Qiskit: {}".format(str(e)))

        backends = set()
        aer_backends = [x.name() for x in qiskit.Aer.backends()]
        for aer_backend in aer_backends:
            backend = None
            for group_name, names in qiskit.Aer.grouped_backend_names().items(
            ):
                if aer_backend in names:
                    backend = group_name
                    break
            if backend is None:
                backend = aer_backend

            supported = True
            for unsupported_backend in QuantumAlgorithm.UNSUPPORTED_BACKENDS:
                if backend.startswith(unsupported_backend):
                    supported = False
                    break

            if supported:
                backends.add(backend)

        return list(backends) + ibmq_backends
예제 #5
0
    def body(self, parent, options):
        preferences = Preferences()
        logging_config = preferences.get_logging_config()
        if logging_config is not None:
            set_logging_config(logging_config)

        uipreferences = UIPreferences()
        populate = uipreferences.get_populate_defaults(True)
        self._populateDefaults.set(1 if populate else 0)

        credentialsGroup = ttk.LabelFrame(parent,
                                          text='IBMQ Credentials',
                                          padding=(6, 6, 6, 6),
                                          borderwidth=4,
                                          relief=tk.GROOVE)
        credentialsGroup.grid(padx=(7, 7),
                              pady=6,
                              row=0,
                              column=0,
                              sticky='nsew')
        self._credentialsview = CredentialsView(credentialsGroup)

        defaultsGroup = ttk.LabelFrame(parent,
                                       text='Defaults',
                                       padding=(6, 6, 6, 6),
                                       borderwidth=4,
                                       relief=tk.GROOVE)
        defaultsGroup.grid(padx=(7, 7), pady=6, row=1, column=0, sticky='nsw')
        defaultsGroup.columnconfigure(1, pad=7)

        self._checkButton = ttk.Checkbutton(defaultsGroup,
                                            text="Populate on file new/open",
                                            variable=self._populateDefaults)
        self._checkButton.grid(row=0, column=1, sticky='nsw')

        packagesGroup = ttk.LabelFrame(parent,
                                       text='Packages',
                                       padding=(6, 6, 6, 6),
                                       borderwidth=4,
                                       relief=tk.GROOVE)
        packagesGroup.grid(padx=(7, 7), pady=6, row=2, column=0, sticky='nsw')
        packagesGroup.columnconfigure(1, pad=7)

        frame = ttk.Frame(packagesGroup)
        frame.grid(row=0, column=0, sticky='nsew')

        self._packagesPage = PackagesPage(frame, preferences)
        self._packagesPage.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.TRUE)
        self._packagesPage.show_add_button(True)
        self._packagesPage.show_remove_button(
            self._packagesPage.has_selection())
        self._packagesPage.show_defaults_button(False)

        loggingGroup = ttk.LabelFrame(parent,
                                      text='Logging Configuration',
                                      padding=(6, 6, 6, 6),
                                      borderwidth=4,
                                      relief=tk.GROOVE)
        loggingGroup.grid(padx=(7, 7), pady=6, row=3, column=0, sticky='nsw')
        loggingGroup.columnconfigure(1, pad=7)

        loglevel = get_logging_level()

        ttk.Label(loggingGroup, text="Level:", borderwidth=0,
                  anchor=tk.E).grid(row=0, column=0, sticky='nsew')
        self._levelCombo = ttk.Combobox(
            loggingGroup,
            exportselection=0,
            state='readonly',
            values=list(PreferencesDialog._LOG_LEVELS.values()))
        index = list(PreferencesDialog._LOG_LEVELS.keys()).index(loglevel)
        self._levelCombo.current(index)
        self._levelCombo.grid(row=0, column=1, sticky='nsw')

        self.entry = self._credentialsview.initial_focus
        return self.entry  # initial focus
예제 #6
0
    def setup_quantum_backend(self,
                              backend='statevector_simulator',
                              shots=1024,
                              skip_transpiler=False,
                              noise_params=None,
                              coupling_map=None,
                              initial_layout=None,
                              hpc_params=None,
                              basis_gates=None,
                              max_credits=10,
                              timeout=None,
                              wait=5):
        """
        Setup the quantum backend.

        Args:
            backend (str or BaseBackend): name of or instance of selected backend
            shots (int): number of shots for the backend
            skip_transpiler (bool): skip most of the compile steps and produce qobj directly
            noise_params (dict): the noise setting for simulator
            coupling_map (list): coupling map (perhaps custom) to target in mapping
            initial_layout (dict): initial layout of qubits in mapping
            hpc_params (dict): HPC simulator parameters
            basis_gates (str): comma-separated basis gate set to compile to
            max_credits (int): maximum credits to use
            timeout (float or None): seconds to wait for job. If None, wait indefinitely.
            wait (float): seconds between queries

        Raises:
            AlgorithmError: set backend with invalid Qconfig
        """
        if backend is None:
            raise AlgorithmError('Missing algorithm backend')

        if isinstance(backend, str):
            operational_backends = self.register_and_get_operational_backends()
            if QuantumAlgorithm.EQUIVALENT_BACKENDS.get(
                    backend, backend) not in operational_backends:
                raise AlgorithmError(
                    "This backend '{}' is not operational for the quantum algorithm, \
                                     select any one below: {}".format(
                        backend, operational_backends))

        self._qjob_config = {'timeout': timeout, 'wait': wait}

        my_backend = None
        if isinstance(backend, BaseBackend):
            my_backend = backend
        else:
            try:
                my_backend = qiskit.Aer.get_backend(backend)
            except KeyError:
                preferences = Preferences()
                my_backend = qiskit.IBMQ.get_backend(
                    backend,
                    url=preferences.get_url(''),
                    token=preferences.get_token(''))

            if my_backend is None:
                raise AlgorithmError(
                    "Missing algorithm backend '{}'".format(backend))

        self._backend = my_backend

        shots = 1 if QuantumAlgorithm.is_statevector_backend(
            my_backend) else shots
        noise_params = noise_params if my_backend.configuration().get(
            'simulator', False) else None

        if my_backend.configuration().get('local', False):
            self._qjob_config.pop('wait', None)

        if coupling_map is None:
            coupling_map = my_backend.configuration()['coupling_map']
        if basis_gates is None:
            basis_gates = my_backend.configuration()['basis_gates']

        self._execute_config = {
            'shots': shots,
            'skip_transpiler': skip_transpiler,
            'config': {
                "noise_params": noise_params
            },
            'basis_gates': basis_gates,
            'coupling_map': coupling_map,
            'initial_layout': initial_layout,
            'max_credits': max_credits,
            'seed': self._random_seed,
            'qobj_id': None,
            'hpc': hpc_params
        }

        info = "Algorithm: '{}' setup with backend '{}', with following setting:\n {}\n{}".format(
            self._configuration['name'],
            my_backend.configuration()['name'], self._execute_config,
            self._qjob_config)

        logger.info('Qiskit Terra version {}'.format(qiskit_version))
        logger.info(info)