internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: scipy/scipy

Issue:
scipy.optimize.minimize returns success on function that returns NaN
```
def f(x):                                                                        
    return float('nan')

res = scipy.optimize.minimize(f, 1)
print(res)
```

will show `Optimization terminated successfully.`  and `success: True`, while obviously the minimum has not be found.

Explicitly setting the method, to, e.g., `method=Nelder-mead` does return `success: False`, which _is_ what one would expect.  



Discussion:
CG and L-BFGS-B also report success in this case. Powell, SLSQP and TNC report failure.


Resolving patch:
diff --git a/scipy/optimize/optimize.py b/scipy/optimize/optimize.py
--- a/scipy/optimize/optimize.py
+++ b/scipy/optimize/optimize.py
@@ -903,6 +903,11 @@ def _minimize_bfgs(fun, x0, args=(), jac=None, callback=None,
                                                  sk[numpy.newaxis, :])
 
     fval = old_fval
+    if np.isnan(fval):
+        # This can happen if the first call to f returned NaN;
+        # the loop is then never entered.
+        warnflag = 2
+
     if warnflag == 2:
         msg = _status_message['pr_loss']
         if disp:


Test patch:
diff --git a/scipy/optimize/tests/test_optimize.py b/scipy/optimize/tests/test_optimize.py
--- a/scipy/optimize/tests/test_optimize.py
+++ b/scipy/optimize/tests/test_optimize.py
@@ -384,6 +384,22 @@ def test_bfgs_nan(self):
             x = optimize.fmin_bfgs(func, x0, fprime, disp=False)
             assert_(np.isnan(func(x)))
 
+    def test_bfgs_nan_return(self):
+        # Test corner cases where fun returns NaN. See gh-4793.
+
+        # First case: NaN from first call.
+        func = lambda x: np.nan
+        result = optimize.minimize(func, 0)
+        assert_(np.isnan(result['fun']))
+        assert_(result['success'] is False)
+
+        # Second case: NaN from second call.
+        func = lambda x: 0 if x == 0 else np.nan
+        fprime = lambda x: np.ones_like(x)  # Steer away from zero.
+        result = optimize.minimize(func, 0, jac=fprime)
+        assert_(np.isnan(result['fun']))
+        assert_(result['success'] is False)
+
     def test_bfgs_numerical_jacobian(self):
         # BFGS with numerical jacobian and a vector epsilon parameter.
         # define the epsilon parameter using a random vector
Repository: scipy/scipy

Issue:
Keep order of entries in OptimizeResults.__str__ always the same
`OptimizeResults.__str__` returns the entries in the dict iteration order (I guess), which changes from run to run on recent Pythons.  This makes it hard to visually grep through outputs:

```
$ python script.py
      nit: 1
  success: True
        x: array([ 0.25,  0.25])
      jac: array([ 4.33663248, -0.75075413])
      fun: 2.303287891423524
 hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>
     nfev: 9
  message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'
   status: 0

$ python script.py
      fun: 2.303287891423524
     nfev: 9
  success: True
 hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>
  message: b'CONVERGENCE: REL_REDUCTION_OF_F_<=_FACTR*EPSMCH'
      jac: array([ 4.33663248, -0.75075413])
   status: 0
        x: array([ 0.25,  0.25])
      nit: 1
```

Sorting the keys would help.



Discussion:

Resolving patch:
diff --git a/scipy/optimize/_linprog.py b/scipy/optimize/_linprog.py
--- a/scipy/optimize/_linprog.py
+++ b/scipy/optimize/_linprog.py
@@ -510,13 +510,13 @@ def _linprog_simplex(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
     >>> x1_bnds = (-3, None)
     >>> res = linprog(c, A, b, bounds=(x0_bnds, x1_bnds))
     >>> print(res)
-    status: 0
-    x: array([ 10.,  -3.])
-    slack: array([ 39.,   0.])
-    nit: 1
-    message: 'Optimization terminated successfully.'
-    fun: -22.0
-    success: True
+         fun: -22.0
+     message: 'Optimization terminated successfully.'
+         nit: 1
+       slack: array([ 39.,   0.])
+      status: 0
+     success: True
+           x: array([ 10.,  -3.])
 
     References
     ----------
@@ -968,13 +968,13 @@ def linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
          Current function value: -22.000000
          Iterations: 1
     >>> print(res)
-      status: 0
-       slack: array([ 39.,   0.])
-     success: True
          fun: -22.0
-           x: array([ 10.,  -3.])
      message: 'Optimization terminated successfully.'
          nit: 1
+       slack: array([ 39.,   0.])
+      status: 0
+     success: True
+           x: array([ 10.,  -3.])
 
     Note the actual objective value is 11.428571.  In this case we minimized
     the negative of the objective function.
diff --git a/scipy/optimize/optimize.py b/scipy/optimize/optimize.py
--- a/scipy/optimize/optimize.py
+++ b/scipy/optimize/optimize.py
@@ -122,7 +122,7 @@ def __repr__(self):
         if self.keys():
             m = max(map(len, list(self.keys()))) + 1
             return '\n'.join([k.rjust(m) + ': ' + repr(v)
-                              for k, v in self.items()])
+                              for k, v in sorted(self.items())])
         else:
             return self.__class__.__name__ + "()"
 


Test patch:
Repository: scipy/scipy

Issue:
Documentation for scipy.integrate.ode incorrectly labels set_jac_params
Quick one - Under Parameters on:

http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.integrate.ode.html#scipy.integrate.ode

Parameters: 
f : callable f(t, y, _f_args) [...] f_args is set by calling set_f_params(_args)
jac : callable jac(t, y, _jac_args) [...] jac_args is set by calling set_f_params(_args)

set_jac_params is presumably what is called to set the jacobian parameters. 



Discussion:
indeed looks like a typo.


Resolving patch:
diff --git a/scipy/integrate/_ode.py b/scipy/integrate/_ode.py
--- a/scipy/integrate/_ode.py
+++ b/scipy/integrate/_ode.py
@@ -119,7 +119,7 @@ class ode(object):
         `f` should return a scalar, array or list (not a tuple).
     jac : callable ``jac(t, y, *jac_args)``, optional
         Jacobian of the right-hand side, ``jac[i,j] = d f[i] / d y[j]``.
-        ``jac_args`` is set by calling ``set_f_params(*args)``.
+        ``jac_args`` is set by calling ``set_jac_params(*args)``.
 
     Attributes
     ----------


Test patch:
Repository: scipy/scipy

Issue:
Changes to default values of differential_evolution break back compat. 
@dlax the current release version of `differential_evolution` uses these default values:

```
maxiter=None, maxfun=None
```

in current master these default values have been changed to numerical (due to a PR I submitted):

```
maxiter=1000, maxfun=np.inf
```

It made sense at the time to convert them to numerical defaults; the default `maxiter=None` was being converted to `maxiter=1000` internally, and it was changed to be an explicit default.

However, I now realise that this could break back compatibility; some scripts of mine (and therefore others) use `maxiter=None` or `maxfun=None`.
This causes problems at [line 496](https://github.com/scipy/scipy/blob/master/scipy/optimize/_differentialevolution.py#L496):

```
for nit in range(1, self.maxiter + 1):
```

If `None` is used for `maxiter` then you get an error: `unsupported operand type(s) for +: 'NoneType' and 'int'`.

I intend to submit a PR that will keep the new numerical defaults, but cope with `None` being supplied, thus preventing existing code from breaking.



Discussion:

Resolving patch:
diff --git a/scipy/optimize/_differentialevolution.py b/scipy/optimize/_differentialevolution.py
--- a/scipy/optimize/_differentialevolution.py
+++ b/scipy/optimize/_differentialevolution.py
@@ -360,7 +360,11 @@ def __init__(self, func, bounds, args=(),
                              'real valued (min, max) pairs for each value'
                              ' in x')
 
+        if maxiter is None:  # the default used to be None
+            maxiter = 1000
         self.maxiter = maxiter
+        if maxfun is None:  # the default used to be None
+            maxfun = np.inf
         self.maxfun = maxfun
 
         # population is scaled to between [0, 1].


Test patch:
diff --git a/scipy/optimize/tests/test__differential_evolution.py b/scipy/optimize/tests/test__differential_evolution.py
--- a/scipy/optimize/tests/test__differential_evolution.py
+++ b/scipy/optimize/tests/test__differential_evolution.py
@@ -408,6 +408,15 @@ def test_convergence(self):
         solver.solve()
         assert_(solver.convergence < 0.2)
 
+    def test_maxiter_none_GH5731(self):
+        # Pre 0.17 the previous default for maxiter and maxfun was None.
+        # the numerical defaults are now 1000 and np.inf. However, some scripts
+        # will still supply None for both of those, this will raise a TypeError
+        # in the solve method.
+        solver = DifferentialEvolutionSolver(rosen, self.bounds, maxiter=None,
+                                             maxfun=None)
+        solver.solve()
+
 
 if __name__ == '__main__':
     run_module_suite()
Repository: scipy/scipy

Issue:
KDtree/cKDtree add `seealso`  ?
KDtree/cKDtree do not reference each-other. 

is adding a `:seealso:` be useful ?

Any reason when using KDtree not to use cKDtree automatically when available ?



Discussion:
Yes. Although we'd like to make `KDTree` a simple alias of `cKDTree` in the near future I think (and after that remove the duplication by deprecating one) but until then this would improve the docs.

and for who picks this up, it's this in numpy docstring format:

```
See Also
--------
cKDTree : <one-liner explanation...>
```


Resolving patch:
diff --git a/scipy/spatial/kdtree.py b/scipy/spatial/kdtree.py
--- a/scipy/spatial/kdtree.py
+++ b/scipy/spatial/kdtree.py
@@ -199,6 +199,10 @@ class KDTree(object):
             >>> import sys
             >>> sys.setrecursionlimit(10000)
 
+    See Also
+    --------
+    cKDTree : Implementation of `KDTree` in Cython
+
     Notes
     -----
     The algorithm used is described in Maneewongvatana and Mount 1999.


Test patch:
Repository: scipy/scipy

Issue:
Error in scipy.linalg.expm for complex matrix with shape (1,1)
When using the function `scipy.linalg.expm` for complex matrices of shape `(1,1)`, some values result in a `IndexError: too many indices for array` error. A minimum example reproducing the error is given below.

This is with Anaconda `Python 2.7.11 :: Continuum Analytics, Inc.` and SciPy version `0.17.0`.

Note that only the value of the single matrix entry changes slightly.

**Minimum example**:

from scipy import sparse
from scipy.sparse import linalg 
v_works = -2.02683397006j
v_error = -2.12817566856j
M_works = sparse.csc_matrix([[v_works]], dtype='complex') 
M_error = sparse.csc_matrix([[v_error]], dtype='complex')
print linalg.expm(M_works)
print linalg.expm(M_error)



Discussion:
Given that the matrix exponential of a 1x1 matrix is trivial, the fix is probably to check this special case early on in `expm`  

What I found very surprising is that the error depends on the _value_ in the matrix. Any idea why this is? A breakdown of the Pade approximation or something?


Resolving patch:
diff --git a/scipy/sparse/linalg/matfuncs.py b/scipy/sparse/linalg/matfuncs.py
--- a/scipy/sparse/linalg/matfuncs.py
+++ b/scipy/sparse/linalg/matfuncs.py
@@ -592,6 +592,17 @@ def _expm(A, use_exact_onenorm):
     if len(A.shape) != 2 or A.shape[0] != A.shape[1]:
         raise ValueError('expected a square matrix')
 
+    # Trivial case
+    if A.shape == (1, 1):
+        out = [[np.exp(A[0, 0])]]
+
+        # Avoid indiscriminate casting to ndarray to
+        # allow for sparse or other strange arrays
+        if isspmatrix(A):
+            return A.__class__(out)
+
+        return np.array(out)
+
     # Detect upper triangularity.
     structure = UPPER_TRIANGULAR if _is_upper_triangular(A) else None
 


Test patch:
diff --git a/scipy/linalg/tests/test_matfuncs.py b/scipy/linalg/tests/test_matfuncs.py
--- a/scipy/linalg/tests/test_matfuncs.py
+++ b/scipy/linalg/tests/test_matfuncs.py
@@ -580,6 +580,27 @@ def test_npmatrix(self):
             a = matrix([[3.,0],[0,-3.]])
             assert_array_almost_equal(expm(a), expm2(a))
 
+    def test_single_elt(self):
+        # See gh-5853
+        from scipy.sparse import csc_matrix
+
+        vOne = -2.02683397006j
+        vTwo = -2.12817566856j
+
+        mOne = csc_matrix([[vOne]], dtype='complex')
+        mTwo = csc_matrix([[vTwo]], dtype='complex')
+
+        outOne = expm(mOne)
+        outTwo = expm(mTwo)
+
+        assert_equal(type(outOne), type(mOne))
+        assert_equal(type(outTwo), type(mTwo))
+
+        assert_allclose(outOne[0, 0], complex(-0.44039415155949196,
+                                              -0.8978045395698304))
+        assert_allclose(outTwo[0, 0], complex(-0.52896401032626006,
+                                              -0.84864425749518878))
+
 
 class TestExpmFrechet(TestCase):
Repository: scipy/scipy

Issue:
DeprecationWarnings in signaltools on python 3.5
Running scipy tests on python 3.5 throws a bunch of these warnings:

```
/home/br/repos/scipy/build/testenv/lib/python3.5/site-packages/scipy/signal/signaltools.py:1899: DeprecationWarning: fractions.gcd() is deprecated. Use math.gcd() instead.
  g_ = gcd(up, down)
```

`git blame` indicates ab803339 which went in as a part of https://github.com/scipy/scipy/pull/5749. 

@Eric89GXL, any suggestions?



Discussion:
Argh, Py35 issue. I'll have to look into whether six provides a wrapper, or
if we need to triage based on version manually (unless there is an
equivalent gcd in math on 2.7), unless someone has a better idea.

It's not in `six`. Just 

```
if sys.version_info[0] < 3:
    from fractions import gcd
else:
    from math import gcd
```

in signaltools.py should do the job. 

I'd like to contribute :)

Feel free to open a PR of you have time, I haven't started on it yet


Resolving patch:
diff --git a/scipy/signal/signaltools.py b/scipy/signal/signaltools.py
--- a/scipy/signal/signaltools.py
+++ b/scipy/signal/signaltools.py
@@ -5,7 +5,11 @@
 
 import warnings
 import threading
-from fractions import gcd
+import sys
+if sys.version_info.major >= 3 and sys.version_info.minor >= 5:
+    from math import gcd
+else:
+    from fractions import gcd
 
 from . import sigtools
 from ._upfirdn import _UpFIRDn, _output_len


Test patch:
Repository: scipy/scipy

Issue:
scipy.sparse.linalg.LinearOperator unpickle error
``` python
import numpy
import scipy.sparse.linalg
import pickle

M = N = 3

def matvec(x):
    return numpy.zeros(N)

A = scipy.sparse.linalg.LinearOperator((M, N), matvec)
s = pickle.dumps(A)
B = pickle.loads(s)
```

gives

```
$ python3 test.py
Traceback (most recent call last):
  File "test.py", line 14, in <module>
    B = pickle.loads(s)
  File "/usr/lib/python3/dist-packages/scipy/sparse/linalg/interface.py", line 142, in __new__
    obj.__init__(*args, **kwargs)
TypeError: __init__() missing 2 required positional arguments: 'shape' and 'matvec'`
```

but it works with `s = pickle.dumps(A, protocol = p)` for p in [0, 1] but not for p in [2, 3, 4].

This is scipy is 0.17.0 and python 3.5.1.



Discussion:

Resolving patch:
diff --git a/scipy/sparse/linalg/interface.py b/scipy/sparse/linalg/interface.py
--- a/scipy/sparse/linalg/interface.py
+++ b/scipy/sparse/linalg/interface.py
@@ -139,7 +139,6 @@ def __new__(cls, *args, **kwargs):
                 raise TypeError("LinearOperator subclass should implement"
                                 " at least one of _matvec and _matmat.")
 
-            obj.__init__(*args, **kwargs)
             return obj
 
     def __init__(self, dtype, shape):


Test patch:
diff --git a/scipy/sparse/linalg/tests/test_interface.py b/scipy/sparse/linalg/tests/test_interface.py
--- a/scipy/sparse/linalg/tests/test_interface.py
+++ b/scipy/sparse/linalg/tests/test_interface.py
@@ -284,6 +284,20 @@ def always_four_ones(x):
         assert_(hasattr(op, "shape"))
         assert_(hasattr(op, "_matvec"))
 
+def matvec(x):
+    """ Needed for test_pickle as local functions are not pickleable """
+    return np.zeros(3)
+
+def test_pickle():
+    import pickle
+
+    for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
+        A = interface.LinearOperator((3, 3), matvec)
+        s = pickle.dumps(A, protocol=protocol)
+        B = pickle.loads(s)
+
+        for k in A.__dict__:
+            assert_equal(getattr(A, k), getattr(B, k))
 
 def test_inheritance():
     class Empty(interface.LinearOperator):
Repository: scipy/scipy

Issue:
optimize.basinhopping - variable referenced before assignment.
It might be a bit silly to call `basinhopping` with `niter=0`, but if you do then there's a variable referenced before assignment.

```
import numpy as np
func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x
from scipy.optimize import basinhopping
x0=[1.]
minimizer_kwargs = {"method": "BFGS"}
ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs, niter=0)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/anz/miniconda3/envs/dev3/lib/python3.4/site-packages/scipy/optimize/_basinhopping.py", line 642, in basinhopping
  res.nit = i + 1
UnboundLocalError: local variable 'i' referenced before assignment
```



Discussion:

Resolving patch:
diff --git a/scipy/optimize/_basinhopping.py b/scipy/optimize/_basinhopping.py
--- a/scipy/optimize/_basinhopping.py
+++ b/scipy/optimize/_basinhopping.py
@@ -611,7 +611,7 @@ def basinhopping(func, x0, niter=100, T=1.0, stepsize=0.5,
                             accept_tests, disp=disp)
 
     # start main iteration loop
-    count = 0
+    count, i = 0, 0
     message = ["requested number of basinhopping iterations completed"
                " successfully"]
     for i in range(niter):


Test patch:
diff --git a/scipy/optimize/tests/test__basinhopping.py b/scipy/optimize/tests/test__basinhopping.py
--- a/scipy/optimize/tests/test__basinhopping.py
+++ b/scipy/optimize/tests/test__basinhopping.py
@@ -290,6 +290,12 @@ def test_minimizer_fail(self):
         # iterations + 1
         assert_equal(res.nit + 1, res.minimization_failures)
 
+    def test_niter_zero(self):
+        # gh5915, what happens if you call basinhopping with niter=0
+        i = 0
+        res = basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs,
+                           niter=0, disp=self.disp)
+
 
 class Test_Storage(TestCase):
     def setUp(self):
Repository: scipy/scipy

Issue:
"master" fails to build with MKL
Recently, when I try to build the "master" branch, I keep getting this error from `linalg/solve/dsolve/setup.py`:

``` .Python
ValueError: list.remove(x): x not in list
```

The error traces to this block of code <a href="https://github.com/scipy/scipy/blob/master/scipy/sparse/linalg/dsolve/setup.py#L30-L32">here</a>, for it seems that the `lsame.c` file does not exist in the list of sources.  Sure enough, when I remove this check, `scipy` builds successfully and tests pass.

I don't know what happened recently that caused this setup to break (it has never happened before until now), but is anyone else getting this issue?

Setup: Python 3.5.1, Windows 7, `numpy` 1.10.4, MKL



Discussion:

Resolving patch:
diff --git a/scipy/sparse/linalg/dsolve/setup.py b/scipy/sparse/linalg/dsolve/setup.py
--- a/scipy/sparse/linalg/dsolve/setup.py
+++ b/scipy/sparse/linalg/dsolve/setup.py
@@ -27,9 +27,6 @@ def configuration(parent_package='',top_path=None):
 
     sources = list(glob.glob(join(superlu_src, '*.c')))
     headers = list(glob.glob(join(superlu_src, '*.h')))
-    if os.name == 'nt' and ('FPATH' in os.environ or 'MKLROOT' in os.environ):
-        # when using MSVC + MKL, lsame is already in MKL
-        sources.remove(join(superlu_src, 'lsame.c'))
 
     config.add_library('superlu_src',
                        sources=sources,


Test patch:
Repository: scipy/scipy

Issue:
unicode vs. string comparison in scipy.stats.binned_statistic_dd
I'm getting an error where `scipy.stats.binned_statistic_dd` isn't recognizing that the `statistic` parameter I'm passing is 'count' [when it does the string comparison](https://github.com/scipy/scipy/blob/master/scipy/stats/_binned_statistic.py#L469).

I'm assuming this has something to do with a `unicode` vs. `str` type issue --- I'm using python2.7 with `from __future__ import unicode_literals`.  Should this be changed to an equality comparison?  i.e.

```
if(statistic != 'count' and Vlen != Dlen):
```

instead of 

```
if(statistic is not 'count' and Vlen != Dlen):
```



Discussion:
My understanding is that you shouldn't use "is" but "==" for string
comparisons for this sort of thing, yeah.


Resolving patch:
diff --git a/scipy/stats/_binned_statistic.py b/scipy/stats/_binned_statistic.py
--- a/scipy/stats/_binned_statistic.py
+++ b/scipy/stats/_binned_statistic.py
@@ -466,7 +466,7 @@ def binned_statistic_dd(sample, values, statistic='mean',
     Vdim, Vlen = values.shape
 
     # Make sure `values` match `sample`
-    if(statistic is not 'count' and Vlen != Dlen):
+    if(statistic != 'count' and Vlen != Dlen):
         raise AttributeError('The number of `values` elements must match the '
                              'length of each `sample` dimension.')
 


Test patch:
diff --git a/scipy/stats/tests/test_binned_statistic.py b/scipy/stats/tests/test_binned_statistic.py
--- a/scipy/stats/tests/test_binned_statistic.py
+++ b/scipy/stats/tests/test_binned_statistic.py
@@ -30,6 +30,15 @@ def test_1d_count(self):
         assert_allclose(count1, count2)
         assert_allclose(edges1, edges2)
 
+    def test_gh5927(self):
+        # smoke test for gh5927 - binned_statistic was using `is` for string
+        # comparison
+        x = self.x
+        v = self.v
+        statistics = [u'mean', u'median', u'count', u'sum']
+        for statistic in statistics:
+            res = binned_statistic(x, v, statistic, bins=10)
+
     def test_1d_result_attributes(self):
         x = self.x
         v = self.v