def test_closest_psd_matrix_import_error(self, input, mocker): """Test import error raising if cvxpy is not installed.""" with pytest.raises(ImportError) as import_error: mocker.patch.dict(sys.modules, {"cvxpy": None}) output = kern.closest_psd_matrix(input, fix_diagonal=True, feastol=1e-10) assert "CVXPY is required" in str(import_error.value)
def test_closest_psd_matrix_solve_error(self, input, solver): """Test verbose error raising if problem.solve crashes.""" with pytest.raises(Exception) as solve_error: output = kern.closest_psd_matrix(input, solver=solver, fix_diagonal=True, feastol=1e-10) assert "CVXPY solver did not converge." in str(solve_error.value)
def test_closest_psd_matrix(self, input, fix_diagonal, expected_output): """Test obtaining the closest positive semi-definite matrix using a semi-definite program.""" try: import cvxpy as cp output = kern.closest_psd_matrix(input, fix_diagonal=fix_diagonal, feastol=1e-10) except cp.error.SolverError: pytest.skip( "The cvxopt solver seems to not be installed on the system." "It is the default solver for qml.kernels.closest_psd_matrix" " and can be installed via `pip install cvxopt`." ) assert np.allclose(output, expected_output, atol=1e-5)
def test_closest_psd_matrix_small_perturb(self): """Test obtaining the closest positive semi-definite matrix using a semi-definite program with a small perturbation input. The small perturbation ensures that the solver does not get stuck. """ input, fix_diagonal, expected_output = ( np.array([[0, 1.000001], [1, 0]]), True, np.array([[1, 1], [1, 1]]), ) try: import cvxpy as cp output = kern.closest_psd_matrix(input, fix_diagonal=fix_diagonal, feastol=1e-10) except cp.error.SolverError: pytest.skip( "The cvxopt solver seems to not be installed on the system." "It is the default solver for qml.kernels.closest_psd_matrix" " and can be installed via `pip install cvxopt`." ) assert np.allclose(output, expected_output, atol=1e-5)