def run(self, input, output=None): if input is None: raise AquaChemistryError("Missing input.") self._parser = InputParser(input) self._parser.parse() driver_return = self._run_driver_from_parser(self._parser, False) if driver_return[0] == AquaChemistry._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 AquaChemistryError( "Algorithm run result should be a dictionary") convert_json_to_dict(data) if logger.isEnabledFor(logging.DEBUG): logger.debug('Algorithm returned: {}'.format( pprint.pformat(data, indent=4))) 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_vertex_cover_vqe(self): algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'grouped_paulis', 'batch_mode': True } optimizer_cfg = {'name': 'SPSA', 'max_trials': 200} var_form_cfg = { 'name': 'RYRZ', 'depth': 3, } params = { 'problem': { 'name': 'ising', 'random_seed': 100 }, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = get_aer_backend('qasm_simulator') result = run_algorithm(params, self.algo_input, backend=backend) x = vertexcover.sample_most_likely(len(self.w), result['eigvecs'][0]) sol = vertexcover.get_graph_solution(x) oracle = self.brute_force() self.assertEqual(np.count_nonzero(sol), oracle)
def test_set_packing_vqe(self): algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'grouped_paulis', 'batch_mode': True } optimizer_cfg = {'name': 'SPSA', 'max_trials': 200} var_form_cfg = {'name': 'RY', 'depth': 5, 'entanglement': 'linear'} params = { 'problem': { 'name': 'ising', 'random_seed': 100 }, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = get_aer_backend('qasm_simulator') result = run_algorithm(params, self.algo_input, backend=backend) x = setpacking.sample_most_likely(len(self.list_of_subsets), result['eigvecs'][0]) ising_sol = setpacking.get_solution(x) oracle = self.brute_force() self.assertEqual(np.count_nonzero(ising_sol), oracle)
def test_graph_partition_vqe(self): algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix', 'batch_mode': True } optimizer_cfg = {'name': 'SPSA', 'max_trials': 300} var_form_cfg = {'name': 'RY', 'depth': 5, 'entanglement': 'linear'} params = { 'problem': { 'name': 'ising', 'random_seed': 10598 }, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = get_aer_backend('statevector_simulator') result = run_algorithm(params, self.algo_input, backend=backend) x = graphpartition.sample_most_likely(result['eigvecs'][0]) # check against the oracle ising_sol = graphpartition.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [1, 0, 0, 1]) oracle = self.brute_force() self.assertEqual(graphpartition.objective_value(x, self.w), oracle)
def test_clique_vqe(self): algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'matrix', 'batch_mode': True } optimizer_cfg = {'name': 'COBYLA'} var_form_cfg = {'name': 'RY', 'depth': 5, 'entanglement': 'linear'} params = { 'problem': { 'name': 'ising', 'random_seed': 10598 }, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = get_aer_backend('statevector_simulator') result = run_algorithm(params, self.algo_input, backend=backend) x = clique.sample_most_likely(len(self.w), result['eigvecs'][0]) ising_sol = clique.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [1, 1, 1, 1, 1]) oracle = self.brute_force() self.assertEqual(clique.satisfy_or_not(ising_sol, self.w, self.K), oracle)
def test_vqe_caching_via_run_algorithm(self, backend, caching, skip_qobj_deepcopy, skip_validation): params_caching = { 'algorithm': { 'name': 'VQE' }, 'problem': { 'name': 'energy', 'random_seed': 50, 'circuit_caching': caching, 'skip_qobj_deepcopy': skip_qobj_deepcopy, 'skip_qobj_validation': skip_validation, 'circuit_cache_file': None, }, 'backend': { 'name': backend, 'shots': 1000 }, } result_caching = run_algorithm(params_caching, self.algo_input) self.assertAlmostEqual(result_caching['energy'], self.reference_vqe_result[backend]['energy']) np.testing.assert_array_almost_equal( self.reference_vqe_result[backend]['eigvals'], result_caching['eigvals'], 5) np.testing.assert_array_almost_equal( self.reference_vqe_result[backend]['opt_params'], result_caching['opt_params'], 5) self.assertIn('eval_count', result_caching) self.assertIn('eval_time', result_caching)
def test_end2end_h2(self, name, optimizer, backend, mode, shots): optimizer_params = {'name': optimizer} if optimizer == 'COBYLA': optimizer_params['maxiter'] = 1000 elif optimizer == 'SPSA': optimizer_params['max_trials'] = 2000 optimizer_params['save_steps'] = 25 algo_params = { 'problem': { 'name': 'energy' }, 'backend': { 'name': backend, 'shots': shots }, 'algorithm': { 'name': 'VQE', 'operator_mode': mode }, 'optimizer': optimizer_params, 'variational_form': { 'name': 'RYRZ', 'depth': 3, 'entanglement': 'full' } } results = run_algorithm(algo_params, self.algo_input) self.assertAlmostEqual(results['energy'], self.reference_energy, places=6)
def test_ee_via_run_algorithm(self): params = {'algorithm': {'name': 'ExactEigensolver'}} result = run_algorithm(params, self.algo_input) self.assertAlmostEqual(result['energy'], -1.85727503) np.testing.assert_array_almost_equal(result['energies'], [-1.85727503]) np.testing.assert_array_almost_equal(result['eigvals'], [-1.85727503 + 0j])
def run_algorithm_from_json(self, params, output=None, backend=None): """ Runs the Aqua Chemistry experiment from json dictionary Args: params (dictionary): Input data output (filename): Output data backend (BaseBackend): backend object Returns: result dictionary """ ret = run_algorithm(params, None, True, backend) if not isinstance(ret, dict): raise AquaChemistryError( "Algorithm run result should be a dictionary") convert_json_to_dict(ret) if logger.isEnabledFor(logging.DEBUG): logger.debug('Algorithm returned: {}'.format( pprint.pformat(ret, indent=4))) print('Output:') if isinstance(ret, dict): for k, v in ret.items(): print("'{}': {}".format(k, v)) else: print(ret) return ret
def test_partition_vqe(self): algorithm_cfg = { 'name': 'VQE', 'operator_mode': 'grouped_paulis', 'batch_mode': True } optimizer_cfg = { 'name': 'SPSA', 'max_trials': 200 } var_form_cfg = { 'name': 'RY', 'depth': 5, 'entanglement': 'linear' } params = { 'problem': {'name': 'ising', 'random_seed': 100}, 'algorithm': algorithm_cfg, 'optimizer': optimizer_cfg, 'variational_form': var_form_cfg } backend = get_aer_backend('qasm_simulator') result = run_algorithm(params, self.algo_input, backend=backend) x = partition.sample_most_likely(result['eigvecs'][0]) self.assertNotEqual(x[0], x[1]) self.assertNotEqual(x[2], x[1]) # hardcoded oracle
def test_vqe_optimizers(self, name, places, batch_mode): params = { 'algorithm': {'name': 'VQE', 'batch_mode': batch_mode}, 'optimizer': {'name': name}, 'backend': {'name': 'statevector_simulator', 'shots': 1} } result = run_algorithm(params, self.algo_input) self.assertAlmostEqual(result['energy'], -1.85727503, places=places)
def test_partition(self): params = { 'problem': {'name': 'ising'}, 'algorithm': {'name': 'ExactEigensolver'} } result = run_algorithm(params, self.algo_input) x = partition.sample_most_likely(result['eigvecs'][0]) np.testing.assert_array_equal(x, [0, 1, 0])
def test_vqe_var_forms(self, name, places): backend = Aer.get_backend('statevector_simulator') params = { 'algorithm': {'name': 'VQE'}, 'variational_form': {'name': name}, 'backend': {'shots': 1} } result = run_algorithm(params, self.algo_input, backend=backend) self.assertAlmostEqual(result['energy'], -1.85727503, places=places)
def test_ee_via_run_algorithm_k4(self): params = { 'algorithm': {'name': 'ExactEigensolver', 'k': 4} } result = run_algorithm(params, self.algo_input) self.assertAlmostEqual(result['energy'], -1.85727503) self.assertEqual(len(result['eigvals']), 4) self.assertEqual(len(result['eigvecs']), 4) np.testing.assert_array_almost_equal(result['energies'], [-1.85727503, -1.24458455, -0.88272215, -0.22491125])
def test_classical_binary(self): training_input = { 'A': np.asarray([ [0.6560706, 0.17605998], [0.14154948, 0.06201424], [0.80202323, 0.40582692], [0.46779595, 0.39946754], [0.57660199, 0.21821317], ]), 'B': np.asarray([[0.38857596, -0.33775802], [0.49946978, -0.48727951], [-0.30119743, -0.11221681], [-0.16479252, -0.08640519], [0.49156185, -0.3660534]]) } test_input = { 'A': np.asarray([ [0.57483139, 0.47120732], [0.48372348, 0.25438544], [0.08791134, 0.11515506], [0.45988094, 0.32854319], [0.53015085, 0.41539212], ]), 'B': np.asarray([[-0.06048935, -0.48345293], [-0.01065613, -0.33910828], [-0.17323832, -0.49535592], [0.14043268, -0.87869109], [-0.15046837, -0.47340207]]) } temp = [test_input[k] for k in test_input] total_array = np.concatenate(temp) params = { 'problem': { 'name': 'svm_classification', 'random_seed': self.random_seed }, 'backend': { 'name': 'local_qasm_simulator', 'shots': 1000 }, 'algorithm': { 'name': 'QSVM.Kernel' } } algo_input = get_input_instance('SVMInput') algo_input.training_dataset = training_input algo_input.test_dataset = test_input algo_input.datapoints = total_array result = run_algorithm(params, algo_input) self.assertEqual(result['test_success_ratio'], 0.6) self.assertEqual(result['predicted_labels'], ['A', 'A', 'A', 'A', 'A', 'A', 'B', 'A', 'A', 'A'])
def main_algorithm(): try: from qiskit_aqua._logging import get_logging_level, build_logging_config, set_logging_config from qiskit_aqua_cmd import Preferences from qiskit_aqua import run_algorithm from qiskit_aqua.utils import convert_json_to_dict parser = argparse.ArgumentParser( description='Qiskit Aqua Command Line Tool') parser.add_argument('input', metavar='input', help='Algorithm JSON input file') parser.add_argument('-jo', metavar='output', help='Algorithm JSON output file name', required=False) args = parser.parse_args() # update logging setting with latest external packages preferences = Preferences() logging_level = logging.INFO if preferences.get_logging_config() is not None: set_logging_config(preferences.get_logging_config()) logging_level = get_logging_level() preferences.set_logging_config(build_logging_config(logging_level)) preferences.save() set_logging_config(preferences.get_logging_config()) params = None with open(args.input) as json_file: params = json.load(json_file) ret = run_algorithm(params, None, True) if args.jo is not None: with open(args.jo, 'w') as f: print('{}'.format(ret), file=f) else: convert_json_to_dict(ret) print( '\n\n--------------------------------- R E S U L T ------------------------------------\n' ) if isinstance(ret, dict): for k, v in ret.items(): print("'{}': {}".format(k, v)) else: print(ret) finally: global _ROOT if _ROOT is not None: _ROOT.destroy() _ROOT = None
def test_classical_multiclass_error_correcting_code(self): training_input = { 'A': np.asarray([[0.6560706, 0.17605998], [0.25776033, 0.47628296], [0.8690704, 0.70847635]]), 'B': np.asarray([[0.38857596, -0.33775802], [0.49946978, -0.48727951], [0.49156185, -0.3660534]]), 'C': np.asarray([[-0.68088231, 0.46824423], [-0.56167659, 0.65270294], [-0.82139073, 0.29941512]]) } test_input = { 'A': np.asarray([[0.57483139, 0.47120732], [0.48372348, 0.25438544], [0.48142649, 0.15931707]]), 'B': np.asarray([[-0.06048935, -0.48345293], [-0.01065613, -0.33910828], [0.06183066, -0.53376975]]), 'C': np.asarray([[-0.74561108, 0.27047295], [-0.69942965, 0.11885162], [-0.66489165, 0.1181712]]) } temp = [test_input[k] for k in test_input] total_array = np.concatenate(temp) params = { 'problem': { 'name': 'svm_classification', 'random_seed': self.random_seed }, 'algorithm': { 'name': 'QSVM.Kernel', 'multiclass_alg': 'error_correcting_code' }, 'backend': { 'name': 'local_qasm_simulator_py', 'shots': 1024 } } algo_input = get_input_instance('SVMInput') algo_input.training_dataset = training_input algo_input.test_dataset = test_input algo_input.datapoints = total_array result = run_algorithm(params, algo_input) self.assertEqual(result['test_success_ratio'], 0.5555555555555556) self.assertEqual(result['predicted_labels'], ['A', 'A', 'C', 'A', 'A', 'A', 'C', 'C', 'C'])
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)
def test_vqe_optimzers(self, name, places): params = { 'algorithm': { 'name': 'VQE' }, 'optimizer': { 'name': name }, 'backend': { 'name': 'local_statevector_simulator' } } result = run_algorithm(params, self.algo_input) self.assertAlmostEqual(result['energy'], -1.85727503, places=places)
def test_vqe_via_run_algorithm(self): params = { 'algorithm': {'name': 'VQE'}, 'backend': {'name': 'statevector_simulator', 'shots': 1}, } result = run_algorithm(params, self.algo_input) self.assertAlmostEqual(result['energy'], -1.85727503) np.testing.assert_array_almost_equal(result['eigvals'], [-1.85727503], 5) np.testing.assert_array_almost_equal(result['opt_params'], [-0.58294401, -1.86141794, -1.97209632, -0.54796022, -0.46945572, 2.60114794, -1.15637845, 1.40498879, 1.14479635, -0.48416694, -0.66608349, -1.1367579, -2.67097002, 3.10214631, 3.10000313, 0.37235089], 5) self.assertIn('eval_count', result) self.assertIn('eval_time', result)
def test_clique(self): params = { 'problem': { 'name': 'ising' }, 'algorithm': { 'name': 'ExactEigensolver' } } result = run_algorithm(params, self.algo_input) x = clique.sample_most_likely(len(self.w), result['eigvecs'][0]) ising_sol = clique.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [1, 1, 1, 1, 1]) oracle = self.brute_force() self.assertEqual(clique.satisfy_or_not(ising_sol, self.w, self.K), oracle)
def test_qsvm_variational_via_run_algorithm(self): np.random.seed(self.random_seed) params = { 'problem': {'name': 'svm_classification', 'random_seed': self.random_seed}, 'algorithm': {'name': 'QSVM.Variational'}, 'backend': {'name': 'qasm_simulator', 'shots': 1024}, 'optimizer': {'name': 'SPSA', 'max_trials': 10, 'save_steps': 1}, 'variational_form': {'name': 'RYRZ', 'depth': 3}, 'feature_map': {'name': 'SecondOrderExpansion', 'depth': 2} } result = run_algorithm(params, self.svm_input) np.testing.assert_array_almost_equal(result['opt_params'], self.ref_opt_params, decimal=4) np.testing.assert_array_almost_equal(result['training_loss'], self.ref_train_loss, decimal=8) self.assertEqual(result['testing_accuracy'], 0.5)
def test_vertex_cover(self): params = { 'problem': { 'name': 'ising' }, 'algorithm': { 'name': 'ExactEigensolver' } } result = run_algorithm(params, self.algo_input) x = vertexcover.sample_most_likely(len(self.w), result['eigvecs'][0]) sol = vertexcover.get_graph_solution(x) np.testing.assert_array_equal(sol, [0, 1, 1]) oracle = self.brute_force() self.assertEqual(np.count_nonzero(sol), oracle)
def test_graph_partition(self): params = { 'problem': { 'name': 'ising' }, 'algorithm': { 'name': 'ExactEigensolver' } } result = run_algorithm(params, self.algo_input) x = graphpartition.sample_most_likely(result['eigvecs'][0]) # check against the oracle ising_sol = graphpartition.get_graph_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 0, 1]) oracle = self.brute_force() self.assertEqual(graphpartition.objective_value(x, self.w), oracle)
def test_set_packing(self): params = { 'problem': { 'name': 'ising' }, 'algorithm': { 'name': 'ExactEigensolver' } } result = run_algorithm(params, self.algo_input) x = setpacking.sample_most_likely(len(self.list_of_subsets), result['eigvecs'][0]) ising_sol = setpacking.get_solution(x) np.testing.assert_array_equal(ising_sol, [0, 1, 1]) oracle = self.brute_force() self.assertEqual(np.count_nonzero(ising_sol), oracle)
def test_cplex_ising_via_run_algorithm(self): params = { 'problem': { 'name': 'ising' }, 'algorithm': { 'name': 'CPLEX.Ising', 'display': 0 } } result = run_algorithm(params, self.algo_input) self.assertEqual(result['energy'], -20.5) x_dict = result['x_sol'] x = np.array([x_dict[i] for i in sorted(x_dict.keys())]) np.testing.assert_array_equal(maxcut.get_graph_solution(x), [1, 0, 1, 1]) self.assertEqual(maxcut.maxcut_value(x, self.w), 24)
def test_qsvm_kernel_binary_via_run_algorithm(self): training_input = { 'A': np.asarray([[0.6560706, 0.17605998], [0.14154948, 0.06201424], [0.80202323, 0.40582692], [0.46779595, 0.39946754], [0.57660199, 0.21821317]]), 'B': np.asarray([[0.38857596, -0.33775802], [0.49946978, -0.48727951], [-0.30119743, -0.11221681], [-0.16479252, -0.08640519], [0.49156185, -0.3660534]]) } test_input = { 'A': np.asarray([[0.57483139, 0.47120732], [0.48372348, 0.25438544], [0.08791134, 0.11515506], [0.45988094, 0.32854319], [0.53015085, 0.41539212]]), 'B': np.asarray([[-0.06048935, -0.48345293], [-0.01065613, -0.33910828], [-0.17323832, -0.49535592], [0.14043268, -0.87869109], [-0.15046837, -0.47340207]]) } temp = [test_input[k] for k in test_input] total_array = np.concatenate(temp) params = { 'problem': { 'name': 'svm_classification', 'random_seed': self.random_seed }, 'backend': { 'shots': self.shots }, 'algorithm': { 'name': 'QSVM.Kernel' } } backend = Aer.get_backend('qasm_simulator') algo_input = SVMInput(training_input, test_input, total_array) result = run_algorithm(params, algo_input, backend=backend) self.assertEqual(result['testing_accuracy'], 0.6) self.assertEqual(result['predicted_classes'], ['A', 'A', 'A', 'A', 'A', 'A', 'B', 'A', 'A', 'A'])
def test_svm_qkernel_via_run_algorithm(self): params = { 'problem': {'name': 'svm_classification', 'random_seed': self.random_seed}, 'algorithm': {'name': 'SVM_QKernel'}, 'backend': {'name': 'local_qasm_simulator', 'shots': 1024} } result = run_algorithm(params, self.svm_input) np.testing.assert_array_almost_equal( result['kernel_matrix_training'], self.ref_kernel_matrix_training, decimal=4) np.testing.assert_array_almost_equal( result['kernel_matrix_testing'], self.ref_kernel_matrix_testing, decimal=4) self.assertEqual(len(result['svm']['support_vectors']), 4) np.testing.assert_array_almost_equal( result['svm']['support_vectors'], self.ref_support_vectors, decimal=4) self.assertEqual(result['test_success_ratio'], 0.5)
def run_algorithm_from_json(self, params, output=None): ret = run_algorithm(params, None, True) if not isinstance(ret, dict): raise AquaChemistryError( "Algorithm run result should be a dictionary") convert_json_to_dict(ret) if logger.isEnabledFor(logging.DEBUG): logger.debug('Algorithm returned: {}'.format( pprint.pformat(ret, indent=4))) print('Output:') if isinstance(ret, dict): for k, v in ret.items(): print("'{}': {}".format(k, v)) else: print(ret) return ret
def classical_svm(train_input, test_input, class_labels, n): temp = [test_input[k] for k in test_input] total_array = np.concatenate(temp) # Select parameters based on number of classes in data if len(class_labels) > 2: aqua_dict = { 'problem': { 'name': 'svm_classification', 'random_seed': 100 }, 'algorithm': { 'name': 'SVM' }, 'multiclass_extension': { 'name': 'AllPairs' } } else: aqua_dict = { 'problem': { 'name': 'svm_classification', 'random_seed': 100 }, 'algorithm': { 'name': 'SVM' } } algo_input = svminput algo_input.training_dataset = train_input algo_input.test_dataset = test_input algo_input.datapoints = total_array # Run the classical SVM algorithm result = run_algorithm(aqua_dict, algo_input) # Print model values # for k,v in result.items(): # print("'{}' : {}".format(k, v)) return result