Пример #1
0
def createPlot(exactGroundStateEnergy=-1.14,
               numberOfIterations=1000,
               bondLength=0.735,
               initialParameters=None,
               numberOfParameters=16,
               shotsPerPoint=1000,
               registerSize=12,
               map_type='jordan_wigner'):
    if initialParameters is None:
        initialParameters = np.random.rand(numberOfParameters)
    global qubitOp
    global qr_size
    global shots
    global values
    global plottingTime
    plottingTime = True
    shots = shotsPerPoint
    qr_size = registerSize
    optimizer = COBYLA(maxiter=numberOfIterations)
    iterations = []
    values = []
    for i in range(numberOfIterations):
        iterations.append(i + 1)

    #Build molecule with PySCF
    driver = PySCFDriver(atom="H .0 .0 .0; H .0 .0 " + str(bondLength),
                         unit=UnitsType.ANGSTROM,
                         charge=0,
                         spin=0,
                         basis='sto3g')
    molecule = driver.run()
    repulsion_energy = molecule.nuclear_repulsion_energy
    num_spin_orbitals = molecule.num_orbitals * 2
    num_particles = molecule.num_alpha + molecule.num_beta

    #Map fermionic operator to qubit operator and start optimization
    ferOp = FermionicOperator(h1=molecule.one_body_integrals,
                              h2=molecule.two_body_integrals)
    qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001)
    sol_opt = optimizer.optimize(numberOfParameters,
                                 energy_opt,
                                 gradient_function=None,
                                 variable_bounds=None,
                                 initial_point=initialParameters)

    #Adjust values to obtain Energy Error
    for i in range(len(values)):
        values[i] = values[i] + repulsion_energy - exactGroundStateEnergy

    #Saving and Plotting Data
    filename = 'Energy Error - Iterations'
    with open(filename, 'wb') as f:
        pickle.dump([iterations, values], f)
    plt.plot(iterations, values)
    plt.ylabel('Energy Error')
    plt.xlabel('Iterations')
    plt.show()
 def __init__(self, ansatz: Ansatz, budget=120):
     super().__init__(ansatz)
     self.__similarity_thresh = 1e-2
     self.sweep_count = 1
     self.maxiter = 200
     self.budget = budget
     self.sweep_divisions = 4
     self.optimizer = COBYLA(maxiter=self.maxiter, tol=1e-3)
     self.objective_function = None
     self.sweepspace_dimension = None
     self.num_vars = None
Пример #3
0
def main():
    # Parse all command line arguments
    args = parser.parse_args()
    shots = args.shots
    seed = args.seed
    basis = args.bell
    logfile = args.logfile
    verbose = args.verbose

    # Define the logger
    logger = logging.getLogger('task2')
    if logfile:
        logger.addHandler(logging.FileHandler(logfile))
    if verbose:
        logger.addHandler(logging.StreamHandler())
    logger.setLevel(logging.DEBUG)

    np.random.seed(seed=seed)

    # Get the noise model
    device_backend = FakeVigo()
    noise_model = NoiseModel.from_backend(device_backend)
    coupling_map = device_backend.configuration().coupling_map
    basis_gates = noise_model.basis_gates

    backend = Aer.get_backend('qasm_simulator')
    statevector_backend = Aer.get_backend('statevector_simulator')

    circuit = build_circuit(measure=basis)
    circuit_for_counts = build_circuit(measure='computational')
    unmeasured_circuit = build_circuit(measure=None)

    # qiskit's COBYLA can't take args to pass to the objective function, so we freeze them with functools.partial
    optimizer = COBYLA(maxiter=1000, tol=1e-8, disp=True)

    for nshots in shots:
        logger.debug('====================================================================================')
        logger.debug(f'\nShots per iteration: {nshots}')
        logger.debug(circuit)

        partial_objective_function = partial(objective_function, circuit=circuit, shots=nshots, backend=backend, bell_basis=(basis == 'bell'),
                                            noise_model=noise_model, coupling_map=coupling_map, basis_gates=basis_gates)
        ret = optimizer.optimize(num_vars=2, objective_function=partial_objective_function, 
                                initial_point=np.random.rand(len(circuit.parameters))*4*np.pi - 2*np.pi)


        params = ret[0]
        logger.debug(f'\nParameters:\n{params}')
        logger.debug(f'\nStatevector:\n{execute_circuit(unmeasured_circuit, params, statevector_backend).result().get_statevector()}')
        logger.debug(f'\nSimulated results:\n{execute_circuit(circuit_for_counts, params, backend, nshots, noise_model, coupling_map, basis_gates).result().get_counts()}')
        logger.debug('====================================================================================\n')

    sys.exit(ExitStatus.success)
    def test_end2end_h2(self, name, optimizer, backend, shots):
        """ end to end h2 """
        del name  # unused
        if optimizer == 'COBYLA':
            optimizer = COBYLA()
            optimizer.set_options(maxiter=1000)
        elif optimizer == 'SPSA':
            optimizer = SPSA(max_trials=2000)

        ryrz = RYRZ(self.qubit_op.num_qubits, depth=3, entanglement='full')
        vqe = VQE(self.qubit_op, ryrz, optimizer, aux_operators=self.aux_ops)
        quantum_instance = QuantumInstance(backend, shots=shots)
        results = vqe.run(quantum_instance)
        self.assertAlmostEqual(results['energy'], self.reference_energy, places=4)
    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.driver1 = HDF5Driver(
            hdf5_input=self.get_resource_path('test_oovqe_h4.hdf5'))
        self.driver2 = HDF5Driver(
            hdf5_input=self.get_resource_path('test_oovqe_lih.hdf5'))
        self.driver3 = HDF5Driver(
            hdf5_input=self.get_resource_path('test_oovqe_h4_uhf.hdf5'))

        self.energy1_rotation = -3.0104
        self.energy1 = -2.77  # energy of the VQE with pUCCD ansatz and LBFGSB optimizer
        self.energy2 = -7.70
        self.energy3 = -2.50
        self.initial_point1 = [
            0.039374, -0.47225463, -0.61891996, 0.02598386, 0.79045546,
            -0.04134567, 0.04944946, -0.02971617, -0.00374005, 0.77542149
        ]

        self.seed = 50

        self.optimizer = COBYLA(maxiter=1)
        self.transformation1 = \
            FermionicTransformation(qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER,
                                    two_qubit_reduction=False)
        self.transformation2 = \
            FermionicTransformation(qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER,
                                    two_qubit_reduction=False,
                                    freeze_core=True)

        self.quantum_instance = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'),
            shots=1,
            seed_simulator=self.seed,
            seed_transpiler=self.seed)
Пример #7
0
    def simulate(self, var_params):
        """ Evaluate the parameterized circuit for the input amplitudes.

        Args:
            var_params (list): The initial amplitudes (float64).
        Returns:
            float64: The total energy (energy).
        Raise:
            ValueError: If the dimension of the amplitude list is incorrect.
        """
        if len(var_params) != self.amplitude_dimension:
            raise ValueError("Incorrect dimension for amplitude list.")

        # Use the Qiskit VQE class to perform a single energy evaluation
        from qiskit.aqua.components.optimizers import COBYLA
        cobyla = COBYLA(maxiter=0)
        vqe = VQE(self.qubit_hamiltonian,
                  self.var_form,
                  cobyla,
                  initial_point=var_params)
        quantum_instance = QuantumInstance(backend=self.backend, shots=1000000)
        results = vqe.run(quantum_instance)

        energy = results['eigvals'][0] + self.nuclear_repulsion_energy

        # Save the amplitudes so we have the optimal ones for RDM calculation
        self.optimized_amplitudes = var_params

        return energy
Пример #8
0
    def test_vqc_statevector(self, mode):
        """ vqc statevector test """
        aqua_globals.random_seed = 10598
        optimizer = COBYLA()
        data_preparation = self.data_preparation[mode]
        wavefunction = self.ryrz_wavefunction[mode]

        if mode == 'wrapped':
            warnings.filterwarnings('ignore', category=DeprecationWarning)
        # set up algorithm
        vqc = VQC(optimizer, data_preparation, wavefunction,
                  self.training_data, self.testing_data)

        if mode in ['circuit', 'library']:
            vqc._feature_map_params = self._sorted_data_params
            vqc._var_form_params = self._sorted_wavefunction_params
        else:
            warnings.filterwarnings('always', category=DeprecationWarning)

        quantum_instance = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'),
            seed_simulator=aqua_globals.random_seed,
            seed_transpiler=aqua_globals.random_seed)
        result = vqc.run(quantum_instance)
        ref_train_loss = 0.1059404
        np.testing.assert_array_almost_equal(result['training_loss'],
                                             ref_train_loss,
                                             decimal=4)

        self.assertEqual(result['testing_accuracy'], 0.5)
Пример #9
0
    def test_qaoa_qc_mixer(self, w, prob, solutions, convert_to_matrix_op):
        """ QAOA test with a mixer as a parameterized circuit"""
        seed = 0
        aqua_globals.random_seed = seed
        self.log.debug(
            'Testing %s-step QAOA with MaxCut on graph with '
            'a mixer as a parameterized circuit\n%s', prob, w)

        backend = BasicAer.get_backend('statevector_simulator')
        optimizer = COBYLA()
        qubit_op, _ = max_cut.get_operator(w)
        qubit_op = qubit_op.to_opflow()
        if convert_to_matrix_op:
            qubit_op = qubit_op.to_matrix_op()

        num_qubits = qubit_op.num_qubits
        mixer = QuantumCircuit(num_qubits)
        theta = Parameter('θ')
        mixer.rx(theta, range(num_qubits))

        qaoa = QAOA(qubit_op, optimizer, prob, mixer=mixer)
        quantum_instance = QuantumInstance(backend,
                                           seed_simulator=seed,
                                           seed_transpiler=seed)

        result = qaoa.run(quantum_instance)
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)
        self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                      solutions)
Пример #10
0
    def test_qaoa_qc_mixer_many_parameters(self):
        """ QAOA test with a mixer as a parameterized circuit with the num of parameters > 1. """
        seed = 0
        aqua_globals.random_seed = seed

        optimizer = COBYLA()
        qubit_op, _ = max_cut.get_operator(W1)
        qubit_op = qubit_op.to_opflow()

        num_qubits = qubit_op.num_qubits
        mixer = QuantumCircuit(num_qubits)
        for i in range(num_qubits):
            theta = Parameter('θ' + str(i))
            mixer.rx(theta, range(num_qubits))

        qaoa = QAOA(qubit_op, optimizer=optimizer, p=2, mixer=mixer)
        backend = BasicAer.get_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend,
                                           seed_simulator=seed,
                                           seed_transpiler=seed)
        result = qaoa.run(quantum_instance)
        x = sample_most_likely(result.eigenstate)
        print(x)
        graph_solution = max_cut.get_graph_solution(x)
        self.assertIn(''.join([str(int(i)) for i in graph_solution]), S1)
Пример #11
0
    def setUp(self):

        super().setUp()
        self.energy1_rotation = -3.0104
        self.energy1 = -2.77  # energy of the VQE with pUCCD ansatz and LBFGSB optimizer
        self.energy2 = -7.70
        self.energy3 = -2.50
        self.initial_point1 = [0.039374, -0.47225463, -0.61891996, 0.02598386, 0.79045546,
                               -0.04134567, 0.04944946, -0.02971617, -0.00374005, 0.77542149]
        self.seed = 50
        aqua_globals.random_seed = self.seed
        self.quantum_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                                                shots=1,
                                                seed_simulator=self.seed,
                                                seed_transpiler=self.seed)
        self.optimizer = COBYLA(maxiter=1)
        self.qmolecule1, self.core1, self.qubit_op1, self.var_form1, self.algo1\
            = self._create_components_for_tests(path='test_oovqe_h4.hdf5',
                                                freeze_core=False, two_qubit_reduction=False,
                                                initial_point=self.initial_point1)
        self.qmolecule2, self.core2, self.qubit_op2, self.var_form2, self.algo2\
            = self._create_components_for_tests(path='test_oovqe_lih.hdf5',
                                                freeze_core=True, two_qubit_reduction=True,
                                                initial_point=None)
        self.qmolecule3, self.core3, self.qubit_op3, self.var_form3, self.algo3\
            = self._create_components_for_tests(path='test_oovqe_h4_uhf.hdf5',
                                                freeze_core=False, two_qubit_reduction=False,
                                                initial_point=self.initial_point1)
Пример #12
0
    def test_qaoa(self, w, prob, m, solutions):
        """ QAOA test """
        seed = 0
        aqua_globals.random_seed = seed
        os.environ.pop('QISKIT_AQUA_CIRCUIT_CACHE', None)
        self.log.debug('Testing %s-step QAOA with MaxCut on graph\n%s', prob,
                       w)

        backend = BasicAer.get_backend('statevector_simulator')
        optimizer = COBYLA()
        qubit_op, offset = max_cut.get_qubit_op(w)

        qaoa = QAOA(qubit_op, optimizer, prob, mixer=m)
        # TODO: cache fails for QAOA since we construct the evolution circuit via instruction
        quantum_instance = QuantumInstance(backend,
                                           circuit_caching=False,
                                           seed_simulator=seed,
                                           seed_transpiler=seed)

        result = qaoa.run(quantum_instance)
        x = sample_most_likely(result['eigvecs'][0])
        graph_solution = max_cut.get_graph_solution(x)
        self.log.debug('energy:             %s', result['energy'])
        self.log.debug('time:               %s', result['eval_time'])
        self.log.debug('maxcut objective:   %s', result['energy'] + offset)
        self.log.debug('solution:           %s', graph_solution)
        self.log.debug('solution objective: %s', max_cut.max_cut_value(x, w))
        self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                      solutions)
        if quantum_instance.has_circuit_caching:
            self.assertLess(quantum_instance._circuit_cache.misses, 3)
Пример #13
0
    def test_vqc_minibatching_no_gradient_support(self, mode):
        """ vqc minibatching with no gradient support test """
        n_dim = 2  # dimension of each data point
        seed = 1024
        aqua_globals.random_seed = seed
        _, training_input, test_input, _ = ad_hoc_data(training_size=6,
                                                       test_size=3,
                                                       n=n_dim,
                                                       gap=0.3,
                                                       plot_data=False)
        backend = BasicAer.get_backend('statevector_simulator')
        optimizer = COBYLA(maxiter=40)
        data_preparation = self.data_preparation[mode]
        wavefunction = self.ryrz_wavefunction[mode]

        if mode == 'wrapped':
            warnings.filterwarnings('ignore', category=DeprecationWarning)

        # set up algorithm
        vqc = VQC(optimizer,
                  data_preparation,
                  wavefunction,
                  training_input,
                  test_input,
                  minibatch_size=2)

        if mode == 'wrapped':
            warnings.filterwarnings('always', category=DeprecationWarning)

        quantum_instance = QuantumInstance(backend,
                                           seed_simulator=seed,
                                           seed_transpiler=seed,
                                           optimization_level=0)
        result = vqc.run(quantum_instance)
        self.assertGreaterEqual(result['testing_accuracy'], 0.5)
Пример #14
0
    def test_qaoa_initial_point(self, w, solutions, init_pt):
        """ Check first parameter value used is initial point as expected """
        optimizer = COBYLA()
        qubit_op, _ = max_cut.get_operator(w)

        first_pt = []

        def cb_callback(eval_count, parameters, mean, std):
            nonlocal first_pt
            if eval_count == 1:
                first_pt = list(parameters)

        quantum_instance = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'))
        qaoa = QAOA(qubit_op,
                    optimizer,
                    initial_point=init_pt,
                    callback=cb_callback,
                    quantum_instance=quantum_instance)

        result = qaoa.compute_minimum_eigenvalue()
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)

        if init_pt is None:  # If None the preferred initial point of QAOA variational form
            init_pt = [0.0,
                       0.0]  # i.e. 0,0 should come through as the first point

        with self.subTest('Initial Point'):
            self.assertListEqual(init_pt, first_pt)

        with self.subTest('Solution'):
            self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                          solutions)
Пример #15
0
    def test_qaoa(self, w, prob, m, solutions, convert_to_matrix_op):
        """ QAOA test """
        seed = 0
        aqua_globals.random_seed = seed
        self.log.debug('Testing %s-step QAOA with MaxCut on graph\n%s', prob,
                       w)

        backend = BasicAer.get_backend('statevector_simulator')
        optimizer = COBYLA()
        qubit_op, offset = max_cut.get_operator(w)
        qubit_op = qubit_op.to_opflow()
        if convert_to_matrix_op:
            qubit_op = qubit_op.to_matrix_op()

        qaoa = QAOA(qubit_op, optimizer, prob, mixer=m)
        quantum_instance = QuantumInstance(backend,
                                           seed_simulator=seed,
                                           seed_transpiler=seed)

        result = qaoa.run(quantum_instance)
        x = sample_most_likely(result.eigenstate)
        graph_solution = max_cut.get_graph_solution(x)
        self.log.debug('energy:             %s', result.eigenvalue.real)
        self.log.debug('time:               %s', result.optimizer_time)
        self.log.debug('maxcut objective:   %s',
                       result.eigenvalue.real + offset)
        self.log.debug('solution:           %s', graph_solution)
        self.log.debug('solution objective: %s', max_cut.max_cut_value(x, w))
        self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                      solutions)
Пример #16
0
    def test_callback(self):
        """Test the callback on VQE."""
        history = {'eval_count': [], 'parameters': [], 'mean': [], 'std': []}

        def store_intermediate_result(eval_count, parameters, mean, std):
            history['eval_count'].append(eval_count)
            history['parameters'].append(parameters)
            history['mean'].append(mean)
            history['std'].append(std)

        optimizer = COBYLA(maxiter=3)
        wavefunction = self.ry_wavefunction

        vqe = VQE(self.h2_op,
                  wavefunction,
                  optimizer,
                  callback=store_intermediate_result)
        vqe.run(self.qasm_simulator)

        self.assertTrue(
            all(isinstance(count, int) for count in history['eval_count']))
        self.assertTrue(
            all(isinstance(mean, float) for mean in history['mean']))
        self.assertTrue(all(isinstance(std, float) for std in history['std']))
        for params in history['parameters']:
            self.assertTrue(all(isinstance(param, float) for param in params))
Пример #17
0
    def test_vqe_callback(self, var_form_type):
        """ VQE Callback test """
        history = {'eval_count': [], 'parameters': [], 'mean': [], 'std': []}

        def store_intermediate_result(eval_count, parameters, mean, std):
            history['eval_count'].append(eval_count)
            history['parameters'].append(parameters)
            history['mean'].append(mean)
            history['std'].append(std)

        backend = BasicAer.get_backend('qasm_simulator')
        num_qubits = self.qubit_op.num_qubits
        init_state = Zero(num_qubits)
        var_form = RY(num_qubits, depth=1, initial_state=init_state)
        if var_form_type is QuantumCircuit:
            params = ParameterVector('θ', var_form.num_parameters)
            var_form = var_form.construct_circuit(params)
        optimizer = COBYLA(maxiter=3)
        algo = VQE(self.qubit_op, var_form, optimizer,
                   callback=store_intermediate_result, auto_conversion=False)
        aqua_globals.random_seed = 50
        quantum_instance = QuantumInstance(backend,
                                           seed_transpiler=50,
                                           shots=1024,
                                           seed_simulator=50)
        algo.run(quantum_instance)

        self.assertTrue(all(isinstance(count, int) for count in history['eval_count']))
        self.assertTrue(all(isinstance(mean, float) for mean in history['mean']))
        self.assertTrue(all(isinstance(std, float) for std in history['std']))
        for params in history['parameters']:
            self.assertTrue(all(isinstance(param, float) for param in params))
Пример #18
0
    def test_h2_two_qubits_statevector(self):
        """Test H2 with parity mapping and statevector backend."""
        two_qubit_reduction = True
        qubit_mapping = 'parity'
        core = Hamiltonian(transformation=TransformationType.FULL,
                           qubit_mapping=QubitMappingType.PARITY,
                           two_qubit_reduction=two_qubit_reduction,
                           freeze_core=False,
                           orbital_reduction=[])
        qubit_op, _ = core.run(self.molecule)

        num_orbitals = core.molecule_info['num_orbitals']
        num_particles = core.molecule_info['num_particles']

        initial_state = HartreeFock(qubit_op.num_qubits, num_orbitals=num_orbitals,
                                    num_particles=num_particles, qubit_mapping=qubit_mapping,
                                    two_qubit_reduction=two_qubit_reduction)
        var_form = UCCSD(num_qubits=qubit_op.num_qubits, depth=1, num_orbitals=num_orbitals,
                         num_particles=num_particles,
                         initial_state=initial_state,
                         qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction)
        optimizer = COBYLA(maxiter=1000, tol=1e-8)

        eom_vqe = QEomVQE(qubit_op, var_form, optimizer, num_orbitals=num_orbitals,
                          num_particles=num_particles, qubit_mapping=qubit_mapping,
                          two_qubit_reduction=two_qubit_reduction)

        backend = BasicAer.get_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend)
        result = eom_vqe.run(quantum_instance)
        np.testing.assert_array_almost_equal(self.reference, result['energies'], decimal=4)
Пример #19
0
    def test_end2end_h2(self, name, optimizer, backend, shots):
        """ end to end h2 """
        del name  # unused
        if optimizer == 'COBYLA':
            optimizer = COBYLA()
            optimizer.set_options(maxiter=1000)
        elif optimizer == 'SPSA':
            optimizer = SPSA(maxiter=2000)

        ryrz = TwoLocal(rotation_blocks=['ry', 'rz'], entanglement_blocks='cz')
        vqe = VQE(self.qubit_op, ryrz, optimizer, aux_operators=self.aux_ops)
        quantum_instance = QuantumInstance(backend, shots=shots)
        result = vqe.run(quantum_instance)
        self.assertAlmostEqual(result.eigenvalue.real,
                               self.reference_energy,
                               places=4)
Пример #20
0
 def test_vqc_minibatching_no_gradient_support(self):
     """ vqc minibatching with no gradient support test """
     n_dim = 2  # dimension of each data point
     seed = 1024
     aqua_globals.random_seed = seed
     _, training_input, test_input, _ = ad_hoc_data(training_size=6,
                                                    test_size=3,
                                                    n=n_dim,
                                                    gap=0.3,
                                                    plot_data=False)
     backend = BasicAer.get_backend('statevector_simulator')
     num_qubits = n_dim
     optimizer = COBYLA(maxiter=40)
     feature_map = SecondOrderExpansion(feature_dimension=num_qubits,
                                        depth=2)
     var_form = RYRZ(num_qubits=num_qubits, depth=3)
     vqc = VQC(optimizer,
               feature_map,
               var_form,
               training_input,
               test_input,
               minibatch_size=2)
     quantum_instance = QuantumInstance(backend,
                                        seed_simulator=seed,
                                        seed_transpiler=seed,
                                        optimization_level=0)
     result = vqc.run(quantum_instance)
     self.log.debug(result['testing_accuracy'])
     self.assertGreaterEqual(result['testing_accuracy'], 0.5)
Пример #21
0
    def test_vqc_with_raw_feature_vector_on_wine(self):
        """ vqc with raw features vector on wine test """
        feature_dim = 4  # dimension of each data point
        training_dataset_size = 8
        testing_dataset_size = 4

        _, training_input, test_input, _ = _wine_data(
            training_size=training_dataset_size,
            test_size=testing_dataset_size,
            n=feature_dim
        )
        aqua_globals.random_seed = self.seed
        feature_map = RawFeatureVector(feature_dimension=feature_dim)
        vqc = VQC(COBYLA(maxiter=100),
                  feature_map,
                  RYRZ(feature_map.num_qubits, depth=3),
                  training_input,
                  test_input)
        result = vqc.run(QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                                         shots=1024,
                                         seed_simulator=aqua_globals.random_seed,
                                         seed_transpiler=aqua_globals.random_seed))
        self.log.debug(result['testing_accuracy'])

        self.assertGreater(result['testing_accuracy'], 0.8)
Пример #22
0
    def test_qaoa(self, w, p, m, solutions):
        self.log.debug('Testing {}-step QAOA with MaxCut on graph\n{}'.format(
            p, w))
        np.random.seed(0)

        backend = BasicAer.get_backend('statevector_simulator')
        optimizer = COBYLA()
        qubitOp, offset = max_cut.get_max_cut_qubitops(w)

        qaoa = QAOA(qubitOp, optimizer, p, operator_mode='matrix', mixer=m)
        quantum_instance = QuantumInstance(backend)

        result = qaoa.run(quantum_instance)
        x = max_cut.sample_most_likely(result['eigvecs'][0])
        graph_solution = max_cut.get_graph_solution(x)
        self.log.debug('energy:             {}'.format(result['energy']))
        self.log.debug('time:               {}'.format(result['eval_time']))
        self.log.debug('maxcut objective:   {}'.format(result['energy'] +
                                                       offset))
        self.log.debug('solution:           {}'.format(graph_solution))
        self.log.debug('solution objective: {}'.format(
            max_cut.max_cut_value(x, w)))
        self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                      solutions)
        if quantum_instance.has_circuit_caching:
            self.assertLess(quantum_instance._circuit_cache.misses, 3)
Пример #23
0
    def test_raw_feature_vector_on_wine(self, mode):
        """Test VQE on the wine dataset using the ``RawFeatureVector`` as data preparation."""
        feature_dim = 4  # dimension of each data point
        training_dataset_size = 8
        testing_dataset_size = 4

        _, training_input, test_input, _ = wine(
            training_size=training_dataset_size,
            test_size=testing_dataset_size,
            n=feature_dim,
            plot_data=False)
        if mode == 'component':
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            feature_map = LegacyRawFeatureVector(feature_dimension=feature_dim)
        else:
            feature_map = RawFeatureVector(feature_dimension=feature_dim)

        vqc = VQC(COBYLA(maxiter=100), feature_map,
                  TwoLocal(feature_map.num_qubits, ['ry', 'rz'], 'cz', reps=3),
                  training_input, test_input)
        result = vqc.run(self.statevector_simulator)
        if mode == 'component':
            warnings.filterwarnings('always', category=DeprecationWarning)

        self.log.debug(result['testing_accuracy'])
        self.assertGreater(result['testing_accuracy'], 0.7)
Пример #24
0
    def test_callback(self):
        """Test the callback function of the VQC."""
        history = {'eval_count': [], 'parameters': [], 'cost': [], 'batch_index': []}

        def store_intermediate_result(eval_count, parameters, cost, batch_index):
            history['eval_count'].append(eval_count)
            history['parameters'].append(parameters)
            history['cost'].append(cost)
            history['batch_index'].append(batch_index)

        optimizer = COBYLA(maxiter=3)
        data_preparation = self.data_preparation
        wavefunction = self.ryrz_wavefunction

        # set up algorithm
        vqc = VQC(optimizer, data_preparation, wavefunction, self.training_data, self.testing_data,
                  callback=store_intermediate_result)

        vqc.run(self.qasm_simulator)

        with self.subTest('eval count'):
            self.assertTrue(all(isinstance(count, int) for count in history['eval_count']))
        with self.subTest('cost'):
            self.assertTrue(all(isinstance(cost, float) for cost in history['cost']))
        with self.subTest('batch index'):
            self.assertTrue(all(isinstance(index, int) for index in history['batch_index']))
        for params in history['parameters']:
            with self.subTest('params'):
                self.assertTrue(all(isinstance(param, float) for param in params))
Пример #25
0
 def test_vqc_minibatching_no_gradient_support(self):
     n_dim = 2  # dimension of each data point
     seed = 1024
     np.random.seed(seed)
     sample_Total, training_input, test_input, class_labels = ad_hoc_data(
         training_size=8, test_size=4, n=n_dim, gap=0.3)
     aqua_globals.random_seed = seed
     backend = BasicAer.get_backend('statevector_simulator')
     num_qubits = n_dim
     optimizer = COBYLA()
     feature_map = SecondOrderExpansion(feature_dimension=num_qubits,
                                        depth=2)
     var_form = RYRZ(num_qubits=num_qubits, depth=3)
     vqc = VQC(optimizer,
               feature_map,
               var_form,
               training_input,
               test_input,
               minibatch_size=2)
     quantum_instance = QuantumInstance(backend,
                                        seed_simulator=seed,
                                        seed_transpiler=seed)
     result = vqc.run(quantum_instance)
     vqc_accuracy_threshold = 0.8
     self.log.debug(result['testing_accuracy'])
     self.assertGreater(result['testing_accuracy'], vqc_accuracy_threshold)
Пример #26
0
    def test_qaoa(self, w, p, m, solutions):
        os.environ.pop('QISKIT_AQUA_CIRCUIT_CACHE', None)
        self.log.debug('Testing {}-step QAOA with MaxCut on graph\n{}'.format(
            p, w))
        np.random.seed(0)

        backend = BasicAer.get_backend('statevector_simulator')
        optimizer = COBYLA()
        qubit_op, offset = max_cut.get_max_cut_qubitops(w)

        qaoa = QAOA(qubit_op, optimizer, p, mixer=m)
        # TODO: cache fails for QAOA since we construct the evolution circuit via instruction
        quantum_instance = QuantumInstance(backend, circuit_caching=False)

        result = qaoa.run(quantum_instance)
        x = max_cut.sample_most_likely(result['eigvecs'][0])
        graph_solution = max_cut.get_graph_solution(x)
        self.log.debug('energy:             {}'.format(result['energy']))
        self.log.debug('time:               {}'.format(result['eval_time']))
        self.log.debug('maxcut objective:   {}'.format(result['energy'] +
                                                       offset))
        self.log.debug('solution:           {}'.format(graph_solution))
        self.log.debug('solution objective: {}'.format(
            max_cut.max_cut_value(x, w)))
        self.assertIn(''.join([str(int(i)) for i in graph_solution]),
                      solutions)
        if quantum_instance.has_circuit_caching:
            self.assertLess(quantum_instance._circuit_cache.misses, 3)
Пример #27
0
def createPlot1(bondLengthMin=0.5,
                bondLengthMax=1.5,
                numberOfPoints=10,
                initialParameters=None,
                numberOfParameters=16,
                shotsPerPoint=1000,
                registerSize=12,
                map_type='jordan_wigner'):
    if initialParameters is None:
        initialParameters = np.random.rand(numberOfParameters)
    global qubitOp
    global qr_size
    global shots
    shots = shotsPerPoint
    qr_size = registerSize
    optimizer = COBYLA(maxiter=20)
    bondLengths = []
    values = []
    delta = (bondLengthMax - bondLengthMin) / numberOfPoints
    for i in range(numberOfPoints):
        bondLengths.append(bondLengthMin + i * delta)
    for bondLength in bondLengths:
        driver = PySCFDriver(atom="H .0 .0 .0; H .0 .0 " + str(bondLength),
                             unit=UnitsType.ANGSTROM,
                             charge=0,
                             spin=0,
                             basis='sto3g')
        molecule = driver.run()
        repulsion_energy = molecule.nuclear_repulsion_energy
        num_spin_orbitals = molecule.num_orbitals * 2
        num_particles = molecule.num_alpha + molecule.num_beta
        ferOp = FermionicOperator(h1=molecule.one_body_integrals,
                                  h2=molecule.two_body_integrals)
        qubitOp = ferOp.mapping(map_type=map_type, threshold=0.00000001)
        sol_opt = optimizer.optimize(numberOfParameters,
                                     energy_opt,
                                     gradient_function=None,
                                     variable_bounds=None,
                                     initial_point=initialParameters)
        values.append(sol_opt[1] + repulsion_energy)
    filename = 'Energy - BondLengths'
    with open(filename, 'wb') as f:
        pickle.dump([bondLengths, values], f)
    plt.plot(bondLengths, values)
    plt.ylabel('Ground State Energy')
    plt.xlabel('Bond Length')
    plt.show()
Пример #28
0
    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))
Пример #29
0
    def test_qaoa_initial_state(self, w, init_state):
        """ QAOA initial state test """

        optimizer = COBYLA()
        qubit_op, _ = max_cut.get_operator(w)

        init_pt = [0.0, 0.0]  # Avoid generating random initial point

        if init_state is None:
            initial_state = None
        else:
            initial_state = Custom(num_qubits=4, state_vector=init_state)

        quantum_instance = QuantumInstance(
            BasicAer.get_backend('statevector_simulator'))
        qaoa_zero_init_state = QAOA(qubit_op,
                                    optimizer,
                                    initial_point=init_pt,
                                    initial_state=Zero(qubit_op.num_qubits),
                                    quantum_instance=quantum_instance)
        qaoa = QAOA(qubit_op,
                    optimizer,
                    initial_point=init_pt,
                    initial_state=initial_state,
                    quantum_instance=quantum_instance)

        zero_circuits = qaoa_zero_init_state.construct_circuit(init_pt)
        custom_circuits = qaoa.construct_circuit(init_pt)

        self.assertEqual(len(zero_circuits), len(custom_circuits))

        backend = BasicAer.get_backend('statevector_simulator')
        for zero_circ, custom_circ in zip(zero_circuits, custom_circuits):

            z_length = len(zero_circ.data)
            c_length = len(custom_circ.data)

            self.assertGreaterEqual(c_length, z_length)
            self.assertTrue(zero_circ.data == custom_circ.data[-z_length:])

            custom_init_qc = custom_circ.copy()
            custom_init_qc.data = custom_init_qc.data[0:c_length - z_length]

            if initial_state is None:
                original_init_qc = QuantumCircuit(qubit_op.num_qubits)
                original_init_qc.h(range(qubit_op.num_qubits))
            else:
                original_init_qc = initial_state.construct_circuit()

            job_init_state = execute(original_init_qc, backend)
            job_qaoa_init_state = execute(custom_init_qc, backend)

            statevector_original = job_init_state.result().get_statevector(
                original_init_qc)
            statevector_custom = job_qaoa_init_state.result().get_statevector(
                custom_init_qc)

            self.assertEqual(statevector_original.tolist(),
                             statevector_custom.tolist())
    def optimize(self):

        # Define objective function
        def objfunc(params):
            return -self.expectation(beta=params[0:self.p],
                                     gamma=params[self.p:2 * self.p])

        # Optimize parameters
        optimizer = COBYLA(maxiter=1000, tol=0.0001)
        params = self.beta_val + self.gamma_val
        ret = optimizer.optimize(num_vars=2 * self.p,
                                 objective_function=objfunc,
                                 initial_point=params)
        self.beta_val = ret[0][0:self.p]
        self.gamma_val = ret[0][self.p:2 * self.p]
        self.error = ret[1]
        return