def load_file(self, filename): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua.parser import JSONSchema from qiskit_aqua import get_provider_from_backend, get_backends_from_provider if filename is None: return [] try: self._parser = InputParser(filename) self._parser.parse() # before merging defaults attempts to find a provider for the backend provider = self._parser.get_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER) if provider is None: backend_name = self._parser.get_section_property(JSONSchema.BACKEND, JSONSchema.NAME) if backend_name is not None: self._parser.set_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER, get_provider_from_backend(backend_name)) else: try: if provider not in self.providers: self._custom_providers[provider] = get_backends_from_provider(provider) except Exception as e: logger.debug(str(e)) 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_load_from_dict(self): json_dict = self.parser.get_sections() p = InputParser(json_dict) p.parse() dict1 = json.loads(json.dumps(self.parser.get_sections())) dict2 = json.loads(json.dumps(p.get_sections())) 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.get_sections())) dict2 = json.loads(json.dumps(p.get_sections())) self.assertEqual(dict1, dict2)
def test_is_modified(self): json_dict = self.parser.get_sections() 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): from qiskit_aqua.parser._inputparser import InputParser 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_pluggable_section_names(self, section_name): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua import PluggableType, local_pluggables from qiskit_aqua.parser import JSONSchema if not Model.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 = 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 run_algorithm_to_json(params, algo_input=None, jsonfile='algorithm.json'): """ Run algorithm as named in params, using params and algo_input as input data and save the combined input as a json file. This json is self-contained and can later be used as a basis to call run_algorithm Args: params (dict): Dictionary of params for algo and dependent objects algo_input(algorithminput): Main input data for algorithm. Optional, an algo may run entirely from params jsonfile(string): Name of file in which json should be saved Returns: Result dictionary containing the jsonfile name """ _discover_on_demand() inputparser = InputParser(params) inputparser.parse() inputparser.validate_merge_defaults() algo_params = copy.deepcopy(inputparser.get_sections()) if algo_input is not None: input_params = algo_input.to_params() convert_dict_to_json(input_params) algo_params['input'] = input_params algo_params['input']['name'] = algo_input.configuration['name'] logger.debug('Result: {}'.format(json.dumps(algo_params, sort_keys=True, indent=4))) with open(jsonfile, 'w') as fp: json.dump(algo_params, fp, sort_keys=True, indent=4) logger.info("Algorithm input file saved: '{}'".format(jsonfile)) return {'jsonfile': jsonfile}
def new(self): from qiskit_aqua.parser._inputparser import InputParser 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 delete_section_property(self, section_name, property_name): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua.parser import JSONSchema if self._parser is None: raise Exception('Input not initialized.') self._parser.delete_section_property(section_name, property_name) if property_name == JSONSchema.NAME and \ (InputParser.is_pluggable_section(section_name)): self._parser.delete_section_properties(section_name)
def test_validate(self): json_dict = self.parser.get_sections() 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(AquaError, p.validate_merge_defaults)
def set_section_property(self, section_name, property_name, value): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua.parser import JSONSchema if self._parser is None: raise Exception('Input not initialized.') self._parser.set_section_property(section_name, property_name, value) if property_name == JSONSchema.NAME and \ (InputParser.is_pluggable_section(section_name)): properties = self._parser.get_section_default_properties( section_name) if isinstance(properties, dict): properties[JSONSchema.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_input_section_names(self): 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
def set_section_property(self, section_name, property_name, value): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua.parser import JSONSchema from qiskit_aqua import get_backends_from_provider if self._parser is None: raise Exception('Input not initialized.') self._parser.set_section_property(section_name, property_name, value) if property_name == JSONSchema.NAME and InputParser.is_pluggable_section(section_name): properties = self._parser.get_section_default_properties(section_name) if isinstance(properties, dict): properties[JSONSchema.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) elif section_name == JSONSchema.BACKEND and property_name == JSONSchema.PROVIDER: backends = get_backends_from_provider(value) if value not in self.providers: self._custom_providers[value] = backends backend = backends[0] if len(backends) > 0 else '' self._parser.set_section_property(section_name, JSONSchema.NAME, backend)
class Model(object): def __init__(self): """Create Model object.""" self._parser = None self._custom_providers = {} self._available_providers = {} self._backendsthread = None self.get_available_providers() @property def providers(self): providers = copy.deepcopy(self._custom_providers) providers.update(self._available_providers) return providers def get_available_providers(self): from qiskit_aqua import register_ibmq_and_get_known_providers if self._backendsthread is not None: return self._register_ibmq_and_get_known_providers = register_ibmq_and_get_known_providers self._backendsthread = threading.Thread(target=self._get_available_providers, name='Aqua available providers') self._backendsthread.daemon = True self._backendsthread.start() def _get_available_providers(self): try: self._available_providers = OrderedDict([x for x in self._register_ibmq_and_get_known_providers().items() if len(x[1]) > 0]) except Exception as e: logger.debug(str(e)) finally: self._backendsthread = None def is_empty(self): return self._parser is None or len(self._parser.get_section_names()) == 0 def new(self): from qiskit_aqua.parser._inputparser import InputParser 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): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua.parser import JSONSchema from qiskit_aqua import get_provider_from_backend, get_backends_from_provider if filename is None: return [] try: self._parser = InputParser(filename) self._parser.parse() # before merging defaults attempts to find a provider for the backend provider = self._parser.get_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER) if provider is None: backend_name = self._parser.get_section_property(JSONSchema.BACKEND, JSONSchema.NAME) if backend_name is not None: self._parser.set_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER, get_provider_from_backend(backend_name)) else: try: if provider not in self.providers: self._custom_providers[provider] = get_backends_from_provider(provider) except Exception as e: logger.debug(str(e)) 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 Exception("Empty input data.") self._parser.save_to_file(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(self, section_name): return self._parser.get_section(section_name) if self._parser is not None else None def get_section_text(self, section_name): if self._parser is None: return '' return self._parser.get_section_text(section_name) def get_section_properties(self, section_name): if self._parser is None: return {} return self._parser.get_section_properties(section_name) def default_properties_equals_properties(self, section_name): from qiskit_aqua.parser import JSONSchema 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) if isinstance(default_properties, OrderedDict): default_properties = dict(default_properties) properties = self.get_section_properties(section_name) if isinstance(properties, OrderedDict): properties = dict(properties) if not isinstance(default_properties, dict) or not isinstance(properties, dict): return default_properties == properties if JSONSchema.BACKEND != section_name and JSONSchema.NAME in properties: default_properties[JSONSchema.NAME] = properties[JSONSchema.NAME] return default_properties == properties 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 set_section(self, section_name): if self._parser is None: raise Exception('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): from qiskit_aqua.parser import JSONSchema if self._parser is None: raise Exception('Input not initialized.') name = self._parser.get_section_property(section_name, JSONSchema.NAME) self._parser.delete_section_properties(section_name) value = self._parser.get_section_default_properties(section_name) if JSONSchema.BACKEND != section_name and name is not None: self._parser.set_section_property(section_name, JSONSchema.NAME, name) if isinstance(value, dict): for property_name, property_value in value.items(): if JSONSchema.BACKEND == section_name or property_name != JSONSchema.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): from qiskit_aqua.parser._inputparser import InputParser return InputParser.is_pluggable_section(section_name) def get_input_section_names(self): 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 def get_pluggable_section_names(self, section_name): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua import PluggableType, local_pluggables from qiskit_aqua.parser import JSONSchema if not Model.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 = 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 Exception('Input not initialized.') self._parser.delete_section(section_name) def get_default_sections(self): if self._parser is None: raise Exception('Input not initialized.') return self._parser.get_default_sections() def get_section_default_properties(self, section_name): if self._parser is None: raise Exception('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 Exception('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 Exception('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 Exception('Input not initialized.') return self._parser.get_property_types(section_name, property_name) def set_section_property(self, section_name, property_name, value): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua.parser import JSONSchema from qiskit_aqua import get_backends_from_provider if self._parser is None: raise Exception('Input not initialized.') self._parser.set_section_property(section_name, property_name, value) if property_name == JSONSchema.NAME and InputParser.is_pluggable_section(section_name): properties = self._parser.get_section_default_properties(section_name) if isinstance(properties, dict): properties[JSONSchema.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) elif section_name == JSONSchema.BACKEND and property_name == JSONSchema.PROVIDER: backends = get_backends_from_provider(value) if value not in self.providers: self._custom_providers[value] = backends backend = backends[0] if len(backends) > 0 else '' self._parser.set_section_property(section_name, JSONSchema.NAME, backend) def delete_section_property(self, section_name, property_name): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua.parser import JSONSchema if self._parser is None: raise Exception('Input not initialized.') self._parser.delete_section_property(section_name, property_name) if property_name == JSONSchema.NAME and InputParser.is_pluggable_section(section_name): self._parser.delete_section_properties(section_name) elif section_name == JSONSchema.BACKEND and (property_name == JSONSchema.PROVIDER or property_name == JSONSchema.NAME): self._parser.delete_section_properties(section_name) def set_section_text(self, section_name, value): if self._parser is None: raise Exception('Input not initialized.') self._parser.set_section_data(section_name, value) def delete_section_text(self, section_name): if self._parser is None: raise Exception('Input not initialized.') self._parser.delete_section_text(section_name)
def is_pluggable_section(section_name): from qiskit_aqua.parser._inputparser import InputParser return InputParser.is_pluggable_section(section_name)
def setUp(self): filepath = self._get_resource_path('H2-0.735.json') self.parser = InputParser(filepath) self.parser.parse()
def run_algorithm(params, algo_input=None, json_output=False): """ Run algorithm as named in params, using params and algo_input as input data and returning a result dictionary Args: params (dict): Dictionary of params for algo and dependent objects algo_input(algorithminput): Main input data for algorithm. Optional, an algo may run entirely from params json_output(bool): False for regular python dictionary return, True for json conversion Returns: Result dictionary containing result of algorithm computation """ _discover_on_demand() inputparser = InputParser(params) inputparser.parse() inputparser.validate_merge_defaults() logger.debug('Algorithm Input: {}'.format(json.dumps(inputparser.get_sections(), sort_keys=True, indent=4))) algo_name = inputparser.get_section_property(JSONSchema.ALGORITHM, JSONSchema.NAME) if algo_name is None: raise AlgorithmError('Missing algorithm name') if algo_name not in local_algorithms(): raise AlgorithmError('Algorithm "{0}" missing in local algorithms'.format(algo_name)) backend_cfg = None backend = inputparser.get_section_property(JSONSchema.BACKEND, JSONSchema.NAME) if backend is not None: backend_cfg = {k: v for k, v in inputparser.get_section(JSONSchema.BACKEND).items() if k != 'name'} backend_cfg['backend'] = backend algorithm = get_algorithm_instance(algo_name) algorithm.random_seed = inputparser.get_section_property(JSONSchema.PROBLEM, 'random_seed') if backend_cfg is not None: algorithm.setup_quantum_backend(**backend_cfg) algo_params = copy.deepcopy(inputparser.get_sections()) if algo_input is None: input_name = inputparser.get_section_property('input', JSONSchema.NAME) if input_name is not None: algo_input = get_input_instance(input_name) input_params = copy.deepcopy(inputparser.get_section_properties('input')) del input_params[JSONSchema.NAME] convert_json_to_dict(input_params) algo_input.from_params(input_params) algorithm.init_params(algo_params, algo_input) value = algorithm.run() if isinstance(value, dict) and json_output: convert_dict_to_json(value) return value
class Model(object): def __init__(self): """Create Model object.""" self._parser = None def is_empty(self): return self._parser is None or len( self._parser.get_section_names()) == 0 def new(self): from qiskit_aqua.parser._inputparser import InputParser 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): from qiskit_aqua.parser._inputparser import InputParser 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 Exception("Empty input data.") self._parser.save_to_file(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(self, section_name): return self._parser.get_section( section_name) if self._parser is not None else None def get_section_text(self, section_name): if self._parser is None: return '' return self._parser.get_section_text(section_name) def get_section_properties(self, section_name): if self._parser is None: return {} return self._parser.get_section_properties(section_name) def default_properties_equals_properties(self, section_name): from qiskit_aqua.parser import JSONSchema 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) if isinstance(default_properties, OrderedDict): default_properties = dict(default_properties) properties = self.get_section_properties(section_name) if isinstance(properties, OrderedDict): properties = dict(properties) if not isinstance(default_properties, dict) or not isinstance( properties, dict): return default_properties == properties if JSONSchema.NAME in properties: default_properties[JSONSchema.NAME] = properties[JSONSchema.NAME] return default_properties == properties 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 set_section(self, section_name): if self._parser is None: raise Exception('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): from qiskit_aqua.parser import JSONSchema if self._parser is None: raise Exception('Input not initialized.') name = self._parser.get_section_property(section_name, JSONSchema.NAME) self._parser.delete_section_properties(section_name) value = self._parser.get_section_default_properties(section_name) if name is not None: self._parser.set_section_property(section_name, JSONSchema.NAME, name) if isinstance(value, dict): for property_name, property_value in value.items(): if property_name != JSONSchema.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): from qiskit_aqua.parser._inputparser import InputParser return InputParser.is_pluggable_section(section_name) def get_input_section_names(self): 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 def get_pluggable_section_names(self, section_name): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua import PluggableType, local_pluggables from qiskit_aqua.parser import JSONSchema if not Model.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 = 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 Exception('Input not initialized.') self._parser.delete_section(section_name) def get_default_sections(self): if self._parser is None: raise Exception('Input not initialized.') return self._parser.get_default_sections() def get_section_default_properties(self, section_name): if self._parser is None: raise Exception('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 Exception('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 Exception('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 Exception('Input not initialized.') return self._parser.get_property_types(section_name, property_name) def set_section_property(self, section_name, property_name, value): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua.parser import JSONSchema if self._parser is None: raise Exception('Input not initialized.') self._parser.set_section_property(section_name, property_name, value) if property_name == JSONSchema.NAME and \ (InputParser.is_pluggable_section(section_name)): properties = self._parser.get_section_default_properties( section_name) if isinstance(properties, dict): properties[JSONSchema.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): from qiskit_aqua.parser._inputparser import InputParser from qiskit_aqua.parser import JSONSchema if self._parser is None: raise Exception('Input not initialized.') self._parser.delete_section_property(section_name, property_name) if property_name == JSONSchema.NAME and \ (InputParser.is_pluggable_section(section_name)): self._parser.delete_section_properties(section_name) def set_section_text(self, section_name, value): if self._parser is None: raise Exception('Input not initialized.') self._parser.set_section_data(section_name, value) def delete_section_text(self, section_name): if self._parser is None: raise Exception('Input not initialized.') self._parser.delete_section_text(section_name)
def run_algorithm(params, algo_input=None, json_output=False, backend=None): """ Run algorithm as named in params, using params and algo_input as input data and returning a result dictionary Args: params (dict): Dictionary of params for algo and dependent objects algo_input (AlgorithmInput): Main input data for algorithm. Optional, an algo may run entirely from params json_output (bool): False for regular python dictionary return, True for json conversion backend (BaseBackend): Backend object to be used in place of backend name Returns: Result dictionary containing result of algorithm computation """ _discover_on_demand() inputparser = InputParser(params) inputparser.parse() # before merging defaults attempts to find a provider for the backend in case no # provider was passed if backend is None and inputparser.get_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER) is None: backend_name = inputparser.get_section_property(JSONSchema.BACKEND, JSONSchema.NAME) if backend_name is not None: inputparser.set_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER, get_provider_from_backend(backend_name)) inputparser.validate_merge_defaults() logger.debug('Algorithm Input: {}'.format(json.dumps(inputparser.get_sections(), sort_keys=True, indent=4))) algo_name = inputparser.get_section_property(PluggableType.ALGORITHM.value, JSONSchema.NAME) if algo_name is None: raise AquaError('Missing algorithm name') if algo_name not in local_pluggables(PluggableType.ALGORITHM): raise AquaError('Algorithm "{0}" missing in local algorithms'.format(algo_name)) if algo_input is None: input_name = inputparser.get_section_property('input', JSONSchema.NAME) if input_name is not None: input_params = copy.deepcopy(inputparser.get_section_properties('input')) del input_params[JSONSchema.NAME] convert_json_to_dict(input_params) algo_input = get_pluggable_class(PluggableType.INPUT, input_name).from_params(input_params) algo_params = copy.deepcopy(inputparser.get_sections()) algorithm = get_pluggable_class(PluggableType.ALGORITHM, algo_name).init_params(algo_params, algo_input) random_seed = inputparser.get_section_property(JSONSchema.PROBLEM, 'random_seed') algorithm.random_seed = random_seed quantum_instance = None # setup backend backend_provider = inputparser.get_section_property(JSONSchema.BACKEND, JSONSchema.PROVIDER) backend_name = inputparser.get_section_property(JSONSchema.BACKEND, JSONSchema.NAME) if backend_provider is not None and backend_name is not None: # quantum algorithm backend_cfg = {k: v for k, v in inputparser.get_section(JSONSchema.BACKEND).items() if k not in [JSONSchema.PROVIDER, JSONSchema.NAME]} noise_params = backend_cfg.pop('noise_params', None) backend_cfg['config'] = {} backend_cfg['config']['noise_params'] = noise_params backend_cfg['seed'] = random_seed backend_cfg['seed_mapper'] = random_seed pass_manager = PassManager() if backend_cfg.pop('skip_transpiler', False) else None if pass_manager is not None: backend_cfg['pass_manager'] = pass_manager if backend is not None and isinstance(backend, BaseBackend): backend_cfg['backend'] = backend else: backend_cfg['backend'] = get_backend_from_provider(backend_provider, backend_name) quantum_instance = QuantumInstance(**backend_cfg) value = algorithm.run(quantum_instance) if isinstance(value, dict) and json_output: convert_dict_to_json(value) return value
class TestInputParser(QiskitAquaTestCase): """Input Parser and algorithms tests.""" def setUp(self): filepath = self._get_resource_path('H2-0.735.json') 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.get_sections())) dict2 = json.loads(json.dumps(p.get_sections())) self.assertEqual(dict1, dict2) def test_load_from_dict(self): json_dict = self.parser.get_sections() p = InputParser(json_dict) p.parse() dict1 = json.loads(json.dumps(self.parser.get_sections())) dict2 = json.loads(json.dumps(p.get_sections())) self.assertEqual(dict1, dict2) def test_is_modified(self): json_dict = self.parser.get_sections() 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.get_sections() 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(AquaError, p.validate_merge_defaults) def test_run_algorithm(self): filepath = self._get_resource_path('ExactEigensolver.json') params = None with open(filepath) as json_file: params = json.load(json_file) dict_ret = None try: dict_ret = run_algorithm(params, None, False) except Exception as e: self.fail(str(e)) self.assertIsInstance(dict_ret, dict)