def test_eoh(self): SIZE = 2 temp = np.random.random((2 ** SIZE, 2 ** SIZE)) h1 = temp + temp.T qubit_op = Operator(matrix=h1) temp = np.random.random((2 ** SIZE, 2 ** SIZE)) h1 = temp + temp.T evo_op = Operator(matrix=h1) state_in = Custom(SIZE, state='random') evo_time = 1 num_time_slices = 100 eoh = EOH(qubit_op, state_in, evo_op, 'paulis', evo_time, num_time_slices) backend = get_aer_backend('statevector_simulator') run_config = RunConfig(shots=1, max_credits=10, memory=False) quantum_instance = QuantumInstance(backend, run_config, pass_manager=PassManager()) # self.log.debug('state_out:\n\n') ret = eoh.run(quantum_instance) self.log.debug('Evaluation result: {}'.format(ret))
def test_qpe(self, distance): self.algorithm = 'QPE' self.log.debug('Testing End-to-End with QPE on H2 with inter-atomic distance {}.'.format(distance)) try: driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 {}'.format(distance), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.molecule = driver.run() qubit_mapping = 'parity' fer_op = FermionicOperator( h1=self.molecule.one_body_integrals, h2=self.molecule.two_body_integrals) self.qubit_op = fer_op.mapping(map_type=qubit_mapping, threshold=1e-10).two_qubit_reduced_operator(2) exact_eigensolver = ExactEigensolver(self.qubit_op, k=1) results = exact_eigensolver.run() self.reference_energy = results['energy'] self.log.debug( 'The exact ground state energy is: {}'.format(results['energy'])) num_particles = self.molecule.num_alpha + self.molecule.num_beta two_qubit_reduction = True num_orbitals = self.qubit_op.num_qubits + \ (2 if two_qubit_reduction else 0) num_time_slices = 50 n_ancillae = 9 state_in = HartreeFock(self.qubit_op.num_qubits, num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) iqft = Standard(n_ancillae) qpe = QPE(self.qubit_op, state_in, iqft, num_time_slices, n_ancillae, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) backend = qiskit.Aer.get_backend('qasm_simulator') run_config = RunConfig(shots=100, max_credits=10, memory=False) quantum_instance = QuantumInstance(backend, run_config, pass_manager=PassManager()) result = qpe.run(quantum_instance) self.log.debug('eigvals: {}'.format(result['eigvals'])) self.log.debug('top result str label: {}'.format(result['top_measurement_label'])) self.log.debug('top result in decimal: {}'.format(result['top_measurement_decimal'])) self.log.debug('stretch: {}'.format(result['stretch'])) self.log.debug('translation: {}'.format(result['translation'])) self.log.debug('final energy from QPE: {}'.format(result['energy'])) self.log.debug('reference energy: {}'.format(self.reference_energy)) self.log.debug('ref energy (transformed): {}'.format( (self.reference_energy + result['translation']) * result['stretch'])) self.log.debug('ref binary str label: {}'.format(decimal_to_binary((self.reference_energy + result['translation']) * result['stretch'], max_num_digits=n_ancillae + 3, fractional_part_only=True))) np.testing.assert_approx_equal( result['energy'], self.reference_energy, significant=2)
def test_vqe_callback(self): tmp_filename = 'vqe_callback_test.csv' is_file_exist = os.path.exists(self._get_resource_path(tmp_filename)) if is_file_exist: os.remove(self._get_resource_path(tmp_filename)) def store_intermediate_result(eval_count, parameters, mean, std): with open(self._get_resource_path(tmp_filename), 'a') as f: content = "{},{},{:.5f},{:.5f}".format(eval_count, parameters, mean, std) print(content, file=f, flush=True) backend = get_aer_backend('qasm_simulator') num_qubits = self.algo_input.qubit_op.num_qubits init_state = Zero(num_qubits) var_form = RY(num_qubits, 1, initial_state=init_state) optimizer = COBYLA(maxiter=3) algo = VQE(self.algo_input.qubit_op, var_form, optimizer, 'paulis', callback=store_intermediate_result) algo.random_seed = 50 run_config = RunConfig(shots=1024, seed=50) quantum_instance = QuantumInstance(backend, seed_mapper=50, run_config=run_config) algo.run(quantum_instance) is_file_exist = os.path.exists(self._get_resource_path(tmp_filename)) self.assertTrue(is_file_exist, "Does not store content successfully.") # check the content ref_content = [[ "1", "[-0.03391886 -1.70850424 -1.53640265 -0.65137839]", "-0.59622", "0.01546" ], [ "2", "[ 0.96608114 -1.70850424 -1.53640265 -0.65137839]", "-0.77452", "0.01692" ], [ "3", "[ 0.96608114 -0.70850424 -1.53640265 -0.65137839]", "-0.80327", "0.01519" ]] with open(self._get_resource_path(tmp_filename)) as f: idx = 0 for record in f.readlines(): eval_count, parameters, mean, std = record.split(",") self.assertEqual(eval_count.strip(), ref_content[idx][0]) self.assertEqual(parameters, ref_content[idx][1]) self.assertEqual(mean.strip(), ref_content[idx][2]) self.assertEqual(std.strip(), ref_content[idx][3]) idx += 1 if is_file_exist: os.remove(self._get_resource_path(tmp_filename))
def test_qsvm_kernel_binary_directly(self): ref_kernel_training = np.array( [[1., 0.85366667, 0.12341667, 0.36408333], [0.85366667, 1., 0.11141667, 0.45491667], [0.12341667, 0.11141667, 1., 0.667], [0.36408333, 0.45491667, 0.667, 1.]]) ref_kernel_testing = np.array( [[0.14316667, 0.18208333, 0.4785, 0.14441667], [0.33608333, 0.3765, 0.02316667, 0.15858333]]) ref_alpha = np.array([0.36064489, 1.49204209, 0.0264953, 1.82619169]) ref_bias = np.array([-0.03380763]) ref_support_vectors = np.array([[2.95309709, 2.51327412], [3.14159265, 4.08407045], [4.08407045, 2.26194671], [4.46106157, 2.38761042]]) backend = get_aer_backend('qasm_simulator') num_qubits = 2 feature_map = SecondOrderExpansion(num_qubits=num_qubits, depth=2, entangler_map={0: [1]}) svm = QSVMKernel(feature_map, self.training_data, self.testing_data, None) svm.random_seed = self.random_seed run_config = RunConfig(shots=self.shots, max_credits=10, memory=False, seed=self.random_seed) quantum_instance = QuantumInstance(backend, run_config, seed_mapper=self.random_seed) result = svm.run(quantum_instance) np.testing.assert_array_almost_equal(result['kernel_matrix_training'], ref_kernel_training, decimal=1) np.testing.assert_array_almost_equal(result['kernel_matrix_testing'], ref_kernel_testing, decimal=1) self.assertEqual(len(result['svm']['support_vectors']), 4) np.testing.assert_array_almost_equal(result['svm']['support_vectors'], ref_support_vectors, decimal=4) np.testing.assert_array_almost_equal(result['svm']['alphas'], ref_alpha, decimal=4) np.testing.assert_array_almost_equal(result['svm']['bias'], ref_bias, decimal=4) self.assertEqual(result['testing_accuracy'], 0.5)
def test_vqe_2_iqpe(self): backend = get_aer_backend('qasm_simulator') num_qbits = self.algo_input.qubit_op.num_qubits var_form = RYRZ(num_qbits, 3) optimizer = SPSA(max_trials=10) # optimizer.set_options(**{'max_trials': 500}) algo = VQE(self.algo_input.qubit_op, var_form, optimizer, 'paulis') quantum_instance = QuantumInstance(backend) result = algo.run(quantum_instance) self.log.debug('VQE result: {}.'.format(result)) self.ref_eigenval = -1.85727503 num_time_slices = 50 num_iterations = 11 state_in = VarFormBased(var_form, result['opt_params']) iqpe = IQPE(self.algo_input.qubit_op, state_in, num_time_slices, num_iterations, paulis_grouping='random', expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) run_config = RunConfig(shots=100, max_credits=10, memory=False) quantum_instance = QuantumInstance(backend, run_config, pass_manager=PassManager(), seed_mapper=self.random_seed) result = iqpe.run(quantum_instance) self.log.debug('top result str label: {}'.format( result['top_measurement_label'])) self.log.debug('top result in decimal: {}'.format( result['top_measurement_decimal'])) self.log.debug('stretch: {}'.format( result['stretch'])) self.log.debug('translation: {}'.format( result['translation'])) self.log.debug('final eigenvalue from QPE: {}'.format( result['energy'])) self.log.debug('reference eigenvalue: {}'.format( self.ref_eigenval)) self.log.debug('ref eigenvalue (transformed): {}'.format( (self.ref_eigenval + result['translation']) * result['stretch'])) self.log.debug('reference binary str label: {}'.format( decimal_to_binary((self.ref_eigenval + result['translation']) * result['stretch'], max_num_digits=num_iterations + 3, fractional_part_only=True))) np.testing.assert_approx_equal(self.ref_eigenval, result['energy'], significant=2)
def test_qsvm_variational_directly(self): np.random.seed(self.random_seed) backend = get_aer_backend('qasm_simulator') num_qubits = 2 optimizer = SPSA(max_trials=10, save_steps=1, c0=4.0, skip_calibration=True) feature_map = SecondOrderExpansion(num_qubits=num_qubits, depth=2) var_form = RYRZ(num_qubits=num_qubits, depth=3) svm = QSVMVariational(optimizer, feature_map, var_form, self.training_data, self.testing_data) svm.random_seed = self.random_seed run_config = RunConfig(shots=1024, max_credits=10, memory=False, seed=self.random_seed) quantum_instance = QuantumInstance(backend, run_config, seed_mapper=self.random_seed) result = svm.run(quantum_instance) 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'], 1.0) file_path = self._get_resource_path('qsvm_variational_test.npz') svm.save_model(file_path) self.assertTrue(os.path.exists(file_path)) loaded_svm = QSVMVariational(optimizer, feature_map, var_form, self.training_data, None) loaded_svm.load_model(file_path) np.testing.assert_array_almost_equal(loaded_svm.ret['opt_params'], self.ref_opt_params, decimal=4) loaded_test_acc = loaded_svm.test(svm.test_dataset[0], svm.test_dataset[1], quantum_instance) self.assertEqual(result['testing_accuracy'], loaded_test_acc) if os.path.exists(file_path): try: os.remove(file_path) except: pass
def test_iqpe(self, qubitOp, simulator): self.algorithm = 'IQPE' self.log.debug('Testing IQPE') self.qubitOp = qubitOp exact_eigensolver = ExactEigensolver(self.qubitOp, k=1) results = exact_eigensolver.run() w = results['eigvals'] v = results['eigvecs'] self.qubitOp.to_matrix() np.testing.assert_almost_equal( self.qubitOp.matrix @ v[0], w[0] * v[0] ) np.testing.assert_almost_equal( expm(-1.j * sparse.csc_matrix(self.qubitOp.matrix)) @ v[0], np.exp(-1.j * w[0]) * v[0] ) self.ref_eigenval = w[0] self.ref_eigenvec = v[0] self.log.debug('The exact eigenvalue is: {}'.format(self.ref_eigenval)) self.log.debug('The corresponding eigenvector: {}'.format(self.ref_eigenvec)) num_time_slices = 50 num_iterations = 6 state_in = Custom(self.qubitOp.num_qubits, state_vector=self.ref_eigenvec) iqpe = IQPE(self.qubitOp, state_in, num_time_slices, num_iterations, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) backend = get_aer_backend(simulator) run_config = RunConfig(shots=100, max_credits=10, memory=False) quantum_instance = QuantumInstance(backend, run_config, pass_manager=PassManager()) result = iqpe.run(quantum_instance) self.log.debug('top result str label: {}'.format(result['top_measurement_label'])) self.log.debug('top result in decimal: {}'.format(result['top_measurement_decimal'])) self.log.debug('stretch: {}'.format(result['stretch'])) self.log.debug('translation: {}'.format(result['translation'])) self.log.debug('final eigenvalue from IQPE: {}'.format(result['energy'])) self.log.debug('reference eigenvalue: {}'.format(self.ref_eigenval)) self.log.debug('ref eigenvalue (transformed): {}'.format( (self.ref_eigenval + result['translation']) * result['stretch']) ) self.log.debug('reference binary str label: {}'.format(decimal_to_binary( (self.ref_eigenval.real + result['translation']) * result['stretch'], max_num_digits=num_iterations + 3, fractional_part_only=True ))) np.testing.assert_approx_equal(result['energy'], self.ref_eigenval.real, significant=2)
def test_grover(self, dimacs_file, incremental, num_iterations, mct_mode, simulator, optimization='off'): dimacs_file = self._get_resource_path(dimacs_file) # get ground-truth with open(dimacs_file) as f: buf = f.read() if incremental: self.log.debug( 'Testing incremental Grover search on SAT problem instance: \n{}' .format(buf, )) else: self.log.debug( 'Testing Grover search with {} iteration(s) on SAT problem instance: \n{}' .format( num_iterations, buf, )) header = buf.split('\n')[0] self.assertGreaterEqual(header.find('solution'), 0, 'Ground-truth info missing.') self.groundtruth = [ ''.join([ '1' if i > 0 else '0' for i in sorted( [int(v) for v in s.strip().split() if v != '0'], key=abs) ])[::-1] for s in header.split('solutions:' if header.find( 'solutions:') >= 0 else 'solution:')[-1].split(',') ] backend = get_aer_backend(simulator) oracle = LogicExpressionOracle(buf, optimization=optimization) grover = Grover(oracle, num_iterations=num_iterations, incremental=incremental, mct_mode=mct_mode) run_config = RunConfig(shots=1000, max_credits=10, memory=False) quantum_instance = QuantumInstance(backend, run_config) ret = grover.run(quantum_instance) self.log.debug('Ground-truth Solutions: {}.'.format(self.groundtruth)) self.log.debug('Top measurement: {}.'.format( ret['top_measurement'])) if ret['oracle_evaluation']: self.assertIn(ret['top_measurement'], self.groundtruth) self.log.debug('Search Result: {}.'.format(ret['result'])) else: self.assertEqual(self.groundtruth, ['']) self.log.debug('Nothing found.')
def test_end2end_h2(self, name, optimizer, backend, mode, shots): if optimizer == 'COBYLA': optimizer = COBYLA() optimizer.set_options(maxiter=1000) elif optimizer == 'SPSA': optimizer = SPSA(max_trials=2000) ryrz = RYRZ(self.algo_input.qubit_op.num_qubits, depth=3, entanglement='full') vqe = VQE(self.algo_input.qubit_op, ryrz, optimizer, mode, aux_operators=self.algo_input.aux_ops) run_config = RunConfig(shots=shots, max_credits=10, memory=False) quantum_instance = QuantumInstance(backend, run_config) results = vqe.run(quantum_instance) self.assertAlmostEqual(results['energy'], self.reference_energy, places=4)
def setUp(self): super().setUp() self.random_seed = 10598 qr = QuantumRegister(2) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]) qc.cx(qr[0], qr[1]) # Ensure qubit 0 is measured before qubit 1 qc.barrier(qr) qc.measure(qr[0], cr[0]) qc.barrier(qr) qc.measure(qr[1], cr[1]) self.qc = qc self.backend = get_aer_backend('qasm_simulator') self.run_config = RunConfig(seed=self.random_seed, shots=1024)
def compile(circuits, backend, config=None, basis_gates=None, coupling_map=None, initial_layout=None, shots=1024, max_credits=10, seed=None, qobj_id=None, seed_mapper=None, pass_manager=None, memory=False): """Compile a list of circuits into a qobj. Args: circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile backend (BaseBackend): a backend to compile for config (dict): dictionary of parameters (e.g. noise) used by runner basis_gates (str): comma-separated basis gate set to compile to coupling_map (list): coupling map (perhaps custom) to target in mapping initial_layout (list): initial layout of qubits in mapping shots (int): number of repetitions of each circuit, for sampling max_credits (int): maximum credits to use seed (int): random seed for simulators seed_mapper (int): random seed for swapper mapper qobj_id (int): identifier for the generated qobj pass_manager (PassManager): a pass manger for the transpiler pipeline memory (bool): if True, per-shot measurement bitstrings are returned as well Returns: Qobj: the qobj to be run on the backends Raises: QiskitError: if the desired options are not supported by backend """ if config: warnings.warn( 'The `config` argument is deprecated and ' 'does not do anything', DeprecationWarning) circuits = transpiler.transpile(circuits, backend, basis_gates, coupling_map, initial_layout, seed_mapper, pass_manager) # step 4: Making a qobj run_config = RunConfig() if seed: run_config.seed = seed if shots: run_config.shots = shots if max_credits: run_config.max_credits = max_credits if memory: run_config.memory = memory qobj = circuits_to_qobj(circuits, user_qobj_header=QobjHeader(), run_config=run_config, qobj_id=qobj_id) return qobj
def __init__(self, backend, run_config=None, initial_layout=None, pass_manager=None, seed_mapper=None, backend_options=None, noise_model=None, timeout=None, wait=5, circuit_cache=None, skip_qobj_validation=False): """Constructor. Args: backend (BaseBackend): instance of selected backend run_config (RunConfig): the run config see https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/qobj/run_config.py initial_layout (dict): initial layout of qubits in mapping pass_manager (PassManager): pass manager to handle how to compile the circuits seed_mapper (int): the random seed for circuit mapper backend_options (dict): all config setting for backend noise_model (qiskit.provider.aer.noise.noise_model.NoiseModel): noise model for simulator timeout (float or None): seconds to wait for job. If None, wait indefinitely. wait (float): seconds between queries to result circuit_cache (CircuitCache): A CircuitCache to use when calling compile_and_run_circuits skip_qobj_validation (bool): Bypass Qobj validation to decrease submission time """ self._backend = backend # setup run config if run_config is None: run_config = RunConfig(shots=1024, max_credits=10, memory=False) if getattr(run_config, 'shots', None) is not None: if self.is_statevector and run_config.shots == 1: logger.info("statevector backend only works with shot=1, change " "shots from {} to 1.".format(run_config.shots)) run_config.shots = 1 if getattr(run_config, 'memory', None) is not None: if not self.is_simulator and run_config.memory is True: logger.info("The memory flag only supports simulator rather than real device. " "Change it to from {} to False.".format(run_config.memory)) run_config.memory = False self._run_config = run_config # setup backend config coupling_map = getattr(backend.configuration(), 'coupling_map', None) # TODO: basis gates will be [str] rather than comma-separated str basis_gates = backend.configuration().basis_gates if isinstance(basis_gates, list): basis_gates = ','.join(basis_gates) self._backend_config = { 'basis_gates': basis_gates, 'coupling_map': coupling_map } # setup noise config noise_config = None if noise_model is not None: if is_aer_provider(self._backend): if not self.is_statevector: noise_config = noise_model else: logger.info("The noise model can be only used with Aer qasm simulator. " "Change it to None.") else: logger.info("The noise model can be only used with Qiskit Aer. " "Please install it.") self._noise_config = {} if noise_config is None else {'noise_model': noise_config} # setup compile config self._compile_config = { 'pass_manager': pass_manager, 'initial_layout': initial_layout, 'seed_mapper': seed_mapper, 'qobj_id': None } # setup job config self._qjob_config = {'timeout': timeout} if self.is_local \ else {'timeout': timeout, 'wait': wait} # setup backend options for run self._backend_options = {} if isinstance(self._backend.provider(), IBMQProvider): logger.info("backend_options can not used with the backends in IBMQ provider.") else: self._backend_options = {} if backend_options is None \ else {'backend_options': backend_options} self._shared_circuits = False self._circuit_summary = False self._circuit_cache = circuit_cache self._skip_qobj_validation = skip_qobj_validation logger.info(self)
def __init__(self, backend, shots=1024, seed=None, max_credits=10, basis_gates=None, coupling_map=None, initial_layout=None, pass_manager=None, seed_mapper=None, backend_options=None, noise_model=None, timeout=None, wait=5, circuit_cache=None, skip_qobj_validation=False): """Constructor. Args: backend (BaseBackend): instance of selected backend shots (int, optional): number of repetitions of each circuit, for sampling seed (int, optional): random seed for simulators max_credits (int, optional): maximum credits to use basis_gates (list[str], optional): list of basis gate names supported by the target. Default: ['u1','u2','u3','cx','id'] coupling_map (list[list]): coupling map (perhaps custom) to target in mapping initial_layout (dict, optional): initial layout of qubits in mapping pass_manager (PassManager, optional): pass manager to handle how to compile the circuits seed_mapper (int, optional): the random seed for circuit mapper backend_options (dict, optional): all running options for backend, please refer to the provider. noise_model (qiskit.provider.aer.noise.noise_model.NoiseModel, optional): noise model for simulator timeout (float, optional): seconds to wait for job. If None, wait indefinitely. wait (float, optional): seconds between queries to result circuit_cache (CircuitCache, optional): A CircuitCache to use when calling compile_and_run_circuits skip_qobj_validation (bool, optional): Bypass Qobj validation to decrease submission time """ self._backend = backend # setup run config run_config = RunConfig(shots=shots, max_credits=max_credits) if seed: run_config.seed = seed if getattr(run_config, 'shots', None) is not None: if self.is_statevector and run_config.shots != 1: logger.info( "statevector backend only works with shot=1, change " "shots from {} to 1.".format(run_config.shots)) run_config.shots = 1 self._run_config = run_config # setup backend config basis_gates = basis_gates or backend.configuration().basis_gates coupling_map = coupling_map or getattr(backend.configuration(), 'coupling_map', None) self._backend_config = { 'basis_gates': basis_gates, 'coupling_map': coupling_map } # setup noise config noise_config = None if noise_model is not None: if is_aer_provider(self._backend): if not self.is_statevector: noise_config = noise_model else: logger.info( "The noise model can be only used with Aer qasm simulator. " "Change it to None.") else: logger.info( "The noise model can be only used with Qiskit Aer. " "Please install it.") self._noise_config = {} if noise_config is None else { 'noise_model': noise_config } # setup compile config if initial_layout is not None and not isinstance( initial_layout, Layout): initial_layout = Layout(initial_layout) self._compile_config = { 'pass_manager': pass_manager, 'initial_layout': initial_layout, 'seed_mapper': seed_mapper } # setup job config self._qjob_config = {'timeout': timeout} if self.is_local \ else {'timeout': timeout, 'wait': wait} # setup backend options for run self._backend_options = {} if is_ibmq_provider(self._backend): logger.info( "backend_options can not used with the backends in IBMQ provider." ) else: self._backend_options = {} if backend_options is None \ else {'backend_options': backend_options} self._shared_circuits = False self._circuit_summary = False self._circuit_cache = circuit_cache self._skip_qobj_validation = skip_qobj_validation logger.info(self)
def _build_algorithm_from_dict(self, quantum_instance): _discover_on_demand() self._parser = InputParser(self._params) self._parser.parse() # before merging defaults attempts to find a provider for the backend in case no # provider was passed if quantum_instance 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)) self._parser.validate_merge_defaults() logger.debug('Algorithm Input: {}'.format( json.dumps(self._parser.get_sections(), sort_keys=True, indent=4))) algo_name = self._parser.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 self._algorithm_input is None: input_name = self._parser.get_section_property( 'input', JSONSchema.NAME) if input_name is not None: input_params = copy.deepcopy( self._parser.get_section_properties('input')) del input_params[JSONSchema.NAME] convert_json_to_dict(input_params) self._algorithm_input = get_pluggable_class( PluggableType.INPUT, input_name).from_params(input_params) algo_params = copy.deepcopy(self._parser.get_sections()) self._quantum_algorithm = get_pluggable_class( PluggableType.ALGORITHM, algo_name).init_params(algo_params, self._algorithm_input) random_seed = self._parser.get_section_property( JSONSchema.PROBLEM, 'random_seed') self._quantum_algorithm.random_seed = random_seed if isinstance(quantum_instance, QuantumInstance): self._quantum_instance = quantum_instance return backend = None if isinstance(quantum_instance, BaseBackend): backend = quantum_instance elif quantum_instance is not None: raise AquaError( 'Invalid QuantumInstance or BaseBackend parameter {}.'.format( quantum_instance)) # setup backend backend_provider = self._parser.get_section_property( JSONSchema.BACKEND, JSONSchema.PROVIDER) backend_name = self._parser.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 self._parser.get_section( JSONSchema.BACKEND).items() if k not in [JSONSchema.PROVIDER, JSONSchema.NAME] } # TODO, how to build the noise model from a dictionary? 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 None: backend = get_backend_from_provider(backend_provider, backend_name) backend_cfg['backend'] = backend # overwrite the basis_gates and coupling_map basis_gates = backend_cfg.pop('basis_gates', None) if isinstance(basis_gates, str): basis_gates = basis_gates.split(',') coupling_map = backend_cfg.pop('coupling_map', None) if backend.configuration().simulator: if basis_gates is not None: backend.configuration().basis_gates = basis_gates if coupling_map is not None: backend.configuration().coupling_map = coupling_map else: logger.warning( "Change basis_gates and coupling_map on a real device is disallowed." ) shots = backend_cfg.pop('shots', 1024) seed = random_seed max_credits = backend_cfg.pop('max_credits', 10) memory = backend_cfg.pop('memory', False) run_config = RunConfig(shots=shots, max_credits=max_credits, memory=memory) if seed is not None: run_config.seed = seed backend_cfg['run_config'] = run_config backend_cfg[ 'skip_qobj_validation'] = self._parser.get_section_property( JSONSchema.PROBLEM, 'skip_qobj_validation') use_caching = self._parser.get_section_property( JSONSchema.PROBLEM, 'circuit_caching') if use_caching: deepcopy_qobj = self._parser.get_section_property( JSONSchema.PROBLEM, 'skip_qobj_deepcopy') cache_file = self._parser.get_section_property( JSONSchema.PROBLEM, 'circuit_cache_file') backend_cfg['circuit_cache'] = CircuitCache( skip_qobj_deepcopy=deepcopy_qobj, cache_file=cache_file) self._quantum_instance = QuantumInstance(**backend_cfg)
def load_qobj_from_cache(self, circuits, chunk, run_config=None): self.try_loading_cache_from_file() if self.try_reusing_qobjs and self.qobjs is not None and len( self.qobjs) <= chunk: self.mappings.insert(chunk, self.mappings[0]) self.qobjs.insert(chunk, copy.deepcopy(qobjs[0])) for circ_num, input_circuit in enumerate(circuits): # If there are too few experiments in the cache, try reusing the first experiment. # Only do this for the first chunk. Subsequent chunks should rely on these copies # through the deepcopy above. if self.try_reusing_qobjs and chunk == 0 and circ_num > 0 and len(self.qobjs[chunk].experiments) <= \ circ_num: self.qobjs[0].experiments.insert( circ_num, copy.deepcopy(self.qobjs[0].experiments[0])) self.mappings[0].insert(circ_num, self.mappings[0][0]) # Unroll circuit in case of composite gates raw_gates = [] for gate in input_circuit.data: if isinstance(gate, CompositeGate): raw_gates += gate.instruction_list() else: raw_gates += [gate] self.qobjs[chunk].experiments[ circ_num].header.name = input_circuit.name for gate_num, compiled_gate in enumerate( self.qobjs[chunk].experiments[circ_num].instructions): if not hasattr(compiled_gate, 'params') or len(compiled_gate.params) < 1: continue if compiled_gate.name == 'snapshot': continue cache_index = self.mappings[chunk][circ_num][gate_num] uncompiled_gate = raw_gates[cache_index] # Need the 'getattr' wrapper because measure has no 'params' field and breaks this. if not len(getattr(compiled_gate, 'params', [])) == len(getattr(uncompiled_gate, 'params', [])) or \ not compiled_gate.name == uncompiled_gate.name: raise AquaError( 'Gate mismatch at gate {0} ({1}, {2} params) of circuit against gate {3} ({4}, ' '{5} params) of cached qobj'.format( cache_index, uncompiled_gate.name, len(uncompiled_gate.params), gate_num, compiled_gate.name, len(compiled_gate.params))) compiled_gate.params = np.array(uncompiled_gate.params, dtype=float).tolist() exec_qobj = copy.copy(self.qobjs[chunk]) if self.skip_qobj_deepcopy: exec_qobj.experiments = self.qobjs[chunk].experiments[ 0:len(circuits)] else: exec_qobj.experiments = copy.deepcopy( self.qobjs[chunk].experiments[0:len(circuits)]) if run_config is None: run_config = RunConfig(shots=1024, max_credits=10, memory=False) exec_qobj.config = QobjConfig(**run_config.to_dict()) exec_qobj.config.memory_slots = max( experiment.config.memory_slots for experiment in exec_qobj.experiments) exec_qobj.config.n_qubits = max( experiment.config.n_qubits for experiment in exec_qobj.experiments) return exec_qobj
def build_algorithm_from_dict(params, algo_input=None, backend=None): """ Construct algorithm as named in params, using params and algo_input as input data and returning a QuantumAlgorithm and QuantumInstance instance 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 backend (BaseBackend): Backend object to be used in place of backend name Returns: Ready-to-run QuantumAlgorithm and QuantumInstance as specified in input parameters. Note that no QuantumInstance will be returned if none is specified - None will be returned instead. """ _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] } # TODO, how to build the noise model from a dictionary? 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 None or not isinstance(backend, BaseBackend): backend = get_backend_from_provider(backend_provider, backend_name) backend_cfg['backend'] = backend # overwrite the basis_gates and coupling_map basis_gates = backend_cfg.pop('basis_gates', None) coupling_map = backend_cfg.pop('coupling_map', None) if backend.configuration().simulator: if basis_gates is not None: backend.configuration().basis_gates = basis_gates if coupling_map is not None: backend.configuration().coupling_map = coupling_map else: logger.warning( "Change basis_gates and coupling_map on a real device is disallowed." ) shots = backend_cfg.pop('shots', 1024) seed = random_seed max_credits = backend_cfg.pop('max_credits', 10) memory = backend_cfg.pop('memory', False) run_config = RunConfig(shots=shots, max_credits=max_credits, memory=memory) if seed is not None: run_config.seed = seed backend_cfg['run_config'] = run_config backend_cfg['skip_qobj_validation'] = inputparser.get_section_property( JSONSchema.PROBLEM, 'skip_qobj_validation') use_caching = inputparser.get_section_property(JSONSchema.PROBLEM, 'circuit_caching') if use_caching: deepcopy_qobj = inputparser.get_section_property( JSONSchema.PROBLEM, 'skip_qobj_deepcopy') cache_file = inputparser.get_section_property( JSONSchema.PROBLEM, 'circuit_cache_file') backend_cfg['circuit_cache'] = CircuitCache( skip_qobj_deepcopy=deepcopy_qobj, cache_file=cache_file) quantum_instance = QuantumInstance(**backend_cfg) # Note that quantum_instance can be None if none is specified return algorithm, quantum_instance
def test_qsvm_variational_callback(self): tmp_filename = 'qsvm_callback_test.csv' is_file_exist = os.path.exists(self._get_resource_path(tmp_filename)) if is_file_exist: os.remove(self._get_resource_path(tmp_filename)) def store_intermediate_result(eval_count, parameters, cost, batch_index): with open(self._get_resource_path(tmp_filename), 'a') as f: content = "{},{},{:.5f},{}".format(eval_count, parameters, cost, batch_index) print(content, file=f, flush=True) np.random.seed(self.random_seed) backend = get_aer_backend('qasm_simulator') num_qubits = 2 optimizer = COBYLA(maxiter=3) feature_map = SecondOrderExpansion(num_qubits=num_qubits, depth=2) var_form = RY(num_qubits=num_qubits, depth=1) svm = QSVMVariational(optimizer, feature_map, var_form, self.training_data, self.testing_data, callback=store_intermediate_result) svm.random_seed = self.random_seed run_config = RunConfig(shots=1024, max_credits=10, memory=False, seed=self.random_seed) quantum_instance = QuantumInstance(backend, run_config, seed_mapper=self.random_seed) svm.run(quantum_instance) is_file_exist = os.path.exists(self._get_resource_path(tmp_filename)) self.assertTrue(is_file_exist, "Does not store content successfully.") # check the content ref_content = [[ "0", "[ 0.18863864 -1.08197582 1.74432295 1.29765602]", "0.53367", "0" ], [ "1", "[ 1.18863864 -1.08197582 1.74432295 1.29765602]", "0.57261", "1" ], [ "2", "[ 0.18863864 -0.08197582 1.74432295 1.29765602]", "0.47137", "2" ]] with open(self._get_resource_path(tmp_filename)) as f: idx = 0 for record in f.readlines(): eval_count, parameters, cost, batch_index = record.split(",") self.assertEqual(eval_count.strip(), ref_content[idx][0]) self.assertEqual(parameters, ref_content[idx][1]) self.assertEqual(cost.strip(), ref_content[idx][2]) self.assertEqual(batch_index.strip(), ref_content[idx][3]) idx += 1 if is_file_exist: os.remove(self._get_resource_path(tmp_filename))