From a5f357bb596e1c38f3816c674da6b4cb723162bf Mon Sep 17 00:00:00 2001 From: Matt Haberland Date: Tue, 7 May 2024 21:54:31 -0700 Subject: [PATCH] TST: optimize.minimize: test improved error message --- .../equality_constrained_sqp.py | 2 +- .../tests/test_minimize_constrained.py | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py b/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py index 233b0a380934..fb4c05dcdd03 100644 --- a/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py +++ b/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py @@ -86,7 +86,7 @@ def equality_constrained_sqp(fun_and_constr, grad_and_jac, lagr_hess, raise ValueError( "The 'expected square matrix' error can occur if there are" " more equality constraints than independent variables." - " Consider how your constraints are setup, or use" + " Consider how your constraints are set up, or use" " factorization_method='SVDFactorization'." ) from e else: diff --git a/scipy/optimize/tests/test_minimize_constrained.py b/scipy/optimize/tests/test_minimize_constrained.py index 1f68bfafae66..ee700ec6e959 100644 --- a/scipy/optimize/tests/test_minimize_constrained.py +++ b/scipy/optimize/tests/test_minimize_constrained.py @@ -10,7 +10,8 @@ Bounds, minimize, BFGS, - SR1) + SR1, + rosen) class Maratos: @@ -747,6 +748,22 @@ def nci(x): assert_allclose(res.fun, ref.fun) +def test_gh20665_too_many_constraints(): + # gh-20665 reports a confusing error message when there are more equality + # constraints than variables. Check that the error message is improved. + message = "...more equality constraints than independent variables..." + with pytest.raises(ValueError, match=message): + x0 = np.ones((2,)) + A_eq, b_eq = np.arange(6).reshape((3, 2)), np.ones((3,)) + g = NonlinearConstraint(lambda x: A_eq @ x, lb=b_eq, ub=b_eq) + minimize(rosen, x0, method='trust-constr', constraints=[g]) + # no error with `SVDFactorization` + with np.testing.suppress_warnings() as sup: + sup.filter(UserWarning) + minimize(rosen, x0, method='trust-constr', constraints=[g], + options={'factorization_method': 'SVDFactorization'}) + + class TestBoundedNelderMead: @pytest.mark.parametrize('bounds, x_opt',