def test_backend_change(self, user_expectation): """Test that VQE works when backend changes.""" vqd = VQD( k=1, ansatz=TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz"), optimizer=SLSQP(maxiter=2), expectation=user_expectation, quantum_instance=BasicAer.get_backend("statevector_simulator"), ) result0 = vqd.compute_eigenvalues(operator=self.h2_op) if user_expectation is not None: with self.subTest("User expectation kept."): self.assertEqual(vqd.expectation, user_expectation) vqd.quantum_instance = BasicAer.get_backend("qasm_simulator") # works also if no expectation is set, since it will be determined automatically result1 = vqd.compute_eigenvalues(operator=self.h2_op) if user_expectation is not None: with self.subTest( "Change backend with user expectation, it is kept."): self.assertEqual(vqd.expectation, user_expectation) with self.subTest("Check results."): self.assertEqual(len(result0.optimal_point), len(result1.optimal_point))
def test_reuse(self): """Test re-using a VQD algorithm instance.""" vqd = VQD(k=1) with self.subTest(msg="assert running empty raises AlgorithmError"): with self.assertRaises(AlgorithmError): _ = vqd.compute_eigenvalues(operator=self.h2_op) ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") vqd.ansatz = ansatz with self.subTest(msg="assert missing operator raises AlgorithmError"): with self.assertRaises(AlgorithmError): _ = vqd.compute_eigenvalues(operator=self.h2_op) vqd.expectation = MatrixExpectation() vqd.quantum_instance = self.statevector_simulator with self.subTest(msg="assert VQE works once all info is available"): result = vqd.compute_eigenvalues(operator=self.h2_op) np.testing.assert_array_almost_equal(result.eigenvalues.real, self.h2_energy, decimal=2) 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 = vqd.compute_eigenvalues(operator=operator) self.assertAlmostEqual(result.eigenvalues.real[0], -1.0, places=5)