Esempio n. 1
0
    def check_if_substitution_key(self, section_name, property_names):
        result = [(property_name, False) for property_name in property_names]
        if not self.is_substitution_allowed():
            return result

        section_name = JSONSchema.format_section_name(section_name).lower()
        property_names = [
            JSONSchema.format_property_name(property_name)
            for property_name in property_names
        ]
        section_property_name = self.get_property_default_value(
            section_name, JSONSchema.NAME)
        section_property_name = self.get_section_property(
            section_name, JSONSchema.NAME, section_property_name)
        for key in self._substitutions.keys():
            key_items = key.split('.')
            if len(key_items) == 3 and \
                    key_items[0] == section_name and \
                    key_items[1] == section_property_name and \
                    key_items[2] in property_names:
                result[property_names.index(key_items[2])] = (key_items[2],
                                                              True)
                continue

        return result
Esempio n. 2
0
 def post_set_section_property(self, section_name, property_name):
     property_name = JSONSchema.format_property_name(property_name)
     if property_name == JSONSchema.NAME:
         section_name = JSONSchema.format_section_name(section_name).lower()
         value = self.get_section_property(section_name, property_name)
         if InputParser.OPERATOR == section_name:
             self._update_operator_input_schema()
         elif JSONSchema.PROBLEM == section_name:
             self._update_operator_problem()
             self._update_operator_input_schema()
             # remove properties that are not valid for this operator
             default_properties = self.get_section_default_properties(
                 InputParser.OPERATOR)
             if isinstance(default_properties, dict):
                 properties = self.get_section_properties(
                     InputParser.OPERATOR)
                 for p_name in list(properties.keys()):
                     if p_name != JSONSchema.NAME and p_name not in default_properties:
                         self.delete_section_property(
                             InputParser.OPERATOR, p_name)
         elif value is not None:
             value = str(value).lower().strip()
             if len(value) > 0 and self.section_is_driver(value):
                 self._update_driver_input_schemas()
                 self._update_driver_sections()
Esempio n. 3
0
    def validate(self, args_dict):
        schema_dict = self.CONFIGURATION.get('input_schema', None)
        if schema_dict is None:
            return

        jsonSchema = JSONSchema(schema_dict)
        schema_property_names = jsonSchema.get_default_section_names()
        json_dict = {}
        for property_name in schema_property_names:
            if property_name in args_dict:
                json_dict[property_name] = args_dict[property_name]

        jsonSchema.validate(json_dict)
Esempio n. 4
0
    def set_section_property(self, section_name, property_name, value):
        section_name = JSONSchema.format_section_name(section_name).lower()
        property_name = JSONSchema.format_property_name(property_name)
        value = self._json_schema.check_property_value(section_name, property_name, value)
        types = self.get_property_types(section_name, property_name)

        sections_temp = copy.deepcopy(self._sections)
        InputParser._set_section_property(sections_temp, section_name, property_name, value, types)
        msg = self._json_schema.validate_property(sections_temp, section_name, property_name)
        if msg is not None:
            raise AquaError("{}.{}: Value '{}': '{}'".format(section_name, property_name, value, msg))

        # check if this provider is loadable and valid
        if JSONSchema.BACKEND == section_name and property_name == JSONSchema.PROVIDER:
            get_backends_from_provider(value)

        InputParser._set_section_property(self._sections, section_name, property_name, value, types)
        if property_name == JSONSchema.NAME:
            if InputParser.OPERATOR == section_name:
                self._update_operator_input_schema()
                # remove properties that are not valid for this section
                default_properties = self.get_section_default_properties(section_name)
                if isinstance(default_properties, dict):
                    properties = self.get_section_properties(section_name)
                    for property_name in list(properties.keys()):
                        if property_name != JSONSchema.NAME and property_name not in default_properties:
                            self.delete_section_property(section_name, property_name)
            elif JSONSchema.PROBLEM == section_name:
                self._update_algorithm_problem()
                self._update_operator_problem()
            elif JSONSchema.BACKEND == section_name:
                self._json_schema.update_backend_schema()
            elif InputParser.is_pluggable_section(section_name):
                self._json_schema.update_pluggable_input_schemas(self)
                # remove properties that are not valid for this section
                default_properties = self.get_section_default_properties(section_name)
                if isinstance(default_properties, dict):
                    properties = self.get_section_properties(section_name)
                    for property_name in list(properties.keys()):
                        if property_name != JSONSchema.NAME and property_name not in default_properties:
                            self.delete_section_property(section_name, property_name)

                if section_name == PluggableType.ALGORITHM.value:
                    self._update_dependency_sections()
            elif value is not None:
                value = str(value).lower().strip()
                if len(value) > 0 and self.section_is_driver(value):
                    self._update_driver_input_schemas()
                    self._update_driver_sections()

        self._sections = self._order_sections(self._sections)
Esempio n. 5
0
 def post_set_section_property(self, section_name, property_name):
     property_name = JSONSchema.format_property_name(property_name)
     if property_name == JSONSchema.NAME:
         section_name = JSONSchema.format_section_name(section_name).lower()
         value = self.get_section_property(section_name, property_name)
         if InputParser.OPERATOR == section_name:
             self._update_operator_input_schema()
         elif JSONSchema.PROBLEM == section_name:
             self._update_operator_problem()
         elif value is not None:
             value = str(value).lower().strip()
             if len(value) > 0 and self.section_is_driver(value):
                 self._update_driver_input_schemas()
                 self._update_driver_sections()
Esempio n. 6
0
    def validate(self, args_dict):
        """ Validates the configuration against the input schema. N.B. Not in use at the moment. """
        schema_dict = self.CONFIGURATION.get('input_schema', None)
        if schema_dict is None:
            return

        jsonSchema = JSONSchema(schema_dict)
        schema_property_names = jsonSchema.get_default_section_names()
        json_dict = {}
        for property_name in schema_property_names:
            if property_name in args_dict:
                json_dict[property_name] = args_dict[property_name]

        jsonSchema.validate(json_dict)
Esempio n. 7
0
    def validate(self, args_dict):
        schema_dict = self.CONFIGURATION.get('input_schema')
        if schema_dict is None:
            return

        jsonSchema = JSONSchema(schema_dict)
        schema_property_names = jsonSchema.get_default_section_names()
        json_dict = {}
        for property_name in schema_property_names:
            if property_name in args_dict:
                value = args_dict[property_name]
                if isinstance(value, np.ndarray):
                    value = value.tolist()
                json_dict[property_name] = value

        jsonSchema.validate(json_dict)
Esempio n. 8
0
 def section_is_driver(self, section_name):
     """ check if this section is a chemistry driver """
     section_name = JSONSchema.format_section_name(section_name).lower()
     InputParser._load_driver_names()
     driver_names = InputParser._DRIVER_NAMES \
         if isinstance(InputParser._DRIVER_NAMES, list) else []
     return section_name in driver_names
Esempio n. 9
0
 def _load_parser_from_dict(self):
     self._sections = OrderedDict()
     for section_name, value in self._inputdict.items():
         section_name = JSONSchema.format_section_name(section_name).lower()
         if isinstance(value, dict):
             self._sections[section_name] = OrderedDict(value)
         elif isinstance(value, list) or isinstance(value, str):
             if isinstance(value, list):
                 self._sections[section_name] = '\n'.join(str(e) for e in value)
             else:
                 self._sections[section_name] = value
         else:
             raise QiskitChemistryError("Invalid parser input type for section {}".format(section_name))
Esempio n. 10
0
    def __init__(self, input=None):
        """Create Parser object."""
        json_schema = JSONSchema(
            os.path.join(os.path.dirname(__file__), 'input_schema.json'))

        # get some properties from algorithms schema
        json_schema.copy_section_from_aqua_schema(
            PluggableType.ALGORITHM.value)
        json_schema.copy_section_from_aqua_schema(JSONSchema.BACKEND)
        json_schema.copy_section_from_aqua_schema(JSONSchema.PROBLEM)
        json_schema.schema['properties'][JSONSchema.PROBLEM]['properties'][
            InputParser.AUTO_SUBSTITUTIONS] = {
                "type": "boolean",
                "default": "true"
            }
        super().__init__(json_schema)

        # limit Chemistry problems to energy and excited_states
        chemistry_problems = [
            problem
            for problem in self.json_schema.get_property_default_values(
                JSONSchema.PROBLEM, JSONSchema.NAME)
            if any(problem == item.value for item in ChemistryProblem)
        ]
        self.json_schema.schema['properties'][JSONSchema.PROBLEM]['properties'][JSONSchema.NAME]['oneOf'] = \
            [{'enum': chemistry_problems}]
        self._json_schema.commit_changes()
        # ---

        self._inputdict = None
        if input is not None:
            if isinstance(input, dict):
                self._inputdict = input
            elif isinstance(input, str):
                self._filename = input
            else:
                raise QiskitChemistryError("Invalid parser input type.")

        self._section_order = [
            JSONSchema.NAME, JSONSchema.PROBLEM, InputParser.DRIVER,
            InputParser._UNKNOWN, InputParser.OPERATOR,
            PluggableType.ALGORITHM.value
        ]
        for pluggable_type in local_pluggables_types():
            if pluggable_type not in [
                    PluggableType.INPUT, PluggableType.ALGORITHM
            ]:
                self._section_order.append(pluggable_type.value)

        self._section_order.extend([JSONSchema.BACKEND, InputParser._UNKNOWN])

        jsonfile = os.path.join(os.path.dirname(__file__),
                                'substitutions.json')
        with open(jsonfile) as json_file:
            self._substitutions = json.load(json_file)
Esempio n. 11
0
    def delete_section(self, section_name):
        """
        Args:
            section_name (str): the name of the section, case insensitive
        """
        section_name = JSONSchema.format_section_name(section_name).lower()
        driver_name = None
        if section_name == InputParser.DRIVER:
            driver_name = self.get_section_property(section_name,
                                                    JSONSchema.NAME)
            if driver_name is not None:
                driver_name = driver_name.strip().lower()

        super().delete_section(section_name)
        if driver_name is not None:
            # delete correspondent driver name section
            super().delete_section(driver_name)

        self._update_driver_input_schemas()
        self._update_operator_input_schema()
Esempio n. 12
0
    def _get_key_value(line):
        stripLine = line.strip()
        pos = -1
        for start_comment in InputParser._START_COMMENTS:
            pos = stripLine.find(start_comment)
            if pos >= 0:
                break

        if pos == 0:
            return (None, None)

        if pos > 0:
            stripLine = stripLine[:pos].strip()

        pos = stripLine.find(InputParser._PROPVALUE_SEPARATOR)
        if pos > 0:
            key = stripLine[0:pos].strip()
            value = stripLine[pos + 1:].strip()
            return (key, JSONSchema.get_value(value))

        return (None, None)
Esempio n. 13
0
 def section_is_driver(self, section_name):
     section_name = JSONSchema.format_section_name(section_name).lower()
     InputParser._load_driver_names()
     return section_name in InputParser._DRIVER_NAMES
 def section_is_driver(self, section_name):
     section_name = JSONSchema.format_section_name(section_name).lower()
     InputParser._load_driver_names()
     driver_names = InputParser._DRIVER_NAMES if isinstance(
         InputParser._DRIVER_NAMES, list) else []
     return section_name in driver_names