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

Issue:
griddata docstring doesn't make any sense
The docstring for `griddata` refers to many different integers:

`D`, `n`, `ndim`, `M`:

```
Interpolate unstructured D-dimensional data.

Parameters
----------
points : ndarray of floats, shape (n, D)
    Data point coordinates. Can either be an array of
    shape (n, D), or a tuple of `ndim` arrays.
values : ndarray of float or complex, shape (n,)
    Data values.
xi : ndarray of float, shape (M, D)
    Points at which to interpolate data.
```

The only one that is defined is `D`, so users have no idea what the others are.

Furthermore the example provided contradicts the docstring as xi is passed as a tuple but the docstring says it must be a ndarray.



Discussion:
The integers are defined by the shapes of the input arrays.

The `xi` description needs to be extended though, looks like it can be both 2-D ndarray or tuple of 1-D arrays.

I wish to work on this . Will be sending the PR.


Resolving patch:
diff --git a/scipy/interpolate/ndgriddata.py b/scipy/interpolate/ndgriddata.py
--- a/scipy/interpolate/ndgriddata.py
+++ b/scipy/interpolate/ndgriddata.py
@@ -97,7 +97,7 @@ def griddata(points, values, xi, method='linear', fill_value=np.nan,
         shape (n, D), or a tuple of `ndim` arrays.
     values : ndarray of float or complex, shape (n,)
         Data values.
-    xi : ndarray of float, shape (M, D)
+    xi : 2-D ndarray of float or tuple of 1-D array, shape (M, D)
         Points at which to interpolate data.
     method : {'linear', 'nearest', 'cubic'}, optional
         Method of interpolation. One of


Test patch:
Repository: scipy/scipy

Issue:
Docs for find_peaks_cwt are incorrect
Docs for scipy.signal.find_peaks_cwt state that the default for `gap_thresh` is 2, but the code says (https://github.com/scipy/scipy/blob/master/scipy/signal/_peak_finding.py#L509)

```
if gap_thresh is None:
    gap_thresh = np.ceil(widths[0]) 
```
Thanks


Discussion:
@rgommers I wish to work on the issue. We have to update the docstring for `gap_thresh`, correct?
Since, this issue remains to be unsolved , I wish to claim this issue.

Resolving patch:
diff --git a/scipy/signal/_peak_finding.py b/scipy/signal/_peak_finding.py
--- a/scipy/signal/_peak_finding.py
+++ b/scipy/signal/_peak_finding.py
@@ -448,7 +448,7 @@ def find_peaks_cwt(vector, widths, wavelet=None, max_distances=None,
         If a relative maximum is not found within `max_distances`,
         there will be a gap. A ridge line is discontinued if there are more
         than `gap_thresh` points without connecting a new relative maximum.
-        Default is 2.
+        Default is the first value of the widths array i.e. widths[0].
     min_length : int, optional
         Minimum length a ridge line needs to be acceptable.
         Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths.


Test patch:
Repository: scipy/scipy

Issue:
scipy.optimize.fsolve Jacobian argument incomplete in the documentation
This seems to be a minor documentation bug & an easy fix

The scipy.optimize.fsolve accepts a jacobian in the fprime argument


`scipy.optimize.fsolve(func, x0, args=(), fprime=None, full_output=0, col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, epsfcn=None, factor=100, diag=None)
`

fprime is defined as

`   fprime : callable(x), optional
        A function to compute the Jacobian of `func` with derivatives
        across the rows. By default, the Jacobian will be estimated.
`

I believe it should really be

`   fprime : callable(x, *args), optional
        A function to compute the Jacobian of `func` with derivatives
        across the rows. By default, the Jacobian will be estimated.
`

The args from fsolve are passed down to the jacobian. This can be confirmed from the code in scipy/optimize/minpack.py, _root_hybr (code snippet below - the last line is where there is check to see if the jacobian accepts x0 & args)


`   Dfun = jac

    if Dfun is None:

        if band is None:

            ml, mu = -10, -10

        else:

            ml, mu = band[:2]

        if maxfev == 0:

            maxfev = 200 * (n + 1)

        retval = _minpack._hybrd(func, x0, args, 1, xtol, maxfev,
                                 ml, mu, epsfcn, factor, diag)

    else:

        _check_func('fsolve', 'fprime', Dfun, x0, args, n, (n, n))
`


Discussion:

Resolving patch:
diff --git a/scipy/optimize/minpack.py b/scipy/optimize/minpack.py
--- a/scipy/optimize/minpack.py
+++ b/scipy/optimize/minpack.py
@@ -62,7 +62,7 @@ def fsolve(func, x0, args=(), fprime=None, full_output=0,
         The starting estimate for the roots of ``func(x) = 0``.
     args : tuple, optional
         Any extra arguments to `func`.
-    fprime : callable(x), optional
+    fprime : callable ``f(x, *args)``, optional
         A function to compute the Jacobian of `func` with derivatives
         across the rows. By default, the Jacobian will be estimated.
     full_output : bool, optional


Test patch:
Repository: scipy/scipy

Issue:
Jaccard distance both zero vectors behaviour
As far as I know, Jaccard distance between two zero boolean vectors should be equal to zero. 

However now implementation returns ```nan``` as a result.

Example code:
```python
import numpy as np
from scipy.spatial.distance import jaccard

a = np.zeros(5)
print jaccard(a, a)
```

This gives result and the warning:
```
RuntimeWarning: invalid value encountered in double_scalars  / 
np.double(np.bitwise_or(u != 0, v != 0).sum()))
nan
```

Maybe returning a zero would be a more acceptable option?
Python 2.7.12
Scipy version 0.18.1


Discussion:

Resolving patch:
diff --git a/scipy/spatial/distance.py b/scipy/spatial/distance.py
--- a/scipy/spatial/distance.py
+++ b/scipy/spatial/distance.py
@@ -829,6 +829,18 @@ def jaccard(u, v, w=None):
     jaccard : double
         The Jaccard distance between vectors `u` and `v`.
 
+    Notes
+    -----
+    When both `u` and `v` lead to a `0/0` division i.e. there is no overlap
+    between the items in the vectors the returned distance is 0. See the
+    Wikipedia page on the Jaccard index [1]_, and this paper [2]_.
+
+    References
+    ----------
+    .. [1] https://en.wikipedia.org/wiki/Jaccard_index
+    .. [2] S. Kosub, "A note on the triangle inequality for the Jaccard
+       distance", 2016, Available online: https://arxiv.org/pdf/1612.02696.pdf
+
     Examples
     --------
     >>> from scipy.spatial import distance
@@ -844,14 +856,16 @@ def jaccard(u, v, w=None):
     """
     u = _validate_vector(u)
     v = _validate_vector(v)
+
     nonzero = np.bitwise_or(u != 0, v != 0)
     unequal_nonzero = np.bitwise_and((u != v), nonzero)
     if w is not None:
         w = _validate_weights(w)
         nonzero = w * nonzero
         unequal_nonzero = w * unequal_nonzero
-    dist = np.double(unequal_nonzero.sum()) / np.double(nonzero.sum())
-    return dist
+    a = np.double(unequal_nonzero.sum())
+    b = np.double(nonzero.sum())
+    return (a / b) if b != 0 else 0
 
 
 def kulsinski(u, v, w=None):


Test patch:
diff --git a/scipy/spatial/tests/test_distance.py b/scipy/spatial/tests/test_distance.py
--- a/scipy/spatial/tests/test_distance.py
+++ b/scipy/spatial/tests/test_distance.py
@@ -1106,6 +1106,11 @@ def test_pdist_djaccard_random_float32(self):
         Y_test1 = wpdist(X, 'jaccard')
         _assert_within_tol(Y_test1, Y_right, eps)
 
+    def test_pdist_djaccard_allzeros(self):
+        eps = 1e-08
+        Y = pdist(np.zeros((5, 3)), 'jaccard')
+        _assert_within_tol(np.zeros(10), Y, eps)
+
     def test_pdist_djaccard_random_nonC(self):
         eps = 1e-08
         X = np.float64(eo['pdist-boolean-inp'])
@@ -1113,6 +1118,11 @@ def test_pdist_djaccard_random_nonC(self):
         Y_test2 = wpdist(X, 'test_jaccard')
         _assert_within_tol(Y_test2, Y_right, eps)
 
+    def test_pdist_djaccard_allzeros_nonC(self):
+        eps = 1e-08
+        Y = pdist(np.zeros((5, 3)), 'test_jaccard')
+        _assert_within_tol(np.zeros(10), Y, eps)
+
     def test_pdist_chebyshev_random(self):
         eps = 1e-08
         X = eo['pdist-double-inp']
Repository: scipy/scipy

Issue:
If a mutable (like a numpy array) is passed as window to resample_poly, it is modified
When passing a pre-computed FIR filter in a numpy array to resample_poly, it is multiplied by `up`.  This scaling happens in-place, and is very undesired behaviour if the same filter is supposed to be used again (which is very likely).

Proposed fix: in line 2368 (or thereabouts) of signaltools.py change `h = window` to `h = array(window)`, ensuring `h` is a copy of `window`.

### Reproducing code example:
```
import numpy
from scipy.signal import resample_poly

impulse = numpy.array([0, 0, 0, 0, 1.0, 0, 0, 0, 0 ])
fake_LPF = numpy.array([.1, .2, .3, .4, .5, .4, .3, .2, .1])

out = resample_poly(impulse, 5, 3, window=fake_LPF)
print(fake_LPF)
```
### Error message:

### Scipy/Numpy/Python version information:
```
0.19.0 1.12.1 sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)
```




Discussion:
@jthiem, thanks for reporting the problem.  I can confirm that the problem still exists in the master branch.
Ping @e-q, @Eric89GXL: can either of you take a look?
I can take a look in the next few days.

Resolving patch:
diff --git a/scipy/signal/signaltools.py b/scipy/signal/signaltools.py
--- a/scipy/signal/signaltools.py
+++ b/scipy/signal/signaltools.py
@@ -2361,7 +2361,7 @@ def resample_poly(x, up, down, axis=0, window=('kaiser', 5.0)):
     n_out = n_out // down + bool(n_out % down)
 
     if isinstance(window, (list, np.ndarray)):
-        window = asarray(window)
+        window = array(window)  # use array to force a copy (we modify it)
         if window.ndim > 1:
             raise ValueError('window must be 1-D')
         half_len = (window.size - 1) // 2


Test patch:
diff --git a/scipy/signal/tests/test_signaltools.py b/scipy/signal/tests/test_signaltools.py
--- a/scipy/signal/tests/test_signaltools.py
+++ b/scipy/signal/tests/test_signaltools.py
@@ -567,6 +567,14 @@ def test_polyphase_extfilter(self):
         # Test external specification of downsampling filter
         self._test_data(method='polyphase', ext=True)
 
+    def test_mutable_window(self):
+        # Test that a mutable window is not modified
+        impulse = np.zeros(3)
+        window = np.random.RandomState(0).randn(2)
+        window_orig = window.copy()
+        signal.resample_poly(impulse, 5, 1, window=window)
+        assert_array_equal(window, window_orig)
+
     def _test_data(self, method, ext=False):
         # Test resampling of sinusoids and random noise (1-sec)
         rate = 100
Repository: scipy/scipy

Issue:
Mistake in the documentation of `ndimage.distance_transform_bf`.
This was reported on stackoverflow: http://stackoverflow.com/questions/43737790/ndimage-distance-transform-bf-transforms-the-wrong-elements

The docstring for `distance_transform_bf` says

    This function calculates the distance transform of the `input`, by
    replacing each background element (zero values), with its
    shortest distance to the foreground (any element non-zero).

In fact, it replaces foreground elements with the distance to the nearest background element.  That is the behavior that is checked in the unit tests.

Here's another example:

```
In [113]: a = np.zeros((6, 6))

In [114]: a[1:-1,1:-1] = 9

In [115]: a
Out[115]: 
array([[ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  9.,  9.,  9.,  9.,  0.],
       [ 0.,  9.,  9.,  9.,  9.,  0.],
       [ 0.,  9.,  9.,  9.,  9.,  0.],
       [ 0.,  9.,  9.,  9.,  9.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])

In [116]: distance_transform_bf(a)
Out[116]: 
array([[ 0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  1.,  0.],
       [ 0.,  1.,  2.,  2.,  1.,  0.],
       [ 0.,  1.,  2.,  2.,  1.,  0.],
       [ 0.,  1.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.]])
```
Clearly it is the nonzero values that are being replaced with the shortest distance to a zero value.


Discussion:

Resolving patch:
diff --git a/scipy/ndimage/morphology.py b/scipy/ndimage/morphology.py
--- a/scipy/ndimage/morphology.py
+++ b/scipy/ndimage/morphology.py
@@ -1758,8 +1758,8 @@ def distance_transform_bf(input, metric="euclidean", sampling=None,
     Distance transform function by a brute force algorithm.
 
     This function calculates the distance transform of the `input`, by
-    replacing each background element (zero values), with its
-    shortest distance to the foreground (any element non-zero).
+    replacing each foreground (non-zero) element, with its
+    shortest distance to the background (any zero-valued element).
 
     In addition to the distance transform, the feature transform can
     be calculated. In this case the index of the closest background


Test patch:
Repository: scipy/scipy

Issue:
Documentation error: script.stats.skew
In the following quote from the documentation for script.stats.skew, shouldn't the inequality sign be the flipped the other way around?

"A skewness value > 0 means that there is more weight in the left tail of the distribution."

Webpage:  https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.skew.html

SciPy v0.14.0


Discussion:
Yes the sign or the side of the tail is flipped

also there should be a qualifier "for unimodal continuous distribution"
The statement is not true in general.

https://en.wikipedia.org/wiki/Skewness


From wikipedia: "positive skew: The right tail is longer; the **mass of the distribution is concentrated on the left of the figure**" 
I think this is synonymous to "skewness value > 0 means that there is more weight in the left tail of the distribution"

Resolving patch:
diff --git a/scipy/stats/stats.py b/scipy/stats/stats.py
--- a/scipy/stats/stats.py
+++ b/scipy/stats/stats.py
@@ -1010,10 +1010,11 @@ def skew(a, axis=0, bias=True, nan_policy='propagate'):
     """
     Compute the skewness of a data set.
 
-    For normally distributed data, the skewness should be about 0. A skewness
-    value > 0 means that there is more weight in the left tail of the
-    distribution. The function `skewtest` can be used to determine if the
-    skewness value is close enough to 0, statistically speaking.
+    For normally distributed data, the skewness should be about 0. For
+    unimodal continuous distributions, a skewness value > 0 means that
+    there is more weight in the right tail of the distribution. The
+    function `skewtest` can be used to determine if the skewness value
+    is close enough to 0, statistically speaking.
 
     Parameters
     ----------


Test patch:
Repository: scipy/scipy

Issue:
Fix for basinhopping unnecessary overflow warning
I am experiencing the following warning:
\scipy\optimize\_basinhopping.py:299: RuntimeWarning: overflow encountered in exp
`  w = min(1.0, np.exp(-(energy_new - energy_old) * self.beta))`

The warning is a bit annoying an unnecessary. I don't have an example to reproduce the warning, but the solution is simple. The statement effectively ensures that you only take the exp of a positive number. So, just use the following mathematically equivalent statement:
`w = np.exp(min(0, -(energy_new - energy_old) * self.beta))`

I am using scipy version 0.19.0




Discussion:
That seems reasonable to me. Could you prepare a PR for the change, with tests?
I'm afraid my experience with git, testing and version to control is too limited to prepare a PR. At the moment, I cannot do more that submitting a bug or fix now and then.
I'll do this.

Resolving patch:
diff --git a/scipy/optimize/_basinhopping.py b/scipy/optimize/_basinhopping.py
--- a/scipy/optimize/_basinhopping.py
+++ b/scipy/optimize/_basinhopping.py
@@ -296,7 +296,7 @@ def __init__(self, T, random_state=None):
         self.random_state = check_random_state(random_state)
 
     def accept_reject(self, energy_new, energy_old):
-        w = min(1.0, np.exp(-(energy_new - energy_old) * self.beta))
+        w = np.exp(min(0, -(energy_new - energy_old) * self.beta))
         rand = self.random_state.rand()
         return w >= rand
 


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
@@ -390,6 +390,13 @@ def test_accept(self):
         assert_(one_accept)
         assert_(one_reject)
 
+    def test_GH7495(self):
+        # an overflow in exp was producing a RuntimeWarning
+        # create own object here in case someone changes self.T
+        met = Metropolis(2)
+        with np.errstate(over='raise'):
+            met.accept_reject(0, 2000)
+
 
 class Test_AdaptiveStepsize(TestCase):
     def setUp(self):
Repository: scipy/scipy

Issue:
How can I call lapack routine dstev from scipy
In Scipy, I can directly access lapack routines, like `zheev`, with `scipy.linalg.lapack.zheev`. But it seems not working with some lapack routines like [dstev](http://www.netlib.org/lapack/explore-html/d7/d48/dstev_8f.html), which is used to diagonalize real, symmetric tridiagonal matrix.

Any comment is appreciated.



Discussion:
The short answer is that if it's not there, you can't. Before someone
contributes the f2py wrapper code to Scipy.

Thanks, but would it be a good idea to expose all driver routines in lapack to `scipy.linalg.lapack`?

Yes. But as long as Scipy's annual budget is $0, it will depend on someone sending a PR for it.


Resolving patch:
diff --git a/scipy/linalg/lapack.py b/scipy/linalg/lapack.py
--- a/scipy/linalg/lapack.py
+++ b/scipy/linalg/lapack.py
@@ -382,6 +382,9 @@
    ssbevx
    dsbevx
 
+   sstev
+   dstev
+
    ssyev
    dsyev
 


Test patch:
Repository: scipy/scipy

Issue:
griddata docstring is missing the "Returns" section.
Like the title says, the docstring for `scipy.interpolate.griddata` doesn't have a "Returns" section.



Discussion:

Resolving patch:
diff --git a/scipy/interpolate/ndgriddata.py b/scipy/interpolate/ndgriddata.py
--- a/scipy/interpolate/ndgriddata.py
+++ b/scipy/interpolate/ndgriddata.py
@@ -132,6 +132,11 @@ def griddata(points, values, xi, method='linear', fill_value=np.nan,
         incommensurable units and differ by many orders of magnitude.
 
         .. versionadded:: 0.14.0
+        
+    Returns
+    -------
+    ndarray
+        Array of interpolated values.
 
     Notes
     -----


Test patch:
Repository: scipy/scipy

Issue:
scipy.io.savemat throws error when dict key is unicode
scipy.io.savemat throws error (from numpy) when dict key is unicode
Error only shows up with an embedded dict

### Reproducing code example:
import scipy.io as sio
test_dict = {u'a':{u'b':1}} 
sio.savemat('dat_name.mat', test_dict)

### Error message:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/scipy/io/matlab/mio.py", line 211, in savemat
    MW.put_variables(mdict)
  File "/usr/local/lib/python2.7/dist-packages/scipy/io/matlab/mio5.py", line 847, in put_variables
    self._matrix_writer.write_top(var, asbytes(name), is_global)
  File "/usr/local/lib/python2.7/dist-packages/scipy/io/matlab/mio5.py", line 588, in write_top
    self.write(arr)
  File "/usr/local/lib/python2.7/dist-packages/scipy/io/matlab/mio5.py", line 606, in write
    narr = to_writeable(arr)
  File "/usr/local/lib/python2.7/dist-packages/scipy/io/matlab/mio5.py", line 444, in to_writeable
    return np.array([tuple(values)], dtype)
TypeError: data type not understood

### Scipy/Numpy/Python version information:
('0.19.1', '1.11.0', sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0))







Discussion:
Is it related to your typo? If I correct the variable name I don't get any problems.
The problem is still there when I fixed the typo. I believe the error is coming from numpy (I'm using version 1.11.0)


It is possible, I'm using 1.13.1
The problem can be fixed by change line 440 in scipy/io/matlab/mio5.py from 
dtype.append((field, object)) to dtype.append((str(field), object))  


Resolving patch:
diff --git a/scipy/io/matlab/mio5.py b/scipy/io/matlab/mio5.py
--- a/scipy/io/matlab/mio5.py
+++ b/scipy/io/matlab/mio5.py
@@ -437,7 +437,7 @@ def to_writeable(source):
         for field, value in source.items():
             if (isinstance(field, string_types) and
                     field[0] not in '_0123456789'):
-                dtype.append((field, object))
+                dtype.append((str(field), object))
                 values.append(value)
         if dtype:
             return np.array([tuple(values)], dtype)


Test patch:
diff --git a/scipy/io/matlab/tests/test_mio.py b/scipy/io/matlab/tests/test_mio.py
--- a/scipy/io/matlab/tests/test_mio.py
+++ b/scipy/io/matlab/tests/test_mio.py
@@ -1229,3 +1229,8 @@ def test_bad_utf8():
     assert_equal(res['bad_string'],
                  b'\x80 am broken'.decode('utf8', 'replace'))
 
+
+def test_save_unicode_field(tmpdir):
+    filename = os.path.join(str(tmpdir), 'test.mat')
+    test_dict = {u'a':{u'b':1,u'c':'test_str'}}
+    savemat(filename, test_dict)
Repository: scipy/scipy

Issue:
Bump minimum Cython version to 0.25?
I believe the current minimum required version is 0.23.4:

https://github.com/scipy/scipy/blob/ab5ef39601b17b204f32c787644bb516350b1a76/pyproject.toml#L5

The current version is 0.27. My primary interest in bumping to 0.25 is that it fixes a complex division bug:

https://github.com/cython/cython/blob/master/CHANGES.rst#significant-bugs-fixed

which we have an ugly workaround for in `special`. (Implementing Smith's algorithm ourselves.)


Discussion:
Sounds fine to me.

Resolving patch:
diff --git a/tools/cythonize.py b/tools/cythonize.py
--- a/tools/cythonize.py
+++ b/tools/cythonize.py
@@ -38,6 +38,7 @@
 import hashlib
 import subprocess
 from multiprocessing.dummy import Pool, Lock
+from os.path import dirname, join
 
 HASH_FILE = 'cythonize.dat'
 DEFAULT_ROOT = 'scipy'
@@ -55,8 +56,25 @@ def process_pyx(fromfile, tofile, cwd):
     try:
         from Cython.Compiler.Version import version as cython_version
         from distutils.version import LooseVersion
-        if LooseVersion(cython_version) < LooseVersion('0.23.4'):
-            raise Exception('Building SciPy requires Cython >= 0.23.4')
+
+        # Try to find pyproject.toml
+        pyproject_toml = join(dirname(__file__), '..', 'pyproject.toml')
+        if not os.path.exists(pyproject_toml):
+            raise ImportError()
+
+        # Try to find the minimum version from pyproject.toml
+        with open(pyproject_toml) as pt:
+            for line in pt:
+                if "cython" not in line.lower():
+                    continue
+                _, line = line.split('=')
+                required_version, _ = line.split('"')
+                break
+            else:
+                raise ImportError()
+
+        if LooseVersion(cython_version) < LooseVersion(required_version):
+            raise Exception('Building SciPy requires Cython >= ' + required_version)
 
     except ImportError:
         pass


Test patch: