def run(self, input, output=None): if input is None: raise ACQUAChemistryError("Missing input.") self._parser = InputParser(input) self._parser.parse() driver_return = self._run_driver_from_parser(self._parser, False) if driver_return[0] == ACQUAChemistry._DRIVER_RUN_TO_HDF5: logger.info('No further process.') return {'printable': [driver_return[1]]} data = run_algorithm(driver_return[1], driver_return[2], True) if not isinstance(data, dict): raise ACQUAChemistryError( "Algorithm run result should be a dictionary") if logger.isEnabledFor(logging.DEBUG): logger.debug('Algorithm returned: {}'.format( json.dumps(data, indent=4))) convert_json_to_dict(data) lines, result = self._format_result(data) logger.info('Processing complete. Final result available') result['printable'] = lines if output is not None: with open(output, 'w') as f: for line in lines: print(line, file=f) return result
def test_load_from_dict(self): json_dict = self.parser.to_JSON() p = InputParser(json_dict) p.parse() dict1 = json.loads(json.dumps(self.parser.to_dictionary())) dict2 = json.loads(json.dumps(p.to_dictionary())) self.assertEqual(dict1, dict2)
def test_save(self): save_path = self._get_resource_path('output.txt') self.parser.save_to_file(save_path) p = InputParser(save_path) p.parse() os.remove(save_path) dict1 = json.loads(json.dumps(self.parser.to_dictionary())) dict2 = json.loads(json.dumps(p.to_dictionary())) self.assertEqual(dict1, dict2)
def _run_drive(self, input, save_json_algo_file): if input is None: raise ACQUAChemistryError("Missing input.") self._parser = InputParser(input) self._parser.parse() driver_return = self._run_driver_from_parser(self._parser, save_json_algo_file) driver_return[1]['input'] = driver_return[2].to_params() driver_return[1]['input']['name'] = driver_return[2].configuration[ 'name'] return driver_return[1]
def test_is_modified(self): json_dict = self.parser.to_JSON() p = InputParser(json_dict) p.parse() p.set_section_property('optimizer', 'maxfun', 1002) self.assertTrue(p.is_modified()) self.assertEqual(p.get_section_property('optimizer', 'maxfun'), 1002)
def load_file(self,filename): if filename is None: return [] try: self._parser = InputParser(filename) self._parser.parse() uipreferences = UIPreferences() if uipreferences.get_populate_defaults(True): self._parser.validate_merge_defaults() self._parser.commit_changes() return self._parser.get_section_names() except: self._parser = None raise
def delete_section_property(self, section_name, property_name): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') self._parser.delete_section_property(section_name, property_name) if InputParser.is_pluggable_section(section_name) and property_name == InputParser.NAME: self._parser.delete_section_properties(section_name)
def new(self): try: dict = {} jsonfile = os.path.join(os.path.dirname(__file__), 'input_template.json') with open(jsonfile) as json_file: dict = json.load(json_file) self._parser = InputParser(dict) self._parser.parse() uipreferences = UIPreferences() if uipreferences.get_populate_defaults(True): self._parser.validate_merge_defaults() self._parser.commit_changes() return self._parser.get_section_names() except: self._parser = None raise
def test_validate(self): json_dict = self.parser.to_JSON() p = InputParser(json_dict) p.parse() try: p.validate_merge_defaults() except Exception as e: self.fail(str(e)) p.set_section_property('optimizer', 'dummy', 1002) self.assertRaises(ACQUAChemistryError, p.validate_merge_defaults)
class TestInputParser(QISKitAcquaChemistryTestCase): """InputParser tests.""" def setUp(self): filepath = self._get_resource_path('test_input_parser.txt') self.parser = InputParser(filepath) self.parser.parse() def test_save(self): save_path = self._get_resource_path('output.txt') self.parser.save_to_file(save_path) p = InputParser(save_path) p.parse() os.remove(save_path) dict1 = json.loads(json.dumps(self.parser.to_dictionary())) dict2 = json.loads(json.dumps(p.to_dictionary())) self.assertEqual(dict1, dict2) def test_load_from_dict(self): json_dict = self.parser.to_JSON() p = InputParser(json_dict) p.parse() dict1 = json.loads(json.dumps(self.parser.to_dictionary())) dict2 = json.loads(json.dumps(p.to_dictionary())) self.assertEqual(dict1, dict2) def test_is_modified(self): json_dict = self.parser.to_JSON() p = InputParser(json_dict) p.parse() p.set_section_property('optimizer', 'maxfun', 1002) self.assertTrue(p.is_modified()) self.assertEqual(p.get_section_property('optimizer', 'maxfun'), 1002) def test_validate(self): json_dict = self.parser.to_JSON() p = InputParser(json_dict) p.parse() try: p.validate_merge_defaults() except Exception as e: self.fail(str(e)) p.set_section_property('optimizer', 'dummy', 1002) self.assertRaises(ACQUAChemistryError, p.validate_merge_defaults)
def set_section_property(self, section_name, property_name, value): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') self._parser.set_section_property(section_name,property_name,value) if InputParser.is_pluggable_section(section_name) and property_name == InputParser.NAME: properties = self._parser.get_section_default_properties(section_name) if isinstance(properties,dict): properties[ InputParser.NAME] = value self._parser.delete_section_properties(section_name) for property_name,property_value in properties.items(): self._parser.set_section_property(section_name,property_name,property_value)
def get_operator_section_names(self): problem_name = None if self._parser is not None: problem_name = self.get_section_property(InputParser.PROBLEM,InputParser.NAME) if problem_name is None: problem_name = self.get_property_default_value(InputParser.PROBLEM,InputParser.NAME) if problem_name is None: return local_chemistry_operators() operator_names = [] for operator_name in local_chemistry_operators(): problems = InputParser.get_operator_problems(operator_name) if problem_name in problems: operator_names.append(operator_name) return operator_names
def get_pluggable_section_names(self,section_name): if not Model.is_pluggable_section(section_name): return [] if InputParser.ALGORITHM == section_name: problem_name = None if self._parser is not None: problem_name = self.get_section_property(InputParser.PROBLEM,InputParser.NAME) if problem_name is None: problem_name = self.get_property_default_value(InputParser.PROBLEM,InputParser.NAME) if problem_name is None: return local_pluggables(InputParser.ALGORITHM) algo_names = [] for algo_name in local_pluggables(InputParser.ALGORITHM): problems = InputParser.get_algorithm_problems(algo_name) if problem_name in problems: algo_names.append(algo_name) return algo_names return local_pluggables(section_name)
def is_pluggable_section(section_name): return InputParser.is_pluggable_section(section_name)
def setUp(self): filepath = self._get_resource_path('test_input_parser.txt') self.parser = InputParser(filepath) self.parser.parse()
class Model(object): def __init__(self): """Create Model object.""" self._configuration_mgr = ConfigurationManager() self._parser = InputParser() def is_empty(self): return self._parser is None or len(self._parser.get_section_names()) == 0 def new(self): try: dict = {} jsonfile = os.path.join(os.path.dirname(__file__), 'input_template.json') with open(jsonfile) as json_file: dict = json.load(json_file) self._parser = InputParser(dict) self._parser.parse() uipreferences = UIPreferences() if uipreferences.get_populate_defaults(True): self._parser.validate_merge_defaults() self._parser.commit_changes() return self._parser.get_section_names() except: self._parser = None raise def load_file(self,filename): if filename is None: return [] try: self._parser = InputParser(filename) self._parser.parse() uipreferences = UIPreferences() if uipreferences.get_populate_defaults(True): self._parser.validate_merge_defaults() self._parser.commit_changes() return self._parser.get_section_names() except: self._parser = None raise def get_filename(self): if self._parser is None: return None return self._parser.get_filename() def is_modified(self): if self._parser is None: return False return self._parser.is_modified() def save_to_file(self,filename): if self.is_empty(): raise ACQUAChemistryError("Empty input data.") self._parser.save_to_file(filename) def get_dictionary(self): if self.is_empty(): raise ACQUAChemistryError("Empty input data.") return self._parser.to_dictionary() def export_dictionary(self,filename): if self.is_empty(): raise ACQUAChemistryError("Empty input data.") self._parser.export_dictionary(filename) def get_section_names(self): if self._parser is None: return [] return self._parser.get_section_names() def get_property_default_values(self,section_name,property_name): if self._parser is None: return None return self._parser.get_property_default_values(section_name,property_name) def section_is_text(self,section_name): if self._parser is None: return False return self._parser.section_is_text(section_name) def get_section_text(self,section_name): if self._parser is None: return '' return self._parser.get_section_text(section_name) def get_section_data(self,section_name): if self._parser is None: return None return self._parser.get_section_data(section_name) def get_section_properties(self,section_name): if self._parser is None: return {} return self._parser.get_section_properties(section_name) def get_section_properties_with_substitution(self,section_name): properties = self.get_section_properties(section_name) result_tuples = self._parser.check_if_substitution_key(section_name,list(properties.keys())) properties_with_substitution = {} for result_tuple in result_tuples: properties_with_substitution[result_tuple[0]] = (properties[result_tuple[0]],result_tuple[1]) return properties_with_substitution def default_properties_equals_properties(self,section_name): if self.section_is_text(section_name): return self.get_section_default_properties(section_name) == self.get_section_data(section_name) default_properties = self.get_section_default_properties(section_name) properties = self.get_section_properties(section_name) if not isinstance(default_properties,dict) or not isinstance(properties,dict): return default_properties == properties if InputParser.NAME in properties: default_properties[InputParser.NAME] = properties[InputParser.NAME] if len(default_properties) != len(properties): return False substitution_tuples = self._parser.check_if_substitution_key(section_name,list(properties.keys())) for substitution_tuple in substitution_tuples: property_name = substitution_tuple[0] if property_name not in default_properties: return False if not substitution_tuple[1]: if default_properties[property_name] != properties[property_name]: return False return True def get_section_property(self,section_name,property_name): if self._parser is None: return None return self._parser.get_section_property(section_name,property_name) def get_section(self,section_name): return self._parser.get_section(section_name) if self._parser is not None else None def set_section(self,section_name): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') self._parser.set_section(section_name) value = self._parser.get_section_default_properties(section_name) if isinstance(value,dict): 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) def set_default_properties_for_name(self,section_name): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') name = self._parser.get_section_property(section_name,InputParser.NAME) self._parser.delete_section_properties(section_name) if name is not None: self._parser.set_section_property(section_name,InputParser.NAME,name) value = self._parser.get_section_default_properties(section_name) if isinstance(value,dict): for property_name,property_value in value.items(): if property_name != InputParser.NAME: 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) @staticmethod def is_pluggable_section(section_name): return InputParser.is_pluggable_section(section_name) def get_operator_section_names(self): problem_name = None if self._parser is not None: problem_name = self.get_section_property(InputParser.PROBLEM,InputParser.NAME) if problem_name is None: problem_name = self.get_property_default_value(InputParser.PROBLEM,InputParser.NAME) if problem_name is None: return local_chemistry_operators() operator_names = [] for operator_name in local_chemistry_operators(): problems = InputParser.get_operator_problems(operator_name) if problem_name in problems: operator_names.append(operator_name) return operator_names def get_pluggable_section_names(self,section_name): if not Model.is_pluggable_section(section_name): return [] if InputParser.ALGORITHM == section_name: problem_name = None if self._parser is not None: problem_name = self.get_section_property(InputParser.PROBLEM,InputParser.NAME) if problem_name is None: problem_name = self.get_property_default_value(InputParser.PROBLEM,InputParser.NAME) if problem_name is None: return local_pluggables(InputParser.ALGORITHM) algo_names = [] for algo_name in local_pluggables(InputParser.ALGORITHM): problems = InputParser.get_algorithm_problems(algo_name) if problem_name in problems: algo_names.append(algo_name) return algo_names return local_pluggables(section_name) def delete_section(self, section_name): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') self._parser.delete_section(section_name) def get_default_sections(self): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') return self._parser.get_default_sections() def get_section_default_properties(self,section_name): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') return self._parser.get_section_default_properties(section_name) def allows_additional_properties(self,section_name): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') return self._parser.allows_additional_properties(section_name) def get_property_default_value(self,section_name,property_name): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') return self._parser.get_property_default_value(section_name,property_name) def get_property_types(self,section_name,property_name): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') return self._parser.get_property_types(section_name,property_name) def set_section_property(self, section_name, property_name, value): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') self._parser.set_section_property(section_name,property_name,value) if InputParser.is_pluggable_section(section_name) and property_name == InputParser.NAME: properties = self._parser.get_section_default_properties(section_name) if isinstance(properties,dict): properties[ InputParser.NAME] = value self._parser.delete_section_properties(section_name) for property_name,property_value in properties.items(): self._parser.set_section_property(section_name,property_name,property_value) def delete_section_property(self, section_name, property_name): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') self._parser.delete_section_property(section_name, property_name) if InputParser.is_pluggable_section(section_name) and property_name == InputParser.NAME: self._parser.delete_section_properties(section_name) def set_section_text(self, section_name, value): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') self._parser.set_section_data(section_name, value) def delete_section_text(self, section_name): if self._parser is None: raise ACQUAChemistryError('Input not initialized.') self._parser.delete_section_text(section_name)
class ACQUAChemistry(object): """Main entry point.""" KEY_HDF5_OUTPUT = 'hdf5_output' _DRIVER_RUN_TO_HDF5 = 1 _DRIVER_RUN_TO_ALGO_INPUT = 2 def __init__(self): """Create an ACQUAChemistry object.""" self._configuration_mgr = ConfigurationManager() self._parser = None self._core = None def get_effective_logging_level(self): """ Returns the logging level being used by ACQUA Chemistry """ levels = get_logger_levels_for_names( ['qiskit_acqua_chemistry', 'qiskit_acqua']) return levels[0] def set_logging(self, level=logging.INFO): """Sets logging output of the logging messages. Sets the output of logging messages (above level `level`) by configuring the logger accordingly. Disables logging if set to logging.NOTSET Params: level (int): minimum severity of the messages that are displayed. """ logging_config = build_logging_config( ['qiskit_acqua_chemistry', 'qiskit_acqua'], level) preferences = Preferences() preferences.set_logging_config(logging_config) preferences.save() set_logger_config(logging_config) def run(self, input, output=None): if input is None: raise ACQUAChemistryError("Missing input.") self._parser = InputParser(input) self._parser.parse() driver_return = self._run_driver_from_parser(self._parser, False) if driver_return[0] == ACQUAChemistry._DRIVER_RUN_TO_HDF5: logger.info('No further process.') return {'printable': [driver_return[1]]} data = run_algorithm(driver_return[1], driver_return[2], True) if not isinstance(data, dict): raise ACQUAChemistryError( "Algorithm run result should be a dictionary") if logger.isEnabledFor(logging.DEBUG): logger.debug('Algorithm returned: {}'.format( json.dumps(data, indent=4))) convert_json_to_dict(data) lines, result = self._format_result(data) logger.info('Processing complete. Final result available') result['printable'] = lines if output is not None: with open(output, 'w') as f: for line in lines: print(line, file=f) return result def save_input(self, input_file): """Save the input of a run to a file. Params: input_file (string): file path """ if self._parser is None: raise ACQUAChemistryError("Missing input information.") self._parser.save_to_file(input_file) def run_drive_to_jsonfile(self, input, jsonfile): if jsonfile is None: raise ACQUAChemistryError("Missing json file") data = self._run_drive(input, True) if data is None: logger.info('No data to save. No further process.') return logger.debug('Result: {}'.format( json.dumps(data, sort_keys=True, indent=4))) with open(jsonfile, 'w') as fp: json.dump(data, fp, sort_keys=True, indent=4) print("Algorithm input file saved: '{}'".format(jsonfile)) def run_algorithm_from_jsonfile(self, jsonfile, output=None): with open(jsonfile) as json_file: return self.run_algorithm_from_json(json.load(json_file), output) def run_algorithm_from_json(self, params, output=None): ret = run_algorithm(params, None, True) if not isinstance(ret, dict): raise ACQUAChemistryError( "Algorithm run result should be a dictionary") logger.debug('Algorithm returned: {}'.format(json.dumps(ret, indent=4))) convert_json_to_dict(ret) print('Output:') if isinstance(ret, dict): for k, v in ret.items(): print("'{}': {}".format(k, v)) else: print(ret) return ret def _format_result(self, data): lines, result = self._core.process_algorithm_result(data) return lines, result def run_drive(self, input): return self._run_drive(input, False) def _run_drive(self, input, save_json_algo_file): if input is None: raise ACQUAChemistryError("Missing input.") self._parser = InputParser(input) self._parser.parse() driver_return = self._run_driver_from_parser(self._parser, save_json_algo_file) driver_return[1]['input'] = driver_return[2].to_params() driver_return[1]['input']['name'] = driver_return[2].configuration[ 'name'] return driver_return[1] def _run_driver_from_parser(self, p, save_json_algo_file): if p is None: raise ACQUAChemistryError("Missing parser") p.validate_merge_defaults() #logger.debug('ALgorithm Input Schema: {}'.format(json.dumps(p.to_JSON(), sort_keys=True, indent=4))) experiment_name = "-- no &NAME section found --" if InputParser.NAME in p.get_section_names(): name_sect = p.get_section(InputParser.NAME) if 'data' in name_sect: experiment_name = name_sect['data'] logger.info('Running chemistry problem from input file: {}'.format( p.get_filename())) logger.info('Experiment description: {}'.format( experiment_name.rstrip())) driver_name = p.get_section_property(InputParser.DRIVER, InputParser.NAME) if driver_name is None: raise ACQUAChemistryError( 'Property "{0}" missing in section "{1}"'.format( InputParser.NAME, InputParser.DRIVER)) hdf5_file = p.get_section_property(InputParser.DRIVER, ACQUAChemistry.KEY_HDF5_OUTPUT) section = p.get_section(driver_name) if 'data' not in section: raise ACQUAChemistryError( 'Property "data" missing in section "{0}"'.format(driver_name)) if driver_name not in self._configuration_mgr.module_names: raise ACQUAChemistryError( 'Driver "{0}" missing in local drivers'.format(driver_name)) work_path = None input_file = p.get_filename() if input_file is not None: work_path = os.path.dirname(os.path.realpath(input_file)) driver = self._configuration_mgr.get_driver_instance(driver_name) driver.work_path = work_path molecule = driver.run(section) if work_path is not None and hdf5_file is not None and not os.path.isabs( hdf5_file): hdf5_file = os.path.abspath(os.path.join(work_path, hdf5_file)) molecule.log() if hdf5_file is not None: molecule._origin_driver_name = driver_name molecule._origin_driver_config = section['data'] molecule.save(hdf5_file) text = "HDF5 file saved '{}'".format(hdf5_file) logger.info(text) if not save_json_algo_file: logger.info('Run ended with hdf5 file saved.') return ACQUAChemistry._DRIVER_RUN_TO_HDF5, text # Run the Hamiltonian to process the QMolecule and get an input for algorithms self._core = get_chemistry_operator_instance( p.get_section_property(InputParser.OPERATOR, InputParser.NAME)) self._core.init_params(p.get_section_properties(InputParser.OPERATOR)) input_object = self._core.run(molecule) logger.debug('Core computed substitution variables {}'.format( self._core.molecule_info)) result = p.process_substitutions(self._core.molecule_info) logger.debug('Substitutions {}'.format(result)) params = {} for section_name, section in p.get_sections().items(): if section_name == InputParser.NAME or \ section_name == InputParser.DRIVER or \ section_name == driver_name.lower() or \ section_name == InputParser.OPERATOR or \ 'properties' not in section: continue params[section_name] = copy.deepcopy(section['properties']) if InputParser.PROBLEM == section_name and \ InputParser.ENABLE_SUBSTITUTIONS in params[section_name]: del params[section_name][InputParser.ENABLE_SUBSTITUTIONS] return ACQUAChemistry._DRIVER_RUN_TO_ALGO_INPUT, params, input_object
def __init__(self): """Create Model object.""" self._configuration_mgr = ConfigurationManager() self._parser = InputParser()