def setUp(self): super().setUp() np.random.seed(50) pauli_dict = { 'paulis': [{"coeff": {"imag": 0.0, "real": -1.052373245772859}, "label": "II"}, {"coeff": {"imag": 0.0, "real": 0.39793742484318045}, "label": "IZ"}, {"coeff": {"imag": 0.0, "real": -0.39793742484318045}, "label": "ZI"}, {"coeff": {"imag": 0.0, "real": -0.01128010425623538}, "label": "ZZ"}, {"coeff": {"imag": 0.0, "real": 0.18093119978423156}, "label": "XX"} ] } qubit_op = Operator.load_from_dict(pauli_dict) self.algo_input = EnergyInput(qubit_op) backends = ['statevector_simulator', 'qasm_simulator'] res = {} for backend in backends: params_no_caching = { 'algorithm': {'name': 'VQE', 'operator_mode': 'matrix' if backend == 'statevector_simulator' else 'paulis'}, 'problem': {'name': 'energy', 'random_seed': 50, 'circuit_caching': False, 'skip_qobj_deepcopy': False, 'skip_qobj_validation': False, 'circuit_cache_file': None, }, 'backend': {'provider': 'qiskit.BasicAer', 'name': backend, 'shots': 1000}, } qiskit_aqua = QiskitAqua(params_no_caching, self.algo_input) res[backend] = qiskit_aqua.run() self.reference_vqe_result = res
def test_vqe_caching_via_run_algorithm(self, backend, caching, skip_qobj_deepcopy): skip_validation = True params_caching = { 'algorithm': {'name': 'VQE', 'operator_mode': 'matrix' if backend == 'statevector_simulator' else 'paulis'}, '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': {'provider': 'qiskit.BasicAer', 'name': backend, 'shots': 1000}, } qiskit_aqua = QiskitAqua(params_caching, self.algo_input) result_caching = qiskit_aqua.run() 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) if qiskit_aqua.quantum_instance.has_circuit_caching: self.assertEqual(qiskit_aqua.quantum_instance._circuit_cache.misses, 0) self.assertIn('eval_count', result_caching) self.assertIn('eval_time', result_caching)
def _build_refrence_result(self, backends): res = {} os.environ.pop('QISKIT_AQUA_CIRCUIT_CACHE', None) for backend in backends: params_no_caching = { 'algorithm': { 'name': 'VQE' }, 'problem': { 'name': 'energy', 'random_seed': 50, 'circuit_caching': False, 'skip_qobj_deepcopy': False, 'skip_qobj_validation': False, 'circuit_cache_file': None, }, 'backend': { 'provider': 'qiskit.BasicAer', 'name': backend }, } if backend != 'statevector_simulator': params_no_caching['backend']['shots'] = 1000 params_no_caching['optimizer'] = { 'name': 'SPSA', 'max_trials': 15 } qiskit_aqua = QiskitAqua(params_no_caching, self.algo_input) res[backend] = qiskit_aqua.run() os.environ['QISKIT_AQUA_CIRCUIT_CACHE'] = '1' self.reference_vqe_result = res
def _build_refrence_result(self, backends): res = {} for backend in backends: params_no_caching = { 'algorithm': { 'name': 'VQE', 'operator_mode': 'matrix' if backend == 'statevector_simulator' else 'paulis' }, 'problem': { 'name': 'energy', 'random_seed': 50, 'circuit_caching': False, 'skip_qobj_deepcopy': False, 'skip_qobj_validation': False, 'circuit_cache_file': None, }, 'backend': { 'provider': 'qiskit.BasicAer', 'name': backend }, } if backend != 'statevector_simulator': params_no_caching['backend']['shots'] = 1000 params_no_caching['optimizer'] = { 'name': 'SPSA', 'max_trials': 15 } qiskit_aqua = QiskitAqua(params_no_caching, self.algo_input) res[backend] = qiskit_aqua.run() self.reference_vqe_result = res
def test_vqe_caching_via_run_algorithm(self, backend, caching, skip_qobj_deepcopy): self._build_refrence_result(backends=[backend]) skip_validation = True params_caching = { 'algorithm': {'name': 'VQE'}, 'problem': {'name': 'energy', 'random_seed': 50, 'circuit_optimization_level': self.optimization_level, 'circuit_caching': caching, 'skip_qobj_deepcopy': skip_qobj_deepcopy, 'skip_qobj_validation': skip_validation, 'circuit_cache_file': None, }, 'backend': {'provider': 'qiskit.BasicAer', 'name': backend}, } if backend != 'statevector_simulator': params_caching['backend']['shots'] = 1000 params_caching['optimizer'] = {'name': 'SPSA', 'max_trials': 15} qiskit_aqua = QiskitAqua(params_caching, self.algo_input) result_caching = qiskit_aqua.run() 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) if qiskit_aqua.quantum_instance.has_circuit_caching: self.assertEqual(qiskit_aqua.quantum_instance._circuit_cache.misses, 0) self.assertIn('eval_count', result_caching) self.assertIn('eval_time', result_caching)
def run_algorithm_from_json(params, output_file): """ Runs the Aqua Chemistry experiment from Qiskit Aqua json dictionary Args: params (dictionary): Qiskit Aqua json dictionary output_file (filename): Output file name to save results """ qiskit_aqua = QiskitAqua(params) ret = qiskit_aqua.run() if not isinstance(ret, dict): raise QiskitChemistryError('Algorithm run result should be a dictionary {}'.format(ret)) print('Output:') pprint(ret, indent=4) if output_file is not None: with open(output_file, 'w') as out: pprint(ret, stream=out, indent=4)
def __init__(self): self.move = 0 self.data_file = 'data.csv' self.data_path = 'PlayerLogic' self.feature_dim = 9 # dimension of each data point sample_Total, training_input, test_input, class_labels = VQCQPlayer.userDefinedData( self.data_path, self.data_file, ['0', '1', '2', '3', '4', '5', '6', '7', '8'], training_size=6000, test_size=500, n=self.feature_dim, PLOT_DATA=False) temp = [test_input[k] for k in test_input] total_array = np.concatenate(temp) aqua_dict = { 'problem': { 'name': 'classification' }, 'algorithm': { 'name': 'SVM' }, 'multiclass_extension': { 'name': 'AllPairs' } } algo_input = ClassificationInput(training_input, test_input, total_array) from qiskit.aqua import QiskitAqua aqua_obj = QiskitAqua(aqua_dict, algo_input) self.algo_obj = aqua_obj.quantum_algorithm logger.info("Training the SVM....") aqua_obj.run() logger.info("Trained!")
def run_driver(self, params, backend=None): """ Runs the Qiskit Chemistry driver Args: params (Union(dictionary, filename)): Chemistry input data backend (QuantumInstance or BaseBackend): the experimental settings to be used in place of backend name Raises: QiskitChemistryError: Missing Input """ if params is None: raise QiskitChemistryError("Missing input.") self._operator = None self._chemistry_result = None self._qiskit_aqua = None self._hdf5_file = None self._parser = InputParser(params) self._parser.parse() # before merging defaults attempts to find a provider for the backend in case no # provider was passed if backend is None and \ self._parser.get_section_property(JSONSchema.BACKEND, JSONSchema.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)) # set provider and name in input file for proper backend schema dictionary build if isinstance(backend, BaseBackend): self._parser.backend = backend self._parser.add_section_properties( JSONSchema.BACKEND, { JSONSchema.PROVIDER: get_provider_from_backend(backend), JSONSchema.NAME: backend.name(), }) self._parser.validate_merge_defaults() experiment_name = "-- no &NAME section found --" if JSONSchema.NAME in self._parser.get_section_names(): name_sect = self._parser.get_section(JSONSchema.NAME) if name_sect is not None: experiment_name = str(name_sect) logger.info('Running chemistry problem from input file: %s', self._parser.get_filename()) logger.info('Experiment description: %s', experiment_name.rstrip()) driver_name = self._parser.get_section_property( InputParser.DRIVER, JSONSchema.NAME) if driver_name is None: raise QiskitChemistryError( 'Property "{0}" missing in section "{1}"'.format( JSONSchema.NAME, InputParser.DRIVER)) self._hdf5_file = \ self._parser.get_section_property(InputParser.DRIVER, InputParser.HDF5_OUTPUT) if driver_name not in local_drivers(): raise QiskitChemistryError( 'Driver "{0}" missing in local drivers'.format(driver_name)) work_path = None input_file = self._parser.get_filename() if input_file is not None: work_path = os.path.dirname(os.path.realpath(input_file)) section = self._parser.get_section(driver_name) driver = get_driver_class(driver_name).init_from_input(section) driver.work_path = work_path molecule = driver.run() if work_path is not None and \ self._hdf5_file is not None and not os.path.isabs(self._hdf5_file): self._hdf5_file = os.path.abspath( os.path.join(work_path, self._hdf5_file)) molecule.log() if self._hdf5_file is not None: molecule.save(self._hdf5_file) logger.info("HDF5 file saved '%s'", self._hdf5_file) # Run the Hamiltonian to process the QMolecule and get an input for algorithms clazz = get_chemistry_operator_class( self._parser.get_section_property(InputParser.OPERATOR, JSONSchema.NAME)) self._operator = clazz.init_params( self._parser.get_section_properties(InputParser.OPERATOR)) qubit_op, aux_ops = self.operator.run(molecule) input_object = EnergyInput(qubit_op, aux_ops) logger.debug('Core computed substitution variables %s', self.operator.molecule_info) result = self._parser.process_substitutions( self.operator.molecule_info) logger.debug('Substitutions %s', result) aqua_params = {} for section_name, section in self._parser.get_sections().items(): if section_name == JSONSchema.NAME or \ section_name == InputParser.DRIVER or \ section_name == driver_name.lower() or \ section_name == InputParser.OPERATOR or \ not isinstance(section, dict): continue aqua_params[section_name] = copy.deepcopy(section) if JSONSchema.PROBLEM == section_name and \ InputParser.AUTO_SUBSTITUTIONS in aqua_params[section_name]: del aqua_params[section_name][InputParser.AUTO_SUBSTITUTIONS] self._qiskit_aqua = QiskitAqua(aqua_params, input_object, backend)
'problem': { 'name': 'svm_classification' }, 'algorithm': { 'name': 'SVM' }, 'multiclass_extension': { 'name': 'AllPairs' } } algo_input = SVMInput(training_input, test_input, total_array) from qiskit.aqua import QiskitAqua aqua_obj = QiskitAqua(aqua_dict, algo_input) algo_obj = aqua_obj.quantum_algorithm result = aqua_obj.run() #run_algorithm(aqua_dict, algo_input) for k, v in result.items(): print("'{}' : {}".format(k, v)) # 6 to_predict = singleDataItem('', 'data.csv', [1, 2, 0, 0, 0, 0, 0, 1, 0], n=3) print(algo_obj.predict(to_predict)) # 2 to_predict = singleDataItem('', 'data.csv', [1, 0, 1, 0, 0, 0, 0, 2, 0], n=3) print(algo_obj.predict(to_predict)) # 1