Ejemplo n.º 1
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))
Ejemplo n.º 2
0
    def test_backend_change(self, user_expectation):
        """Test that VQE works when backend changes."""
        vqe = VQE(
            operator=self.h2_op,
            var_form=TwoLocal(rotation_blocks=['ry', 'rz'],
                              entanglement_blocks='cz'),
            optimizer=SLSQP(maxiter=2),
            expectation=user_expectation,
            quantum_instance=BasicAer.get_backend('statevector_simulator'))
        result0 = vqe.run()
        if user_expectation is not None:
            with self.subTest('User expectation kept.'):
                self.assertEqual(vqe.expectation, user_expectation)
        else:
            with self.subTest('Expectation created.'):
                self.assertIsInstance(vqe.expectation, ExpectationBase)
        try:
            vqe.set_backend(BasicAer.get_backend('qasm_simulator'))
        except Exception as ex:  # pylint: disable=broad-except
            self.fail("Failed to change backend. Error: '{}'".format(str(ex)))
            return

        result1 = vqe.run()
        if user_expectation is not None:
            with self.subTest(
                    'Change backend with user expectation, it is kept.'):
                self.assertEqual(vqe.expectation, user_expectation)
        else:
            with self.subTest(
                    'Change backend without user expectation, one created.'):
                self.assertIsInstance(vqe.expectation, ExpectationBase)

        with self.subTest('Check results.'):
            self.assertEqual(len(result0.optimal_point),
                             len(result1.optimal_point))
Ejemplo n.º 3
0
    def test_reuse(self):
        """Test re-using a VQE algorithm instance."""
        vqe = VQE()
        with self.subTest(msg='assert running empty raises AlgorithmError'):
            with self.assertRaises(AlgorithmError):
                _ = vqe.run()

        var_form = TwoLocal(rotation_blocks=['ry', 'rz'],
                            entanglement_blocks='cz')
        vqe.var_form = var_form
        with self.subTest(msg='assert missing operator raises AlgorithmError'):
            with self.assertRaises(AlgorithmError):
                _ = vqe.run()

        vqe.operator = self.h2_op
        with self.subTest(msg='assert missing backend raises AlgorithmError'):
            with self.assertRaises(AlgorithmError):
                _ = vqe.run()

        vqe.quantum_instance = self.statevector_simulator
        with self.subTest(msg='assert VQE works once all info is available'):
            result = vqe.run()
            self.assertAlmostEqual(result.eigenvalue.real,
                                   self.h2_energy,
                                   places=5)

        operator = PrimitiveOp(
            np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0,
                                                                  3]]))

        with self.subTest(msg='assert minimum eigensolver interface works'):
            result = vqe.compute_minimum_eigenvalue(operator)
            self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5)
Ejemplo n.º 4
0
    def test_with_aer_qasm(self):
        """Test VQE with Aer's qasm_simulator."""
        try:
            # pylint: disable=import-outside-toplevel
            from qiskit import Aer
        except Exception as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return
        backend = Aer.get_backend('qasm_simulator')
        optimizer = SPSA(maxiter=200, last_avg=5)
        wavefunction = self.ry_wavefunction

        vqe = VQE(self.h2_op,
                  wavefunction,
                  optimizer,
                  expectation=PauliExpectation())

        quantum_instance = QuantumInstance(
            backend,
            seed_simulator=aqua_globals.random_seed,
            seed_transpiler=aqua_globals.random_seed)
        result = vqe.run(quantum_instance)
        self.assertAlmostEqual(result.eigenvalue.real, -1.86305, places=2)
Ejemplo n.º 5
0
    def test_with_aer_qasm_snapshot_mode(self):
        """Test the VQE using Aer's qasm_simulator snapshot mode."""
        try:
            # pylint: disable=import-outside-toplevel
            from qiskit import Aer
        except Exception as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return
        backend = Aer.get_backend('qasm_simulator')
        optimizer = L_BFGS_B()
        wavefunction = self.ry_wavefunction

        vqe = VQE(self.h2_op,
                  wavefunction,
                  optimizer,
                  expectation=AerPauliExpectation())

        quantum_instance = QuantumInstance(
            backend,
            shots=1,
            seed_simulator=aqua_globals.random_seed,
            seed_transpiler=aqua_globals.random_seed)
        result = vqe.run(quantum_instance)
        self.assertAlmostEqual(result.eigenvalue.real,
                               self.h2_energy,
                               places=6)
Ejemplo n.º 6
0
 def test_circuit_input(self):
     """Test running the VQE on a plain QuantumCircuit object."""
     wavefunction = QuantumCircuit(2).compose(EfficientSU2(2))
     optimizer = SLSQP(maxiter=50)
     vqe = VQE(self.h2_op, wavefunction, optimizer=optimizer)
     result = vqe.run(self.statevector_simulator)
     self.assertAlmostEqual(result.eigenvalue.real,
                            self.h2_energy,
                            places=5)
Ejemplo n.º 7
0
    def test_basic_aer_qasm(self):
        """Test the VQE on BasicAer's QASM simulator."""
        optimizer = SPSA(maxiter=300, last_avg=5)
        wavefunction = self.ry_wavefunction

        vqe = VQE(self.h2_op, wavefunction, optimizer, max_evals_grouped=1)

        # TODO benchmark this later.
        result = vqe.run(self.qasm_simulator)
        self.assertAlmostEqual(result.eigenvalue.real, -1.86823, places=2)
Ejemplo n.º 8
0
 def test_max_evals_grouped(self, optimizer, places, max_evals_grouped):
     """ VQE Optimizers test """
     vqe = VQE(self.h2_op,
               self.ryrz_wavefunction,
               optimizer,
               max_evals_grouped=max_evals_grouped,
               quantum_instance=self.statevector_simulator)
     result = vqe.run()
     self.assertAlmostEqual(result.eigenvalue.real,
                            self.h2_energy,
                            places=places)
Ejemplo n.º 9
0
    def test_vqe(self):
        """Test VQE with gradients"""

        method = 'lin_comb'
        backend = 'qasm_simulator'
        q_instance = QuantumInstance(BasicAer.get_backend(backend),
                                     seed_simulator=79,
                                     seed_transpiler=2)
        # Define the Hamiltonian
        h2_hamiltonian = -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) \
                         - 0.01 * (Z ^ Z) + 0.18 * (X ^ X)
        h2_energy = -1.85727503

        # Define the Ansatz
        wavefunction = QuantumCircuit(2)
        params = ParameterVector('theta', length=8)
        itr = iter(params)
        wavefunction.ry(next(itr), 0)
        wavefunction.ry(next(itr), 1)
        wavefunction.rz(next(itr), 0)
        wavefunction.rz(next(itr), 1)
        wavefunction.cx(0, 1)
        wavefunction.ry(next(itr), 0)
        wavefunction.ry(next(itr), 1)
        wavefunction.rz(next(itr), 0)
        wavefunction.rz(next(itr), 1)

        # Conjugate Gradient algorithm
        optimizer = CG(maxiter=10)

        grad = Gradient(grad_method=method)

        # Gradient callable
        vqe = VQE(h2_hamiltonian,
                  wavefunction,
                  optimizer=optimizer,
                  gradient=grad)

        result = vqe.run(q_instance)
        np.testing.assert_almost_equal(result['optimal_value'],
                                       h2_energy,
                                       decimal=0)
Ejemplo n.º 10
0
    def test_ibmq(self):
        """ IBMQ VQE Test """
        from qiskit import IBMQ
        provider = IBMQ.load_account()
        backend = provider.get_backend('ibmq_qasm_simulator')
        ansatz = TwoLocal(rotation_blocks=['ry', 'rz'],
                          entanglement_blocks='cz')

        opt = SLSQP(maxiter=1)
        opt.set_max_evals_grouped(100)
        vqe = VQE(self.h2_op, ansatz, SLSQP(maxiter=2))

        result = vqe.run(backend)
        print(result)
        self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy)
        np.testing.assert_array_almost_equal(result.eigenvalue.real,
                                             self.h2_energy, 5)
        self.assertEqual(len(result.optimal_point), 16)
        self.assertIsNotNone(result.cost_function_evals)
        self.assertIsNotNone(result.optimizer_time)
Ejemplo n.º 11
0
    def test_basic_aer_statevector(self):
        """Test the VQE on BasicAer's statevector simulator."""
        wavefunction = self.ryrz_wavefunction
        vqe = VQE(self.h2_op, wavefunction, L_BFGS_B())

        result = vqe.run(
            QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                            basis_gates=['u1', 'u2', 'u3', 'cx', 'id'],
                            coupling_map=[[0, 1]],
                            seed_simulator=aqua_globals.random_seed,
                            seed_transpiler=aqua_globals.random_seed))

        with self.subTest(msg='test eigenvalue'):
            self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy)

        with self.subTest(msg='test dimension of optimal point'):
            self.assertEqual(len(result.optimal_point), 16)

        with self.subTest(msg='assert cost_function_evals is set'):
            self.assertIsNotNone(result.cost_function_evals)

        with self.subTest(msg='assert optimizer_time is set'):
            self.assertIsNotNone(result.optimizer_time)
Ejemplo n.º 12
0
    def test_with_aer_statevector(self):
        """Test VQE with Aer's statevector_simulator."""
        try:
            # pylint: disable=import-outside-toplevel
            from qiskit import Aer
        except Exception as ex:  # pylint: disable=broad-except
            self.skipTest(
                "Aer doesn't appear to be installed. Error: '{}'".format(
                    str(ex)))
            return
        backend = Aer.get_backend('statevector_simulator')
        wavefunction = self.ry_wavefunction
        optimizer = L_BFGS_B()

        vqe = VQE(self.h2_op, wavefunction, optimizer, max_evals_grouped=1)

        quantum_instance = QuantumInstance(
            backend,
            seed_simulator=aqua_globals.random_seed,
            seed_transpiler=aqua_globals.random_seed)
        result = vqe.run(quantum_instance)
        self.assertAlmostEqual(result.eigenvalue.real,
                               self.h2_energy,
                               places=6)
Ejemplo n.º 13
0
 def test_missing_varform_params(self):
     """Test specifying a variational form with no parameters raises an error."""
     circuit = QuantumCircuit(self.h2_op.num_qubits)
     vqe = VQE(self.h2_op, circuit)
     with self.assertRaises(RuntimeError):
         vqe.run(BasicAer.get_backend('statevector_simulator'))