def get_pluggable_section_names(self, section_name):
        """ get all pluggable section names """
        from qiskit.aqua.parser import BaseParser
        from qiskit.aqua import PluggableType, local_pluggables
        from qiskit.aqua.parser import JSONSchema
        if not BaseModel.is_pluggable_section(section_name):
            return []

        if PluggableType.ALGORITHM.value == section_name:
            problem_name = None
            if self._parser is not None:
                problem_name = self.get_section_property(
                    JSONSchema.PROBLEM, JSONSchema.NAME)
            if problem_name is None:
                problem_name = self.get_property_default_value(
                    JSONSchema.PROBLEM, JSONSchema.NAME)

            if problem_name is None:
                return local_pluggables(PluggableType.ALGORITHM)

            algo_names = []
            for algo_name in local_pluggables(PluggableType.ALGORITHM):
                problems = BaseParser.get_algorithm_problems(algo_name)
                if problem_name in problems:
                    algo_names.append(algo_name)

            return algo_names

        return local_pluggables(section_name)
Пример #2
0
    def test_pluggable_inputs(self):
        algorithm_problems = set()
        for pluggable_name in local_pluggables(PluggableType.ALGORITHM):
            configuration = get_pluggable_configuration(PluggableType.ALGORITHM, pluggable_name)
            if isinstance(configuration, dict):
                algorithm_problems.update(configuration.get('problems', []))

        err_msgs = []
        all_problems = set()
        for pluggable_name in local_pluggables(PluggableType.INPUT):
            cls = get_pluggable_class(PluggableType.INPUT, pluggable_name)
            configuration = get_pluggable_configuration(PluggableType.INPUT, pluggable_name)
            missing_problems = []
            if isinstance(configuration, dict):
                problem_names = configuration.get('problems', [])
                all_problems.update(problem_names)
                for problem_name in problem_names:
                    if problem_name not in algorithm_problems:
                        missing_problems.append(problem_name)

            if len(missing_problems) > 0:
                err_msgs.append("{}: No algorithm declares the problems {}.".format(cls, missing_problems))

        invalid_problems = list(set(AlgorithmInput._PROBLEM_SET).difference(all_problems))
        if len(invalid_problems) > 0:
            err_msgs.append("Base Class AlgorithmInput contains problems {} that don't belong to any Input class.".format(invalid_problems))

        if len(err_msgs) > 0:
            self.fail('\n'.join(err_msgs))
Пример #3
0
    def _validate_depends(self, cls, dependencies):
        err_msgs = []
        for dependency in dependencies:
            if not isinstance(dependency, dict):
                err_msgs.append("{} configuration section:'{}' item isn't a dictionary.".format(cls, 'depends'))
                continue

            dependency_pluggable_type = dependency.get('pluggable_type')
            if not isinstance(dependency_pluggable_type, str):
                err_msgs.append("{} configuration section:'{}' item:'{}' isn't a string.".format(cls, 'depends', 'pluggable_type'))
                continue

            if not any(x for x in PluggableType if x.value == dependency_pluggable_type):
                err_msgs.append("{} configuration section:'{}' item:'{}/{}' doesn't exist.".format(cls, 'depends', 'pluggable_type', dependency_pluggable_type))
                continue

            defaults = dependency.get('default')
            if not isinstance(defaults, dict):
                continue

            default_name = defaults.get('name')
            if default_name not in local_pluggables(dependency_pluggable_type):
                print(default_name, dependency_pluggable_type, local_pluggables(dependency_pluggable_type))
                err_msgs.append("{} configuration section:'{}' item:'{}/{}/{}/{}' not found.".format(cls, 'depends', dependency_pluggable_type, 'default', 'name', default_name))
                continue

            del defaults['name']
            if len(defaults) > 0:
                err_msgs.extend(self._validate_defaults_against_schema(dependency_pluggable_type, default_name, defaults))

        return err_msgs
Пример #4
0
    def _update_algorithm_problem(self):
        problem_name = self.get_section_property(JSONSchema.PROBLEM,
                                                 JSONSchema.NAME)
        if problem_name is None:
            problem_name = self.get_property_default_value(
                JSONSchema.PROBLEM, JSONSchema.NAME)

        if problem_name is None:
            raise AquaError("No algorithm 'problem' section found on input.")

        algo_name = self.get_section_property(PluggableType.ALGORITHM.value,
                                              JSONSchema.NAME)
        if algo_name is not None and problem_name in BaseParser.get_algorithm_problems(
                algo_name):
            return

        for algo_name in local_pluggables(PluggableType.ALGORITHM):
            if problem_name in self.get_algorithm_problems(algo_name):
                # set to the first algorithm to solve the problem
                self.set_section_property(PluggableType.ALGORITHM.value,
                                          JSONSchema.NAME, algo_name)
                return

        # no algorithm solve this problem, remove section
        self.delete_section(PluggableType.ALGORITHM.value)
Пример #5
0
    def _update_input_problem(self):
        problem_name = self.get_section_property(JSONSchema.PROBLEM,
                                                 JSONSchema.NAME)
        if problem_name is None:
            problem_name = self.get_property_default_value(
                JSONSchema.PROBLEM, JSONSchema.NAME)

        if problem_name is None:
            raise AquaError("No algorithm 'problem' section found on input.")

        input_name = self.get_section_property(PluggableType.INPUT.value,
                                               JSONSchema.NAME)
        if input_name is not None and problem_name in InputParser.get_input_problems(
                input_name):
            return

        for input_name in local_pluggables(PluggableType.INPUT):
            if problem_name in self.get_input_problems(input_name):
                # set to the first input to solve the problem
                self.set_section_property(PluggableType.INPUT.value,
                                          JSONSchema.NAME, input_name)
                return

        # no input solve this problem, remove section
        self.delete_section(PluggableType.INPUT.value)
Пример #6
0
    def test_pluggable_configuration(self):
        """ pluggable configuration tests """
        err_msgs = []
        for pluggable_type in local_pluggables_types():
            for pluggable_name in local_pluggables(pluggable_type):
                cls = get_pluggable_class(pluggable_type, pluggable_name)
                configuration = get_pluggable_configuration(
                    pluggable_type, pluggable_name)
                if not isinstance(configuration, dict):
                    err_msgs.append(
                        "{} configuration isn't a dictionary.".format(cls))
                    continue

                if pluggable_type in [
                        PluggableType.ALGORITHM, PluggableType.INPUT
                ]:
                    if not configuration.get('problems', []):
                        err_msgs.append(
                            "{} missing or empty 'problems' section.".format(
                                cls))

                schema_found = False
                for configuration_name, configuration_value in configuration.items(
                ):
                    if configuration_name in ['problems', 'depends']:
                        if not isinstance(configuration_value, list):
                            err_msgs.append(
                                "{} configuration section:'{}' isn't a list.".
                                format(cls, configuration_name))
                            continue

                        if configuration_name == 'depends':
                            err_msgs.extend(
                                self._validate_depends(cls,
                                                       configuration_value))

                        continue

                    if configuration_name == 'input_schema':
                        schema_found = True
                        if not isinstance(configuration_value, dict):
                            err_msgs.append(
                                "{} configuration section:'{}' isn't a dictionary."
                                .format(cls, configuration_name))
                            continue

                        err_msgs.extend(
                            self._validate_schema(cls, configuration_value))
                        continue

                if not schema_found:
                    err_msgs.append(
                        "{} configuration missing schema.".format(cls))

        if err_msgs:
            self.fail('\n'.join(err_msgs))
Пример #7
0
    def _initialize_problem_section(self):
        """Initialize problem"""
        self._schema['properties'][JSONSchema.PROBLEM]['properties']['num_processes']['maximum'] = aqua_globals.CPU_COUNT
        problems_dict = OrderedDict()
        for algo_name in local_pluggables(PluggableType.ALGORITHM):
            problems = JSONSchema.get_algorithm_problems(algo_name)
            for problem in problems:
                problems_dict[problem] = None

        self._schema['properties'][JSONSchema.PROBLEM]['properties'][JSONSchema.NAME]['enum'] = list(problems_dict.keys())
Пример #8
0
    def populate_problem_names(self):
        """Populate enum list of problem names"""
        problems_dict = OrderedDict()
        for algo_name in local_pluggables(PluggableType.ALGORITHM):
            problems = JSONSchema.get_algorithm_problems(algo_name)
            for problem in problems:
                problems_dict[problem] = None

        problems_enum = {'enum': list(problems_dict.keys())}
        self._schema['properties'][JSONSchema.PROBLEM]['properties'][
            JSONSchema.NAME]['oneOf'] = [problems_enum]
Пример #9
0
    def get_input_section_names(self):
        """ get input section valid names """
        from qiskit.aqua.parser._inputparser import InputParser
        from qiskit.aqua import local_pluggables, PluggableType
        from qiskit.aqua.parser import JSONSchema
        problem_name = None
        if self._parser is not None:
            problem_name = self.get_section_property(JSONSchema.PROBLEM, JSONSchema.NAME)
        if problem_name is None:
            problem_name = self.get_property_default_value(JSONSchema.PROBLEM, JSONSchema.NAME)

        if problem_name is None:
            return local_pluggables(PluggableType.INPUT)

        input_names = []
        for input_name in local_pluggables(PluggableType.INPUT):
            problems = InputParser.get_input_problems(input_name)
            if problem_name in problems:
                input_names.append(input_name)

        return input_names
Пример #10
0
    def _update_algorithm_input_schema(self):
        # find algorithm input
        default_name = self.get_property_default_value(PluggableType.INPUT.value, JSONSchema.NAME)
        input_name = self.get_section_property(PluggableType.INPUT.value,
                                               JSONSchema.NAME, default_name)
        if input_name is None:
            # find the first valid input for the problem
            problem_name = self.get_section_property(JSONSchema.PROBLEM, JSONSchema.NAME)
            if problem_name is None:
                problem_name = self.get_property_default_value(JSONSchema.PROBLEM,
                                                               JSONSchema.NAME)

            if problem_name is None:
                raise AquaError("No algorithm 'problem' section found on input.")

            for name in local_pluggables(PluggableType.INPUT):
                if problem_name in self.get_input_problems(name):
                    # set to the first input to solve the problem
                    input_name = name
                    break

        if input_name is None:
            # just remove from schema if none solves the problem
            if PluggableType.INPUT.value in self.json_schema.schema['properties']:
                del self.json_schema.schema['properties'][PluggableType.INPUT.value]
            return

        if default_name is None:
            default_name = input_name

        config = {}
        try:
            config = get_pluggable_configuration(PluggableType.INPUT, input_name)
        except Exception:  # pylint: disable=broad-except
            pass

        input_schema = config['input_schema'] if 'input_schema' in config else {}
        properties = input_schema['properties'] if 'properties' in input_schema else {}
        properties[JSONSchema.NAME] = {'type': 'string'}
        required = input_schema['required'] if 'required' in input_schema else []
        additional_properties = input_schema['additionalProperties'] \
            if 'additionalProperties' in input_schema else True
        if default_name is not None:
            properties[JSONSchema.NAME]['default'] = default_name
            required.append(JSONSchema.NAME)

        if PluggableType.INPUT.value not in self.json_schema.schema['properties']:
            self.json_schema.schema['properties'][PluggableType.INPUT.value] = {'type': 'object'}

        self.json_schema.schema['properties'][PluggableType.INPUT.value]['properties'] = properties
        self.json_schema.schema['properties'][PluggableType.INPUT.value]['required'] = required
        self.json_schema.schema['properties'][PluggableType.INPUT.value]['additionalProperties'] = \
            additional_properties
Пример #11
0
    def _load_data(self):
        if self._data_loaded:
            return

        from qiskit.aqua import (local_pluggables_types, local_pluggables,
                                 get_pluggable_configuration)

        self._schema_property_titles = OrderedDict()
        self._sections = OrderedDict()
        for pluggable_type in sorted(local_pluggables_types(),
                                     key=lambda x: x.value):
            self._sections[pluggable_type.value] = OrderedDict()
            self._schema_property_titles[pluggable_type.value] = OrderedDict()
            for pluggable_name in sorted(local_pluggables(pluggable_type)):
                config = copy.deepcopy(
                    get_pluggable_configuration(pluggable_type,
                                                pluggable_name))
                self._populate_section(pluggable_type.value, pluggable_name,
                                       config)

        self._data_loaded = True
    def set_section(self, section_name):
        """ set section """
        if self._parser is None:
            raise Exception('Input not initialized.')

        value = self._parser.get_section_default_properties(section_name)
        if isinstance(value, dict):
            from qiskit.aqua.parser import JSONSchema
            # if there is no pluggable default name, use the first one found
            if value.get(JSONSchema.NAME, '') == '' and \
               BaseModel.is_pluggable_section(section_name):
                from qiskit.aqua import local_pluggables
                pluggable_names = local_pluggables(section_name)
                if pluggable_names:
                    value[JSONSchema.NAME] = pluggable_names[0]

            for property_name, property_value in value.items():
                self._parser.set_section_property(section_name, property_name,
                                                  property_value)

            # do one more time in case schema was updated
            value = self._parser.get_section_default_properties(section_name)
            for property_name, property_value in value.items():
                self._parser.set_section_property(section_name, property_name,
                                                  property_value)
        else:
            if value is None:
                types = self._parser.get_section_types(section_name)
                if 'null' not in types:
                    if 'string' in types:
                        value = ''
                    elif 'object' in types:
                        value = {}
                    elif 'array' in types:
                        value = []

            self._parser.set_section_data(section_name, value)