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

Issue:
scipy.optimize.fminbound, numpy depreciation warning Creating an ndarray from ragged nested sequences
When using the function `scipy.optimize.fminbound`, I get the following warning:
```
Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray
```

I tracked down the message to this line:
https://github.com/scipy/scipy/blob/28d4244b6f5c1543755e586f27f9261d0f84153b/scipy/optimize/optimize.py#L1976

It seems that `np.maximum` should be used instead of `np.max` here anyway !


A minimal example:
```
from scipy import optimize
import numpy as np
optimize.fminbound(lambda x: np.array([x**2]), -np.pi, np.pi, disp=False)
```

Versions:
`scipy: 1.5.0   numpy: 1.19.1   sys: sys.version_info(major=3, minor=6, micro=10, releaselevel='final', serial=0)`


Discussion:
Do you have a minimal working example that demonstrates the issue? Otherwise it's difficult to provide a fix.
Yep, I've edited the issue

Resolving patch:
diff --git a/scipy/optimize/optimize.py b/scipy/optimize/optimize.py
--- a/scipy/optimize/optimize.py
+++ b/scipy/optimize/optimize.py
@@ -1973,7 +1973,7 @@ def _minimize_scalar_bounded(func, bounds, args=(),
             step = '       golden'
 
         si = np.sign(rat) + (rat == 0)
-        x = xf + si * np.max([np.abs(rat), tol1])
+        x = xf + si * np.maximum(np.abs(rat), tol1)
         fu = func(x, *args)
         num += 1
         fmin_data = (num, x, fu)


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
@@ -12,8 +12,8 @@
 import itertools
 import numpy as np
 from numpy.testing import (assert_allclose, assert_equal,
-                           assert_,
-                           assert_almost_equal, assert_warns,
+                           assert_, assert_almost_equal,
+                           assert_no_warnings, assert_warns,
                            assert_array_less, suppress_warnings)
 import pytest
 from pytest import raises as assert_raises
@@ -2170,3 +2170,9 @@ def test_memoize_jac_with_bfgs(function_with_gradient):
 
     scalar_function.fun(x0 + 0.2)
     assert function_with_gradient.number_of_calls == 3
+
+def test_gh12696():
+    # Test that optimize doesn't throw warning gh-12696
+    with assert_no_warnings():
+        optimize.fminbound(
+            lambda x: np.array([x**2]), -np.pi, np.pi, disp=False)
Repository: scipy/scipy

Issue:
optimize.root(method="krylov") fails if options["tol_norm"] expects an ndarray like x0
If `optimize.root(method="krylov")` is passed a custom `options["tol_norm"]` that doesn't handle a single float, it fails with various exceptions depending on the custom norm.  This is surprising as the norm might be thought to be defined on `numpy.ndarray` of the same shape as `x0`.

#### Reproducing code example:
```python
import numpy as np
from scipy.optimize import root


def norm(x: np.ndarray) -> float:
    return abs(x[0])


print(root(np.zeros_like, np.zeros(2), method="krylov"))
print(root(np.zeros_like, np.zeros(2), method="krylov", options={"tol_norm": norm}))
```

#### Error message:

```
Traceback (most recent call last):
  File "mwe.py", line 10, in <module>
    print(root(np.zeros_like, np.zeros(2), method="krylov", options={"tol_norm": norm}))
  File "/home/gmcbain/src/scipy/scipy/optimize/_root.py", line 194, in root
    sol = _root_nonlin_solve(fun, x0, args=args, jac=jac,
  File "/home/gmcbain/src/scipy/scipy/optimize/_root.py", line 292, in _root_nonlin_solve
    x, info = nonlin.nonlin_solve(f, x0, jacobian=jacobian(**jac_options),
  File "/home/gmcbain/src/scipy/scipy/optimize/nonlin.py", line 303, in nonlin_solve
    status = condition.check(Fx, x, dx)
  File "/home/gmcbain/src/scipy/scipy/optimize/nonlin.py", line 456, in check
    dx_norm = self.norm(dx)
  File "mwe.py", line 6, in norm
    return abs(x[0])
TypeError: 'float' object is not subscriptable
```

#### Scipy/Numpy/Python version information:

```
1.5.2 1.19.1 sys.version_info(major=3, minor=8, micro=5, releaselevel='final', serial=0)
```


Discussion:

Resolving patch:
diff --git a/scipy/optimize/nonlin.py b/scipy/optimize/nonlin.py
--- a/scipy/optimize/nonlin.py
+++ b/scipy/optimize/nonlin.py
@@ -272,7 +272,7 @@ def nonlin_solve(F, x0, jacobian='krylov', iter=None, verbose=False,
     func = lambda z: _as_inexact(F(_array_like(z, x0))).flatten()
     x = x0.flatten()
 
-    dx = np.inf
+    dx = np.full_like(x, np.inf)
     Fx = func(x)
     Fx_norm = norm(Fx)
 


Test patch:
diff --git a/scipy/optimize/tests/test__root.py b/scipy/optimize/tests/test__root.py
--- a/scipy/optimize/tests/test__root.py
+++ b/scipy/optimize/tests/test__root.py
@@ -38,6 +38,22 @@ def dfunc(z):
             assert_(abs(func(sol1.x)).max() < abs(func(sol2.x)).max(),
                     msg)
 
+    def test_tol_norm(self):
+
+        def norm(x):
+            return abs(x[0])
+
+        for method in ['excitingmixing',
+                       'diagbroyden',
+                       'linearmixing',
+                       'anderson',
+                       'broyden1',
+                       'broyden2',
+                       'krylov']:
+
+            root(np.zeros_like, np.zeros(2), method=method,
+                options={"tol_norm": norm})
+
     def test_minimize_scalar_coerce_args_param(self):
         # github issue #3503
         def func(z, f=1):
Repository: scipy/scipy

Issue:
Broken link in doc for signal.max_len_seq
<!-- 
Thank you for taking the time to file a bug report. 
Please fill in the fields below, deleting the sections that 
don't apply to your issue. You can view the final output
by clicking the preview button above.
Note: This is a comment, and won't appear in the output.
-->

My issue is about ...
documentation for scipy.signal.max_len_seq()

In this document: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.max_len_seq.html?highlight=correlation
This link is broken:
http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm

#### Reproducing code example:
<!-- 
If you place your code between the triple backticks below, 
it will be rendered as a code block. 
-->

```
Sample code to reproduce the problem
```

#### Error message:
<!-- If any, paste the *full* error message inside a code block
as above (starting from line Traceback)
-->

```
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ...
```

#### Scipy/Numpy/Python version information:
<!-- You can simply run the following and paste the result in a code block
```
import sys, scipy, numpy; print(scipy.__version__, numpy.__version__, sys.version_info)
```
-->


Discussion:
I guess http://in.ncu.edu.tw/ncume_ee/digilogi/prbs.htm#Table%20of%20M-Sequence%20Feedback%20Taps would be a suitable replacement, but it doesn't look particularly permanent. Maybe we should copy the values into the code somewhere...
How about a Wayback machine link, https://web.archive.org/web/20181001062252/http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm ?  It looks like they've also archived the data files.

Resolving patch:
diff --git a/scipy/signal/_max_len_seq.py b/scipy/signal/_max_len_seq.py
--- a/scipy/signal/_max_len_seq.py
+++ b/scipy/signal/_max_len_seq.py
@@ -58,7 +58,7 @@ def max_len_seq(nbits, state=None, length=None, taps=None):
     The default values for taps are specifically taken from the first
     option listed for each value of ``nbits`` in:
 
-        http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm
+        https://web.archive.org/web/20181001062252/http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm
 
     .. versionadded:: 0.15.0
 


Test patch:
Repository: scipy/scipy

Issue:
Vector-valued interpolation in `interp2d`
**Is your feature request related to a problem? Please describe.**
There should be an easy way to interpolate non-scalar data on a 2D grid. Given e.g. `x.shape == y.shape == (36, 48)` and `z.shape == (36, 48, 11)`, there should be a straight-forward way to interpolate this to get an interpolated vector-valued function. This exists for `interp1d`, so why not for `interp2d`?

**Describe the solution you'd like**
One intuitive approach from the user perspective would be an `axes` keyword, which specifies which axes will be used to interpolate along, such that:

    f = interp2d(x, y, z, axes=(0, 1))
    f(0.253, 0.447).shape == (11,)  # True

For `interp2d` axes would of course (usually) be a length-2 tuple. Also, this should not be limited to vector/1D function data, but arbitrary dimensionality, i.e. `z` could also have shape `(36, 48, 11, 31)`, then the `interp2d` interpolation output should have shape `(11, 31)`.

As the input can also be flattened, `axes` essentially tells you along which axes you will find the data to be flattened/interpolated (could also be longer than *n*). For an already-flattened input (`x.shape == y.shape == (1728,)` and `z.shape == (1728,11)`) the equivalent call signature would of course be `axes=(0,)`

**Describe alternatives you've considered**
Use `interpn` instead


Discussion:
interpn:

>>> x = np.linspace(0, 2, 5)
>>> y = np.linspace(0, 2, 7)
>>> z =
np.random.randn(5, 7, 3)
>>> interpn((x, y), z, (1.0, 1.0))
array([[
0.41399926, -0.35760212,  0.5403803 ]])
>>> z[2,3]
array([ 0.41399926,
-0.35760212,  0.5403803 ])



> 
> interpn:

As you replied via e-mail you did not see the changes made before your reply - when writing this I was thinking of `interp2d` and assumed `interpn` was just an *n*-D version of it. I did realize that `interpn` behaves differently, and does things the way I want, but still `interp2d` cannot. Since `interp1d` and `interp2d` share basically the same behaviour/call signature and `interp1d` can interpolate along arbitrary axes, it would be expected that `interp2d` should also be able to. 



Resolving patch:
diff --git a/scipy/interpolate/interpolate.py b/scipy/interpolate/interpolate.py
--- a/scipy/interpolate/interpolate.py
+++ b/scipy/interpolate/interpolate.py
@@ -94,11 +94,14 @@ class interp2d(object):
     Interpolate over a 2-D grid.
 
     `x`, `y` and `z` are arrays of values used to approximate some function
-    f: ``z = f(x, y)``. This class returns a function whose call method uses
-    spline interpolation to find the value of new points.
+    f: ``z = f(x, y)`` which returns a scalar value `z`. This class returns a
+    function whose call method uses spline interpolation to find the value
+    of new points.
 
     If `x` and `y` represent a regular grid, consider using
-    RectBivariateSpline.
+    `RectBivariateSpline`.
+
+    If `z` is a vector value, consider using `interpn`.
 
     Note that calling `interp2d` with NaNs present in input values results in
     undefined behaviour.


Test patch:
Repository: scipy/scipy

Issue:
Documentation: in scipy.stats.johnsonsu, parameter `a` can be less than or equal to zero
The documentation for scipy.stats.johnsonsu (https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.johnsonsu.html) says that the parameter `a` must be greater than zero, but on looking at the formulas on the Wikipedia page (https://en.wikipedia.org/wiki/Johnson%27s_SU-distribution) and looking at the source code, it turns out that `a` can be less than or equal to zero. Values of `a` less than or equal to zero are allowed by the code, and don't cause run time errors.

The bug fix is just to change the documentation.

Inspired by this Stackoverflow question: https://stackoverflow.com/questions/65567759/why-doesnt-johnson-su-distribution-give-positive-skewness-in-scipy-stats/


Discussion:
The documentation say "for all x, a, b > 0, ...".  It is natural to interpret that as meaning x > 0 and a > 0, but that is not the intent.  I agree we should adjust the documentation to avoid that ambiguity.
[`johnsonsb`](http://scipy.github.io/devdocs/generated/scipy.stats.johnsonsb.html) has the same issue.  The documentation says "a, b > 0", but in fact, a < 0 is allowed.
I would have submitted a PR, but I'll leave this open, as it is indeed a good first issue. I'll have the email return to my inbox in case it hasn't been addressed by 1.7 release time.
About restating the description, I wonder if there is or should be a convention for stating the ranges of variables and parameters. E.g. "For all x in R, all a in R, and all b in R such that b > 0, ...". I don't know how other functions in Scipy are described. I leave it to someone else to sort it out. 

Resolving patch:
diff --git a/scipy/stats/_continuous_distns.py b/scipy/stats/_continuous_distns.py
--- a/scipy/stats/_continuous_distns.py
+++ b/scipy/stats/_continuous_distns.py
@@ -3975,8 +3975,9 @@ class johnsonsb_gen(rv_continuous):
 
         f(x, a, b) = \frac{b}{x(1-x)}  \phi(a + b \log \frac{x}{1-x} )
 
-    for :math:`0 <= x < =1` and :math:`a, b > 0`, and :math:`\phi` is the normal
-    pdf.
+    for all :math:`x \in \mathbb{R}, a \in \mathbb{R}`, and :math:`b \in
+    \mathbb{R}`, where :math:`0 \leq x \leq 1`, :math:`b > 0`,
+    and :math:`\phi` is the normal pdf.
 
     `johnsonsb` takes :math:`a` and :math:`b` as shape parameters.
 
@@ -4023,7 +4024,8 @@ class johnsonsu_gen(rv_continuous):
         f(x, a, b) = \frac{b}{\sqrt{x^2 + 1}}
                      \phi(a + b \log(x + \sqrt{x^2 + 1}))
 
-    for all :math:`x, a, b > 0`, and :math:`\phi` is the normal pdf.
+    for all :math:`(x, a, b) \in \mathbb{R}^3` where :math:`b > 0`,
+    and :math:`\phi` is the normal pdf.
 
     `johnsonsu` takes :math:`a` and :math:`b` as shape parameters.
 


Test patch:
Repository: scipy/scipy

Issue:
One-word typo in the documentation of optimize.linprog_simplex
Hello there,
I just observed this typo
https://github.com/scipy/scipy/blob/232092afebf7a59949dca5595aaac3446814293c/scipy/optimize/_linprog_doc.py#L1105
tabluea-based => tableau-based
I've contributed to tiny tiny changes in scipy a few years ago, but I'm not sure what's the best things to do for such tiny typos: do you want me to submit a pull request?
Thanks in advance. -- @Naereen


Discussion:
Please do! I'll merge it right away.
Thanks!
I know you guys are extra busy (the number of issues and PR here is quite scary), and I preferred to ask.
I also read all the documentation pages of `optimize.linprog` and various options/solvers, didn't find any other typo or things I could easily improve.

Resolving patch:
diff --git a/scipy/optimize/_linprog_doc.py b/scipy/optimize/_linprog_doc.py
--- a/scipy/optimize/_linprog_doc.py
+++ b/scipy/optimize/_linprog_doc.py
@@ -1102,7 +1102,7 @@ def _linprog_simplex_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
                          **unknown_options):
     r"""
     Linear programming: minimize a linear objective function subject to linear
-    equality and inequality constraints using the tabluea-based simplex method.
+    equality and inequality constraints using the tableau-based simplex method.
 
     Linear programming solves problems of the following form:
 


Test patch:
Repository: scipy/scipy

Issue:
`_within_tolerance` seems an unnecessary repetition of `numpy.isclose`
https://github.com/scipy/scipy/blob/417761e719dcb5cf3c9bb0a25f9f0f792cfb350a/scipy/optimize/zeros.py#L891-L895 

This function is essentially the same as [numpy.isclose](https://numpy.org/doc/stable/reference/generated/numpy.isclose.html) so I'm not sure why this is written separately here?


Discussion:

Resolving patch:
diff --git a/scipy/optimize/zeros.py b/scipy/optimize/zeros.py
--- a/scipy/optimize/zeros.py
+++ b/scipy/optimize/zeros.py
@@ -888,13 +888,6 @@ def brenth(f, a, b, args=(),
 #  See [1]
 
 
-def _within_tolerance(x, y, rtol, atol):
-    diff = np.abs(x - y)
-    z = np.abs(y)
-    result = (diff <= (atol + rtol * z))
-    return result
-
-
 def _notclose(fs, rtol=_rtol, atol=_xtol):
     # Ensure not None, not 0, all finite, and not very close to each other
     notclosefvals = (
@@ -1121,7 +1114,7 @@ def start(self, f, a, b, args=()):
     def get_status(self):
         """Determine the current status."""
         a, b = self.ab[:2]
-        if _within_tolerance(a, b, self.rtol, self.xtol):
+        if np.isclose(a, b, rtol=self.rtol, atol=self.xtol):
             return _ECONVERGED, sum(self.ab) / 2.0
         if self.iterations >= self.maxiter:
             return _ECONVERR, sum(self.ab) / 2.0


Test patch:
Repository: scipy/scipy

Issue:
ENH: Extend find_peaks_cwt to take numbers and iterables for widths argument.
Added regression test for iterable and tuple dtypes passed into the `width` argument of `find_peaks_cwt`.

Supersedes and closes gh-5304


Discussion:

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
@@ -1201,8 +1201,9 @@ def find_peaks_cwt(vector, widths, wavelet=None, max_distances=None,
     ----------
     vector : ndarray
         1-D array in which to find the peaks.
-    widths : sequence
-        1-D array of widths to use for calculating the CWT matrix. In general,
+    widths : float or sequence
+        Single width or 1-D array-like of widths to use for calculating
+        the CWT matrix. In general,
         this range should cover the expected width of peaks of interest.
     wavelet : callable, optional
         Should take two parameters and return a 1-D array to convolve
@@ -1279,7 +1280,7 @@ def find_peaks_cwt(vector, widths, wavelet=None, max_distances=None,
     ([32], array([ 1.6]), array([ 0.9995736]))
 
     """
-    widths = np.asarray(widths)
+    widths = np.array(widths, copy=False, ndmin=1)
 
     if gap_thresh is None:
         gap_thresh = np.ceil(widths[0])


Test patch:
diff --git a/scipy/signal/tests/test_peak_finding.py b/scipy/signal/tests/test_peak_finding.py
--- a/scipy/signal/tests/test_peak_finding.py
+++ b/scipy/signal/tests/test_peak_finding.py
@@ -845,3 +845,15 @@ def test_find_peaks_window_size(self):
         found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=3,
                                     min_length=None, window_size=20)
         assert found_locs.size == act_locs.size
+
+    def test_find_peaks_with_one_width(self):
+        """
+        Verify that the `width` argument
+        in `find_peaks_cwt` can be a float
+        """
+        xs = np.arange(0, np.pi, 0.05)
+        test_data = np.sin(xs)
+        widths = 1
+        found_locs = find_peaks_cwt(test_data, widths)
+
+        np.testing.assert_equal(found_locs, 32)
Repository: scipy/scipy

Issue:
Scipy cosine distance can be greater than 2
I am using the cosine distance as implemented in scipy.spatial.distance and while (mathematically) the value should always be between 0 and 2 this is not practically the case: 
Namely, with v= [-3.0e-05 -2.4e-05  0.0e+00] and w=[3.5e-05 2.8e-05 0.0e+00]  the returned value is: 2.0000000000000004 

I am not surprised that this is computationally possible, but I am surprised that the mathematical properties of the function are not enforced as this will cause other functions not to work, hence the bug request. Or maybe it is a feature request? :)

versions: scipy 1.6.0, numpy 1.19.4, python 3.8.5



Discussion:
Yes, we can just clamp the min/max values to ensure there's no exceeding the theoretical bounds.

Resolving patch:
diff --git a/scipy/spatial/distance.py b/scipy/spatial/distance.py
--- a/scipy/spatial/distance.py
+++ b/scipy/spatial/distance.py
@@ -772,7 +772,8 @@ def cosine(u, v, w=None):
     """
     # cosine distance is also referred to as 'uncentered correlation',
     #   or 'reflective correlation'
-    return correlation(u, v, w=w, centered=False)
+    # clamp the result to 0-2
+    return max(0, min(correlation(u, v, w=w, centered=False), 2.0))
 
 
 def hamming(u, v, w=None):


Test patch:
Repository: scipy/scipy

Issue:
delta0 argument of scipy.odr.ODR() ignored
In 1.6.1 1.20.1 sys.version_info(major=3, minor=9, micro=2, releaselevel='final', serial=0), the numpy.array passed as delta0 argument to scipy.odr.ODR() is ignored for set_job(del_init=1, restart=0).

This can be checked by using set_iprint(init=2) and looking at ODR's output for SUM OF SQUARED WEIGHTED DELTAS, which should not be zero for a non-zero delta0 array:

```
 --- INITIAL WEIGHTED SUM OF SQUARES        =                    1.57660852D-04
         SUM OF SQUARED WEIGHTED DELTAS     =   0.00000000D+00
         SUM OF SQUARED WEIGHTED EPSILONS   =   1.21660852D-04
```


Discussion:

Resolving patch:
diff --git a/scipy/odr/odrpack.py b/scipy/odr/odrpack.py
--- a/scipy/odr/odrpack.py
+++ b/scipy/odr/odrpack.py
@@ -1086,7 +1086,7 @@ def run(self):
                  'ndigit', 'taufac', 'sstol', 'partol', 'maxit', 'stpb',
                  'stpd', 'sclb', 'scld', 'work', 'iwork']
 
-        if self.delta0 is not None and self.job % 1000 // 10 == 1:
+        if self.delta0 is not None and (self.job // 10000) % 10 == 0:
             # delta0 provided and fit is not a restart
             self._gen_work()
 


Test patch:
Repository: scipy/scipy

Issue:
DOC: scipy.spatial.KDTree.query
In this paragraph, a tabular layout in the source is run together without punctuation in the generated docs:

> Which Minkowski p-norm to use. 1 is the sum-of-absolute-values “Manhattan” distance 2 is the usual Euclidean distance infinity is the maximum-coordinate-difference distance A large, finite p may cause a ValueError if overflow can occur. 


Discussion:

Resolving patch:
diff --git a/scipy/optimize/_minimize.py b/scipy/optimize/_minimize.py
--- a/scipy/optimize/_minimize.py
+++ b/scipy/optimize/_minimize.py
@@ -96,7 +96,8 @@ def minimize(fun, x0, args=(), method=None, jac=None, hess=None,
 
         where ``x`` is an array with shape (n,) and ``args`` is a tuple with
         the fixed parameters. If `jac` is a Boolean and is True, `fun` is
-        assumed to return and objective and gradient as an ``(f, g)`` tuple.
+        assumed to return a tuple ``(f, g)`` containing the objective
+        function and the gradient.
         Methods 'Newton-CG', 'trust-ncg', 'dogleg', 'trust-exact', and
         'trust-krylov' require that either a callable be supplied, or that
         `fun` return the objective and gradient.
diff --git a/scipy/spatial/kdtree.py b/scipy/spatial/kdtree.py
--- a/scipy/spatial/kdtree.py
+++ b/scipy/spatial/kdtree.py
@@ -354,9 +354,9 @@ def query(
             distance to the real kth nearest neighbor.
         p : float, 1<=p<=infinity, optional
             Which Minkowski p-norm to use.
-            1 is the sum-of-absolute-values "Manhattan" distance
-            2 is the usual Euclidean distance
-            infinity is the maximum-coordinate-difference distance
+            1 is the sum-of-absolute-values distance ("Manhattan" distance).
+            2 is the usual Euclidean distance.
+            infinity is the maximum-coordinate-difference distance.
             A large, finite p may cause a ValueError if overflow can occur.
         distance_upper_bound : nonnegative float, optional
             Return only neighbors within this distance. This is used to prune


Test patch: