Exemplo n.º 1
0
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
Exemplo n.º 2
0
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}
Exemplo n.º 3
0
    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)
Exemplo n.º 4
0
    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)
Exemplo n.º 5
0
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
Exemplo n.º 6
0
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)