Skip to content

Commit

Permalink
ENH: Clearer error when fmin_slsqp obj doesn't return scalar (#6691)
Browse files Browse the repository at this point in the history
Closes gh-5433.
  • Loading branch information
b-carter authored and person142 committed Nov 1, 2016
1 parent 552f811 commit 38f5366
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
7 changes: 5 additions & 2 deletions scipy/optimize/slsqp.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def fmin_slsqp(func, x0, eqcons=(), f_eqcons=None, ieqcons=(), f_ieqcons=None,
Parameters
----------
func : callable f(x,*args)
Objective function.
Objective function. Must return a scalar.
x0 : 1-D ndarray of float
Initial guess for the independent variable(s).
eqcons : list, optional
Expand Down Expand Up @@ -364,7 +364,10 @@ def cjac(x, *args):
if mode == 0 or mode == 1: # objective and constraint evaluation requird

# Compute objective function
fx = func(x)
try:
fx = float(np.asarray(func(x)))
except:
raise ValueError("Objective function must return a scalar")
# Compute the constraints
if cons['eq']:
c_eq = concatenate([atleast_1d(con['fun'](x, *con['args']))
Expand Down
15 changes: 14 additions & 1 deletion scipy/optimize/tests/test_slsqp.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from __future__ import division, print_function, absolute_import

from numpy.testing import (assert_, assert_array_almost_equal, TestCase,
assert_allclose, assert_equal, run_module_suite)
assert_allclose, assert_equal, run_module_suite,
assert_raises)
import numpy as np

from scipy._lib._testutils import knownfailure_overridable
Expand Down Expand Up @@ -305,6 +306,18 @@ def test_integer_bounds(self):
# This should not raise an exception
fmin_slsqp(lambda z: z**2 - 1, [0], bounds=[[0, 1]], iprint=0)

def test_obj_must_return_scalar(self):
# Regression test for Github Issue #5433
# If objective function does not return a scalar, raises ValueError
with assert_raises(ValueError):
fmin_slsqp(lambda x: [0, 1], [1, 2, 3])

def test_obj_returns_scalar_in_list(self):
# Test for Github Issue #5433 and PR #6691
# Objective function should be able to return length-1 Python list
# containing the scalar
fmin_slsqp(lambda x: [0], [1, 2, 3])

def test_callback(self):
# Minimize, method='SLSQP': unbounded, approximated jacobian. Check for callback
callback = MyCallBack()
Expand Down

0 comments on commit 38f5366

Please sign in to comment.