예제 #1
0
    def apply(self):
        from qiskit_aqua_cmd import Preferences
        from qiskit_aqua._logging import (build_logging_config,
                                          set_logging_config)
        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 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 provider_object == IBMQ:
        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))
예제 #3
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 provider_object == IBMQ:
        # enable IBMQ account
        preferences = Preferences()
        enable_ibmq_account(preferences.get_url(), preferences.get_token(),
                            preferences.get_proxies({}))

    return provider_object
예제 #4
0
def discover_preferences_pluggables():
    """
    Discovers the pluggable modules on the directory and subdirectories of the preferences package
    and attempts to register them. Pluggable modules should subclass Pluggable Base classes.
    """
    from qiskit_aqua_cmd import Preferences
    preferences = Preferences()
    packages = preferences.get_packages([])
    for package in packages:
        try:
            mod = importlib.import_module(package)
            if mod is not None:
                _discover_local_pluggables(os.path.dirname(mod.__file__),
                                           mod.__name__,
                                           names_to_exclude=['__main__'],
                                           folders_to_exclude=['__pycache__'])
            else:
                # Ignore package that could not be initialized.
                # print('Failed to import package {}'.format(package))
                logger.debug('Failed to import package {}'.format(package))
        except Exception as e:
            # Ignore package that could not be initialized.
            # print('Failed to load package {} error {}'.format(package, str(e)))
            logger.debug('Failed to load package {} error {}'.format(
                package, str(e)))
예제 #5
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())
예제 #6
0
def main_algorithm():
    try:
        from qiskit.aqua._logging import get_logging_level, build_logging_config, set_logging_config
        from qiskit_aqua_cmd import Preferences
        from qiskit.aqua import run_algorithm
        from qiskit.aqua.utils import convert_json_to_dict
        parser = argparse.ArgumentParser(
            description='Qiskit Aqua Command Line Tool')
        parser.add_argument('input',
                            metavar='input',
                            help='Algorithm JSON input file')
        parser.add_argument('-jo',
                            metavar='output',
                            help='Algorithm JSON output file name',
                            required=False)

        args = parser.parse_args()

        # update logging setting with latest external packages
        preferences = Preferences()
        logging_level = logging.INFO
        if preferences.get_logging_config() is not None:
            set_logging_config(preferences.get_logging_config())
            logging_level = get_logging_level()

        preferences.set_logging_config(build_logging_config(logging_level))
        preferences.save()

        set_logging_config(preferences.get_logging_config())

        params = None
        with open(args.input) as json_file:
            params = json.load(json_file)

        ret = run_algorithm(params, None, True)

        if args.jo is not None:
            with open(args.jo, 'w') as f:
                print('{}'.format(ret), file=f)
        else:
            convert_json_to_dict(ret)
            print(
                '\n\n--------------------------------- R E S U L T ------------------------------------\n'
            )
            if isinstance(ret, dict):
                for k, v in ret.items():
                    print("'{}': {}".format(k, v))
            else:
                print(ret)
    finally:
        global _ROOT
        if _ROOT is not None:
            _ROOT.destroy()
            _ROOT = None
예제 #7
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):
        from qiskit_aqua_cmd import Preferences
        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
예제 #8
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 remove credentials 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:
                IBMQ._accounts[credentials.unique_id()] = IBMQSingleProvider(
                    credentials, IBMQ)
                logger.debug("Registered with Qiskit successfully.")
                ibmq_backends = [x.name()
                                 for x in 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 Aer.backends()]
        for aer_backend in aer_backends:
            backend = aer_backend
            supported = True
            for unsupported_backend in QuantumInstance.UNSUPPORTED_BACKENDS:
                if backend.startswith(unsupported_backend):
                    supported = False
                    break

            if supported:
                backends.add(backend)

        return list(backends) + ibmq_backends
예제 #9
0
    def __init__(self, parent, **options):
        super(CredentialsView, self).__init__(parent, **options)

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

        from qiskit_aqua_cmd import Preferences
        preferences = Preferences()
        self._credentials_preferences = preferences.credentials_preferences

        ttk.Label(self,
                  text="URL:",
                  borderwidth=0,
                  anchor=tk.E).grid(row=0, column=0, pady=5, sticky='nsew')
        urls = [credentials.url for credentials in self._credentials_preferences.get_all_credentials()]
        self._urlCombobox = URLCombobox(self,
                                        self,
                                        width=80,
                                        exportselection=0,
                                        state='readonly',
                                        values=urls)
        self._urlCombobox._text = self._credentials_preferences.get_url('')
        self._urlCombobox.set(self._urlCombobox._text)
        if len(urls) > 0:
            if self._urlCombobox.get() in urls:
                self._urlCombobox.current(urls.index(self._urlCombobox.get()))
            else:
                self._urlCombobox.current(0)

        self._urlCombobox.grid(row=0, column=1, pady=5, sticky='nsew')

        button_container = tk.Frame(self)
        button_container.grid(row=0, column=2, pady=5, sticky='nsw')
        self._add_button = ttk.Button(button_container,
                                      text='Add',
                                      state='enable',
                                      command=self.onadd)
        self._remove_button = ttk.Button(button_container,
                                         text='Remove',
                                         state='enable',
                                         command=self.onremove)
        self._add_button.pack(side=tk.LEFT)
        if len(urls) > 0:
            self._remove_button.pack(side=tk.LEFT)

        self._apiToken = tk.StringVar()
        self._apiToken.set(self._credentials_preferences.get_token(''))
        ttk.Label(self,
                  text="Token:",
                  borderwidth=0,
                  anchor=tk.E).grid(row=1, column=0, pady=5, sticky='nsew')
        self._apiTokenEntry = EntryCustom(self,
                                          textvariable=self._apiToken,
                                          width=120,
                                          state=tk.NORMAL if len(urls) > 0 else tk.DISABLED)
        self._apiTokenEntry.grid(row=1, column=1, columnspan=2, pady=5, sticky='nsew')

        ttk.Label(self,
                  text="Proxies:",
                  borderwidth=0,
                  anchor=tk.E).grid(row=2, column=0, pady=5, sticky='nsew')
        self._proxiespage = ProxiesPage(self, self._credentials_preferences)
        self._proxiespage.grid(row=3, column=0, columnspan=3, 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)
        if len(urls) == 0:
            self._proxiespage.enable(False)

        self.initial_focus = self._urlCombobox
예제 #10
0
    def apply(self):
        try:
            if self._credentialsview:
                from qiskit_aqua_cmd import Preferences
                from qiskit.aqua import disable_ibmq_account
                preferences = Preferences()
                disable_ibmq_account(preferences.get_url(),
                                     preferences.get_token(),
                                     preferences.get_proxies({}))
                self._credentialsview.apply(preferences)
                preferences.save()

            level_name = self._levelCombo.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)

            preferences = self._guiprovider.create_preferences()
            preferences.set_logging_config(logging_config)
            preferences.save()

            self._guiprovider.set_logging_config(logging_config)

            populate = self._populateDefaults.get()
            preferences = self._guiprovider.create_uipreferences()
            preferences.set_populate_defaults(False if populate == 0 else True)
            preferences.save()

            self._controller.model.get_available_providers()
        except Exception as e:
            self.controller.outputview.write_line(str(e))
예제 #11
0
 def create_preferences(self):
     """Creates provider preferences."""
     from qiskit_aqua_cmd import Preferences
     return Preferences()
예제 #12
0
    def body(self, parent, options):
        from qiskit_aqua._logging import (get_logging_level,
                                          set_logging_config)
        from qiskit_aqua_cmd import Preferences
        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
예제 #13
0
def _post_install():
    from qiskit_aqua_cmd import Preferences
    preferences = Preferences()
    preferences.add_package('qiskit_aqua_chemistry.aqua_extensions')
    preferences.save()
예제 #14
0
def main():
    from qiskit.aqua._logging import (get_logging_level, build_logging_config,
                                      set_logging_config, set_aqua_logging)
    from qiskit_aqua_cmd import Preferences
    from qiskit.aqua import run_algorithm
    from qiskit.aqua.utils import convert_json_to_dict

    preferences = Preferences()
    _LOG_LEVELS = OrderedDict([
        (logging.getLevelName(logging.CRITICAL).lower(), logging.CRITICAL),
        (logging.getLevelName(logging.ERROR).lower(), logging.ERROR),
        (logging.getLevelName(logging.WARNING).lower(), logging.WARNING),
        (logging.getLevelName(logging.INFO).lower(), logging.INFO),
        (logging.getLevelName(logging.DEBUG).lower(), logging.DEBUG),
        (logging.getLevelName(logging.NOTSET).lower(), logging.NOTSET)
    ])

    parser = argparse.ArgumentParser(
        prog='qiskit_aqua_cmd',
        formatter_class=argparse.RawTextHelpFormatter,
        description='Qiskit Aqua Command Line Tool')
    parser.add_argument('input',
                        metavar='input',
                        help='Algorithm JSON input file')
    parser.add_argument('-jo',
                        metavar='output',
                        help='Algorithm JSON output file name')
    parser.add_argument('-l',
                        metavar='logging',
                        choices=_LOG_LEVELS.keys(),
                        help=textwrap.dedent('''\
                            Logging level:
                            {}
                            (defaults to level from preferences file: {})
                             '''.format(list(_LOG_LEVELS.keys()),
                                        preferences.filepath)))

    args = parser.parse_args()

    if args.l is not None:
        set_aqua_logging(_LOG_LEVELS.get(args.l, logging.INFO))
    else:
        # update logging setting with latest external packages
        logging_level = logging.INFO
        if preferences.get_logging_config() is not None:
            set_logging_config(preferences.get_logging_config())
            logging_level = get_logging_level()

        preferences.set_logging_config(build_logging_config(logging_level))
        preferences.save()
        set_logging_config(preferences.get_logging_config())

    params = None
    with open(args.input) as json_file:
        params = json.load(json_file)

    ret = run_algorithm(params, None, True)

    if args.jo is not None:
        with open(args.jo, 'w') as f:
            print('{}'.format(ret), file=f)
    else:
        convert_json_to_dict(ret)
        print(
            '\n\n--------------------------------- R E S U L T ------------------------------------\n'
        )
        if isinstance(ret, dict):
            for k, v in ret.items():
                print("'{}': {}".format(k, v))
        else:
            print(ret)