Ejemplo n.º 1
0
def _load_provider(provider_name):
    index = provider_name.rfind(".")
    if index < 1:
        raise ImportError("Invalid provider name '{}'".format(provider_name))

    modulename = provider_name[0:index]
    objectname = provider_name[index + 1:len(provider_name)]

    module = importlib.import_module(modulename)
    if module is None:
        raise ImportError(
            "Failed to import provider '{}'".format(provider_name))

    provider_object = getattr(module, objectname)
    if provider_object is None:
        raise ImportError(
            "Failed to import provider '{}'".format(provider_name))

    if has_ibmq() and isinstance(provider_object, IBMQProvider):
        # enable IBMQ account
        preferences = Preferences()
        enable_ibmq_account(preferences.get_url(), preferences.get_token(),
                            preferences.get_proxies({}))

    return provider_object
Ejemplo n.º 2
0
    def apply(self):
        try:
            level_name = self._level_combo.get()
            levels = \
                [key for key, value in PreferencesDialog.log_levels.items() if value == level_name]
            loglevel = levels[0]

            logging_config = self._guiprovider.build_logging_config(loglevel)
            populate = self._populate_defaults.get()
            preferences = self._guiprovider.create_uipreferences()
            preferences.set_logging_config(logging_config)
            preferences.set_populate_defaults(populate != 0)
            preferences.save()

            self._guiprovider.set_logging_config(logging_config)

            if self._credentialsview:
                from qiskit.aqua import Preferences
                preferences = Preferences()
                self._credentialsview.apply(preferences)
                preferences.save()

            self._controller.model.get_available_providers()
        except Exception as ex:  # pylint: disable=broad-except
            self.controller.outputview.write_line(str(ex))
Ejemplo n.º 3
0
def get_backends_from_provider(provider_name):
    """
    Backends access method.

    Args:
        provider_name (str): Fullname of provider instance global property or class
    Returns:
        list: backend names
    Raises:
        ImportError: Invalid provider name or failed to find provider
    """
    provider_object = _load_provider(provider_name)
    if has_ibmq() and isinstance(provider_object, IBMQProvider):
        preferences = Preferences()
        url = preferences.get_url()
        token = preferences.get_token()
        kwargs = {}
        if url is not None and url != '':
            kwargs['url'] = url
        if token is not None and token != '':
            kwargs['token'] = token
        return [
            x.name() for x in provider_object.backends(**kwargs)
            if x.name() not in _UNSUPPORTED_BACKENDS
        ]

    try:
        # try as variable containing provider instance
        return [
            x.name() for x in provider_object.backends()
            if x.name() not in _UNSUPPORTED_BACKENDS
        ]
    except:
        # try as provider class then
        try:
            provider_instance = provider_object()
            return [
                x.name() for x in provider_instance.backends()
                if x.name() not in _UNSUPPORTED_BACKENDS
            ]
        except:
            pass

    raise ImportError(
        "'Backends not found for provider '{}'".format(provider_object))
Ejemplo n.º 4
0
def get_backend_from_provider(provider_name, backend_name):
    """
    Backend access method.

    Args:
        provider_name (str): Fullname of provider instance global property or class
        backend_name (str): name of backend for this provider
    Returns:
        BaseBackend: backend object
    Raises:
        ImportError: Invalid provider name or failed to find provider
    """
    backend = None
    provider_object = _load_provider(provider_name)
    if has_ibmq() and isinstance(provider_object, IBMQProvider):
        preferences = Preferences()
        url = preferences.get_url()
        token = preferences.get_token()
        kwargs = {}
        if url is not None and url != '':
            kwargs['url'] = url
        if token is not None and token != '':
            kwargs['token'] = token
        backend = provider_object.get_backend(backend_name, **kwargs)
    else:
        try:
            # try as variable containing provider instance
            backend = provider_object.get_backend(backend_name)
        except:
            # try as provider class then
            try:
                provider_instance = provider_object()
                backend = provider_instance.get_backend(backend_name)
            except:
                pass

    if backend is None:
        raise ImportError("'{} not found in provider '{}'".format(
            backend_name, provider_object))

    return backend
Ejemplo n.º 5
0
def _refresh_ibmq_account():
    """
    Refresh IBMQ account by enabling or disabling it depending on preferences stored values
    """
    preferences = Preferences().ibmq_credentials_preferences
    token = preferences.token or ''
    proxies = preferences.proxies or {}
    hub = preferences.hub
    group = preferences.group
    project = preferences.project
    provider = None
    try:
        # pylint: disable=no-name-in-module, import-error
        from qiskit import IBMQ
        providers = IBMQ.providers()
        if token != '':
            # check if there was a previous account that needs to be disabled first
            disable_account = False
            enable_account = True
            for provider in providers:
                if provider.credentials.token == token and provider.credentials.proxies == proxies:
                    enable_account = False
                else:
                    disable_account = True

            if disable_account:
                IBMQ.disable_account()
                logger.info('Disabled IBMQ account.')

            if enable_account:
                IBMQ.enable_account(token, proxies=proxies)
                logger.info('Enabled IBMQ account.')

            providers = IBMQ.providers(hub=hub, group=group, project=project)
            provider = providers[0] if providers else None
            if provider is None:
                logger.info(
                    "No Provider found for IBMQ account. "
                    "Hub/Group/Project: '%s/%s/%s' Proxies:'%s'", hub, group,
                    project, proxies)
        else:
            if providers:
                IBMQ.disable_account()
                logger.info('Disabled IBMQ account.')
    except Exception as ex:  # pylint: disable=broad-except
        logger.warning(
            "IBMQ account Account Failure. "
            "Hub/Group/Project: '%s/%s/%s' "
            "Proxies:'%s' :%s", hub, group, project, proxies, str(ex))

    return provider
Ejemplo n.º 6
0
    def __init__(self, parent, **options) -> None:
        super(CredentialsView, self).__init__(parent, **options)

        self._thread_queue = queue.Queue()
        self._thread = None

        self.pack(fill=tk.BOTH, expand=tk.TRUE)

        from qiskit.aqua import Preferences
        preferences = Preferences()
        cred_prefs = preferences.ibmq_credentials_preferences

        self._token = tk.StringVar()
        self._token.set(
            cred_prefs.token if cred_prefs.token is not None else '')
        ttk.Label(self, text="Token:", borderwidth=0,
                  anchor=tk.E).grid(row=0, column=0, pady=5, sticky='nsew')
        self._token_entry = EntryCustom(self,
                                        textvariable=self._token,
                                        width=120,
                                        state=tk.NORMAL)
        self._token_entry.grid(row=0, column=1, padx=5, pady=5, sticky='nsew')

        self._hub = tk.StringVar()
        self._hub.set(cred_prefs.hub if cred_prefs.hub is not None else '')
        ttk.Label(self, text="Hub:", borderwidth=0,
                  anchor=tk.E).grid(row=1, column=0, pady=5, sticky='nsew')
        self._hub_entry = ttk.Label(self,
                                    textvariable=self._hub,
                                    borderwidth=0,
                                    width=50)
        self._hub_entry.grid(row=1, column=1, padx=5, pady=5, sticky='nsw')

        self._group = tk.StringVar()
        self._group.set(
            cred_prefs.group if cred_prefs.group is not None else '')
        ttk.Label(self, text="Group:", borderwidth=0,
                  anchor=tk.E).grid(row=2, column=0, pady=5, sticky='nsew')
        self._group_entry = ttk.Label(self,
                                      textvariable=self._group,
                                      borderwidth=0,
                                      width=50)
        self._group_entry.grid(row=2, column=1, padx=5, pady=5, sticky='nsw')

        self._project = tk.StringVar()
        self._project.set(
            cred_prefs.project if cred_prefs.project is not None else '')
        ttk.Label(self, text="Project:", borderwidth=0,
                  anchor=tk.E).grid(row=3, column=0, pady=5, sticky='nsew')
        self._project_entry = ttk.Label(self,
                                        textvariable=self._project,
                                        borderwidth=0,
                                        width=50)
        self._project_entry.grid(row=3, column=1, padx=5, pady=5, sticky='nsw')

        self._chose_button = ttk.Button(self,
                                        text='Chose Hub/Group/Project',
                                        state='enable',
                                        command=self.cb_chose)
        self._chose_button.grid(row=4, column=1, padx=5, pady=5, sticky='nsw')

        ttk.Label(self, text="Proxies:", borderwidth=0,
                  anchor=tk.E).grid(row=5, column=0, pady=5, sticky='nsew')
        self._proxiespage = ProxiesPage(self, cred_prefs)
        self._proxiespage.grid(row=6,
                               column=0,
                               columnspan=2,
                               pady=5,
                               sticky='nsew')
        self._proxiespage.show_add_button(True)
        self._proxiespage.show_remove_button(self._proxiespage.has_selection())
        self._proxiespage.show_defaults_button(False)
        self._proxiespage.enable(True)

        self.initial_focus = self._token_entry