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

Issue:
BUG: mesonpy embeds random path in .pyx files
### Describe your issue.

While working on [reproducible builds](https://reproducible-builds.org/) for [openSUSE](https://en.opensuse.org/openSUSE:Reproducible_Builds), I found that
our `python-scipy` 1.11.1 package varies between builds. One of the reasons is that a random mesonpy path gets embedded in `cython_special.pyx`, `_ufuncs_cxx.pyx` and `_ufuncs.pyx`

### Reproducing Code Example

```python
build it twice
```


### Error message

```shell
+++ /usr/lib64/python3.9/site-packages/scipy/special/cython_special.pyx     2023-07-27 00:00:00.000000000 +0000
@@ -1088,50 +1088,50 @@
 from ._agm cimport agm as _func_agm
 ctypedef double _proto_agm_t(double, double) noexcept nogil
 cdef _proto_agm_t *_proto_agm_t_var = &_func_agm
-cdef extern from r"/home/abuild/rpmbuild/BUILD/scipy-1.11.1/.mesonpy-nb_0k4ap/build/scipy/special/_ufuncs_defs.h":
+cdef extern from r"/home/abuild/rpmbuild/BUILD/scipy-1.11.1/.mesonpy-il1v1fcx/build/scipy/special/_ufuncs_defs.h":
     cdef npy_int _func_airy_wrap "airy_wrap"(npy_double, npy_double *, npy_double *, npy_double *, npy_double *)nogil
-cdef extern from r"/home/abuild/rpmbuild/BUILD/scipy-1.11.1/.mesonpy-nb_0k4ap/build/scipy/special/_ufuncs_defs.h":
+cdef extern from r"/home/abuild/rpmbuild/BUILD/scipy-1.11.1/.mesonpy-il1v1fcx/build/scipy/special/_ufuncs_defs.h":
```


### SciPy/NumPy/Python version and system information

```shell
1.11.1 1.25.2 3.11.4
```



Discussion:
Thank you for the report @bmwiedemann. I agree that that can be considered a bug.

The issue here stems from this line in `scipy/special/_generate_pyx.py`:
```python
defs.append(f'cdef extern from r"{proto_h_filename}":')
```
where `proto_h_filename` is an absolute path. Given that meson-python creates a tmpdir, absolute paths in installed files are no good. 

However, the more desirable fix here is to not install this header at all, since we don't need it in the installed package. For why we currently install it, see: https://github.com/scipy/scipy/blob/f8036bc210d95365cd3a9ac44462ad0640cad9a1/scipy/special/meson.build#L287-L291
In this case, we should be able to change `_generate_pyx.py` to use a relative path though, since the referenced header is located right next to the `.pyx` file. So that's the easier fix here.
There's a bunch of other code gen scripts with `cdef extern from`, but the ones I checked all used relative paths.

Resolving patch:
diff --git a/scipy/special/_generate_pyx.py b/scipy/special/_generate_pyx.py
--- a/scipy/special/_generate_pyx.py
+++ b/scipy/special/_generate_pyx.py
@@ -1232,6 +1232,7 @@ def get_declaration(ufunc, c_name, c_proto, cy_proto, header,
         # redeclare the function, so that the assumed
         # signature is checked at compile time
         new_name = f"{ufunc.cython_func_name(c_name)} \"{c_name}\""
+        proto_h_filename = os.path.basename(proto_h_filename)
         defs.append(f'cdef extern from r"{proto_h_filename}":')
         defs.append("    cdef %s" % (cy_proto.replace('(*)', new_name)))
         defs_h.append(f'#include "{header}"')


Test patch:
Repository: scipy/scipy

Issue:
DOC: typo in scipy.stats.Covariance
### Issue with current documentation:

We need to correct the spelling to 'matrix' in the Covariance class docstring, which is spelled as 'metrix'

### Idea or request for content:

_No response_

### Additional context (e.g. screenshots, GIFs)

_No response_


Discussion:

Resolving patch:
diff --git a/scipy/stats/_covariance.py b/scipy/stats/_covariance.py
--- a/scipy/stats/_covariance.py
+++ b/scipy/stats/_covariance.py
@@ -15,7 +15,7 @@ class Covariance:
     Calculations involving covariance matrices (e.g. data whitening,
     multivariate normal function evaluation) are often performed more
     efficiently using a decomposition of the covariance matrix instead of the
-    covariance metrix itself. This class allows the user to construct an
+    covariance matrix itself. This class allows the user to construct an
     object representing a covariance matrix using any of several
     decompositions and perform calculations using a common interface.
 


Test patch:
Repository: scipy/scipy

Issue:
DOC: interpolate: add note to BarycentricInterpolator.add_xi about numerical stability
### Issue with current documentation:

Currently the docs for `BarycentricInterpolator` don't mention that new points added by `add_xi` are not randomly permuted so they may introduce numerical instability. It would be nice to add a note documenting this and explaining that, if this occurs to reconstruct the interpolant from scratch instead.

https://github.com/scipy/scipy/blob/f990b1d2471748c79bc4260baf8923db0a5248af/scipy/interpolate/_polyint.py#L562-L566C28

### Idea or request for content:

Add note to `add_xi` docstring.a 

### Additional context (e.g. screenshots, GIFs)

Will get around to this eventually but in the meantime anybody is welcome to go for it


Discussion:

Resolving patch:
diff --git a/scipy/interpolate/_polyint.py b/scipy/interpolate/_polyint.py
--- a/scipy/interpolate/_polyint.py
+++ b/scipy/interpolate/_polyint.py
@@ -701,6 +701,13 @@ def add_xi(self, xi, yi=None):
             If `yi` is not given, the y values will be supplied later. `yi`
             should be given if and only if the interpolator has y values
             specified.
+
+        Notes
+        -----
+        The new points added by `add_xi` are not randomly permuted
+        so there is potential for numerical instability,
+        especially for a large number of points. If this
+        happens, please reconstruct interpolation from scratch instead.
         """
         if yi is not None:
             if self.yi is None:


Test patch:
Repository: scipy/scipy

Issue:
Calculation of frequencies w is not accurate when fs is default value (fs=2*pi)
Calculation of frequencies w is not accurate when fs is default value (fs=2*pi)

https://github.com/scipy/scipy/blob/686422c4f0a71be1b4258309590fd3e9de102e18/scipy/signal/_filter_design.py#L483

Because at first python calculates w * fs and then divide into (2*pi). 
It's needed to use parentheses to allow python at first calculates fs/(2 * pi) and then multiply w
This is correct:
w = w * (fs / (2 * pi))

And pls fix other functions which has the same issue (freqz_zpk, group_delay)


Discussion:
Could you give an example where this makes a practical difference?  E.g., here's one where's the a `1e-16`-order difference:

```
In [20]: w = 0.8278445229178596

In [21]: fs = 2 * pi

In [22]: (w - w * fs / (2 * pi))
Out[22]: 1.1102230246251565e-16

In [24]: (w - w * (fs / (2 * pi)))
Out[24]: 0.0
```

I agree, it's not a big difference.
For worN=512 max difference: 4.440892098500626e-16

`w1=np.array(w)`
`w = w*fs/(2*pi)`
`print(np.max(np.abs(w-w1)))`

4.440892098500626e-16
This seems like an easy fix, and may as well do it - applying `(fs / (2*pi))` first seems right.

Resolving patch:
diff --git a/scipy/signal/_filter_design.py b/scipy/signal/_filter_design.py
--- a/scipy/signal/_filter_design.py
+++ b/scipy/signal/_filter_design.py
@@ -478,7 +478,7 @@ def freqz(b, a=1, worN=512, whole=False, plot=None, fs=2*pi,
         h = (npp_polyval(zm1, b, tensor=False) /
              npp_polyval(zm1, a, tensor=False))
 
-    w = w*fs/(2*pi)
+    w = w*(fs/(2*pi))
 
     if plot is not None:
         plot(w, h)
@@ -588,7 +588,7 @@ def freqz_zpk(z, p, k, worN=512, whole=False, fs=2*pi):
     zm1 = exp(1j * w)
     h = k * polyvalfromroots(zm1, z) / polyvalfromroots(zm1, p)
 
-    w = w*fs/(2*pi)
+    w = w*(fs/(2*pi))
 
     return w, h
 
@@ -708,7 +708,7 @@ def group_delay(system, w=512, whole=False, fs=2*pi):
             stacklevel=2
         )
 
-    w = w*fs/(2*pi)
+    w = w*(fs/(2*pi))
 
     return w, gd
 


Test patch:
Repository: scipy/scipy

Issue:
BUG: Normal Inverse Gaussian numerically unstable
### Describe your issue.

The current implementation overflows in regimes that should be easily handled.

### Reproducing Code Example

```python

from scipy.stats import norminvgauss

jitter = 1e-3
Z = norminvgauss(2**0.5/jitter**2,1/jitter**2,loc=0,scale=1)

Z.pdf(1.0) # nan
```


### Error message


nans are not the wrong answer :-)



### SciPy/NumPy/Python version and system information


recent master




Discussion:

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
@@ -5208,9 +5208,9 @@ def _fitstart(self, data):
 
     def _pdf(self, x, a, b):
         gamma = np.sqrt(a**2 - b**2)
-        fac1 = a / np.pi * np.exp(gamma)
+        fac1 = a / np.pi
         sq = np.hypot(1, x)  # reduce overflows
-        return fac1 * sc.k1e(a * sq) * np.exp(b*x - a*sq) / sq
+        return fac1 * sc.k1e(a * sq) * np.exp(b*x - a*sq + gamma) / sq
 
     def _sf(self, x, a, b):
         if np.isscalar(x):


Test patch:
diff --git a/scipy/stats/tests/test_distributions.py b/scipy/stats/tests/test_distributions.py
--- a/scipy/stats/tests/test_distributions.py
+++ b/scipy/stats/tests/test_distributions.py
@@ -4658,6 +4658,17 @@ def test_entropy(self, a, ref, rtol):
 
         assert_allclose(stats.gamma.entropy(a), ref, rtol=rtol)
 
+def test_pdf_overflow_gh19616():
+    # Confirm that gh19616 (intermediate over/underflows in PDF) is resolved
+    # Reference value from R GeneralizedHyperbolic library
+    # library(GeneralizedHyperbolic)
+    # options(digits=16)
+    # jitter = 1e-3
+    # dnig(1, a=2**0.5 / jitter**2, b=1 / jitter**2)
+    jitter = 1e-3
+    Z = stats.norminvgauss(2**0.5 / jitter**2, 1 / jitter**2, loc=0, scale=1)
+    assert_allclose(Z.pdf(1.0), 282.0948446666433)
+
 
 class TestDgamma:
     def test_pdf(self):
Repository: scipy/scipy

Issue:
DOC: documentation for transpose operator for sparse matrices omits key information
### Issue with current documentation:

As it stands, every kind of scipy sparse array uses the same docstring for the transpose operator. That docstring (found [here](https://github.com/scipy/scipy/blob/main/scipy/sparse/_base.py#L783)) says: 

```python
Returns
-------
p : `self` with the dimensions reversed.
```

### Idea or request for content:

#### Misleading Documentation
However, for the ``csr_array`` and ``csc_array`` classes, it returns a ``csc_array`` and a ``csr_array``, respectively (the "opposite" of what the ``transpose`` operator was called on). 

This is a great choice in terms of the code, because that's by far the most efficient way to perform the transpose. The documentation is misleading, though, because saying it "returns `self` with dimensions reversed" is not entirely accurate.

#### Minimum Effort Solution
A minimum effort solution would be to add a line in the transpose docstring indicating that for ``csr_arrays`` and ``csc_arrays``, the class of the returned variable is swapped for efficiency.

Here's an example of a proposal for the new docstring:

```python
def transpose(self, axes=None, copy=False):
        """
        
        ---

        Returns
        -------
        p : `self` with the dimensions reversed.

        Notes
        --------
        If 'self' is a csr_array or a csc_array, then a csc_array or csr_array is
        returned, respectively.

        ---

        """
```

### Additional context (e.g. screenshots, GIFs)

_No response_


Discussion:
> A minimum effort solution would be to add a line in the transpose docstring indicating that for csr_arrays and csc_arrays, the class of the returned variable is swapped for efficiency.

PR welcome if you'd like to!

Resolving patch:
diff --git a/scipy/sparse/_base.py b/scipy/sparse/_base.py
--- a/scipy/sparse/_base.py
+++ b/scipy/sparse/_base.py
@@ -800,6 +800,11 @@ def transpose(self, axes=None, copy=False):
         -------
         p : `self` with the dimensions reversed.
 
+        Notes
+        -----
+        If `self` is a `csr_array` or a `csc_array`, then this will return a
+        `csc_array` or a `csr_array`, respectively.
+
         See Also
         --------
         numpy.transpose : NumPy's implementation of 'transpose' for ndarrays


Test patch:
Repository: scipy/scipy

Issue:
DOC: make default bounds in scipy.optimize.linprog more obvious
### Issue with current documentation:

If you open up the [docs page](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linprog.html), it's very hard to tell that by default the lower bound is 0 without reading everything very carefully. You have to scroll down to see it unless you're in full screen on my laptop. 

Furthermore, when the default lower bound is mentioned, it's mentioned in reference to  the `lb` and `up` variables which are not part of the function's signature or the LaTeX.

Edit: I think it's worth noting that not realizing that there was a lower bound by default causes me a lot of confusion. The lack of mention of this in the latex section or the function's signature prevented me from realizing that a lower bound existed causing me to be very confused and lose a lot of time. 

### Idea or request for content:

Either include that this is the default in the function's signature or mention this with in the LaTeX or both. You could add a line like this: 

 Note that by default $l=0$  and $u=\infty$.

### Additional context (e.g. screenshots, GIFs)

<img width="1437" alt="Screen Shot 2023-07-17 at 9 31 11 PM" src="https://github.com/scipy/scipy/assets/67246777/b9a43bae-e214-4bb8-ac34-70799372574f">



Discussion:
You are welcome to open a PR.

Resolving patch:
diff --git a/scipy/optimize/_linprog.py b/scipy/optimize/_linprog.py
--- a/scipy/optimize/_linprog.py
+++ b/scipy/optimize/_linprog.py
@@ -168,7 +168,7 @@ def linprog_terse_callback(res):
 
 
 def linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
-            bounds=None, method='highs', callback=None,
+            bounds=(0, None), method='highs', callback=None,
             options=None, x0=None, integrality=None):
     r"""
     Linear programming: minimize a linear objective function subject to linear


Test patch:
Repository: scipy/scipy

Issue:
MAINT: Use NumPy sliding_window_view instead of as_strided in fft_helper
The [`_fft_helper`](https://github.com/scipy/scipy/blob/fe967c70d783197511e1b0d45a0c34e0f1b5f8ba/scipy/signal/_spectral_py.py#L1968) function, which is still used by some non-legacy public functions (e.g. [`periodogram`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.periodogram.html#scipy.signal.periodogram) and [`csd`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.csd.html#scipy.signal.csd)), uses NumPy's [`as_strided`](https://numpy.org/doc/stable/reference/generated/numpy.lib.stride_tricks.as_strided.html) function to compute a sliding window view of an array. The latter function contains a warning in its documentation and is generally considered unsafe. For the current use case, NumPy introduced the [`sliding_window_view`](https://numpy.org/doc/stable/reference/generated/numpy.lib.stride_tricks.sliding_window_view.html) function in the 1.20 release several years ago. This new function is considered safer (the `as_strided` documentation refers to it as a safer alternative), uses `as_strided` under the hood, and is quite a bit easier to understand.

I suggest replacing `as_strided` by `sliding_window_view`. I am working on an implementation of this change (for my own use) and could open a PR if such a change is deemed worthwhile.


Discussion:

Resolving patch:
diff --git a/scipy/signal/_spectral_py.py b/scipy/signal/_spectral_py.py
--- a/scipy/signal/_spectral_py.py
+++ b/scipy/signal/_spectral_py.py
@@ -1987,16 +1987,15 @@ def _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides):
 
     .. versionadded:: 0.16.0
     """
-    # Created strided array of data segments
+    # Created sliding window view of array
     if nperseg == 1 and noverlap == 0:
         result = x[..., np.newaxis]
     else:
-        # https://stackoverflow.com/a/5568169
         step = nperseg - noverlap
-        shape = x.shape[:-1]+((x.shape[-1]-noverlap)//step, nperseg)
-        strides = x.strides[:-1]+(step*x.strides[-1], x.strides[-1])
-        result = np.lib.stride_tricks.as_strided(x, shape=shape,
-                                                 strides=strides)
+        result = np.lib.stride_tricks.sliding_window_view(
+            x, window_shape=nperseg, axis=-1, writeable=True
+        )
+        result = result[..., 0::step, :]
 
     # Detrend each data segment individually
     result = detrend_func(result)


Test patch:
Repository: scipy/scipy

Issue:
DOC: scipy.stats.unitary_group does not specify dim>1
### Issue with current documentation:

The current docs do not mention the restriction dim>1.  And in any case, I don't see why this restriction is applied.  dim=1 makes perfect sense.

### Idea or request for content:

_No response_

### Additional context (e.g. screenshots, GIFs)

_No response_


Discussion:

Resolving patch:
diff --git a/scipy/stats/_multivariate.py b/scipy/stats/_multivariate.py
--- a/scipy/stats/_multivariate.py
+++ b/scipy/stats/_multivariate.py
@@ -4158,7 +4158,7 @@ class unitary_group_gen(multi_rv_generic):
     Parameters
     ----------
     dim : scalar
-        Dimension of matrices
+        Dimension of matrices, must be greater than 1.
     seed : {None, int, np.random.RandomState, np.random.Generator}, optional
         Used for drawing random variates.
         If `seed` is `None`, the `~np.random.RandomState` singleton is used.


Test patch:
Repository: scipy/scipy

Issue:
DOC: linalg: Unclear description for the output `P` of `qr`.
### Issue with current documentation:

I find the description of the output `P` in the [documentation](https://scipy.github.io/devdocs/reference/generated/scipy.linalg.qr.html#scipy.linalg.qr) to be confusing. For the parameter `pivoting`, the docs say:

> Whether or not factorization should include pivoting for rank-revealing qr decomposition. If pivoting, compute the decomposition A P = Q R as above, but where P is chosen such that the diagonal of R is non-increasing.

This gives the impression that `P` must be an (N,N) array. However, it is an (N,) array. If I am not missing anything, there is no other description of what `P` is.

### Idea or request for content:

Upon playing with the code, I realized that the output `P` is a list of indices s.t. `a[:,P]` is the pivoted `a`. I suggest that we change the name of the variable `P`, and describe it. We could also add an example showing how to use this output to get the pivoted `a`.

On a side note, I think this could be a good first issue.

### Additional context (e.g. screenshots, GIFs)

_No response_


Discussion:

Resolving patch:
diff --git a/scipy/linalg/_decomp_qr.py b/scipy/linalg/_decomp_qr.py
--- a/scipy/linalg/_decomp_qr.py
+++ b/scipy/linalg/_decomp_qr.py
@@ -51,8 +51,8 @@ def qr(a, overwrite_a=False, lwork=None, mode='full', pivoting=False,
     pivoting : bool, optional
         Whether or not factorization should include pivoting for rank-revealing
         qr decomposition. If pivoting, compute the decomposition
-        ``A P = Q R`` as above, but where P is chosen such that the diagonal
-        of R is non-increasing.
+        ``A[:, P] = Q @ R`` as above, but where P is chosen such that the 
+        diagonal of R is non-increasing.
     check_finite : bool, optional
         Whether to check that the input matrix contains only finite numbers.
         Disabling may give a performance gain, but may result in problems


Test patch:
Repository: scipy/scipy

Issue:
DOC: optimize.root(method='lm') option
### Issue with current documentation:

The option called "epsfcn" in the doc for the `optimise.root(method='lm')` function is actually "eps" in the code.

### Idea or request for content:

Change option name "epsfcn" to "eps" in this doc page [optimize.root-lm](https://docs.scipy.org/doc/scipy/reference/optimize.root-lm.html)

### Additional context (e.g. screenshots, GIFs)

_No response_


Discussion:
I checked git history fo this function.
Before this [PR](https://github.com/scipy/scipy/pull/217), which was 12 years ago, the option for the root function was named `epsfcn`, but after this PR, it appears to have been changed to `eps`.
Some functions like[`fsolve`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html), [`leastsq`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html#scipy.optimize.leastsq), etc are using `epsfcn`. But, [`root(method="hybr")`](https://docs.scipy.org/doc/scipy/reference/optimize.root-hybr.html#optimize-root-hybr) is also using `esp`. 
So, API consistency stand of view, I think we should use `esp` in the `root` function.



Resolving patch:
diff --git a/scipy/optimize/_root.py b/scipy/optimize/_root.py
--- a/scipy/optimize/_root.py
+++ b/scipy/optimize/_root.py
@@ -291,9 +291,9 @@ def _root_leastsq(fun, x0, args=(), jac=None,
     maxiter : int
         The maximum number of calls to the function. If zero, then
         100*(N+1) is the maximum where N is the number of elements in x0.
-    epsfcn : float
+    eps : float
         A suitable step length for the forward-difference approximation of
-        the Jacobian (for Dfun=None). If epsfcn is less than the machine
+        the Jacobian (for Dfun=None). If `eps` is less than the machine
         precision, it is assumed that the relative errors in the functions
         are of the order of the machine precision.
     factor : float


Test patch:
Repository: scipy/scipy

Issue:
DOC: ndimage.convolve: clarify origin parameter description
### Issue with current documentation:

https://scipy.github.io/devdocs/reference/generated/scipy.ndimage.convolve.html#scipy-ndimage-convolve

The ndimage.convolve has the parameter origin, which is listed as type int.  

when working with this, it actually appears to take in a sequence with length equal to the number of dimensions.

### Idea or request for content:

clarifying the description to be the same as ndimage.correlate:
https://scipy.github.io/devdocs/reference/generated/scipy.ndimage.correlate.html#scipy.ndimage.correlate



### Additional context (e.g. screenshots, GIFs)

_No response_


Discussion:
@AlexanderForrest would you like to make a PR

Resolving patch:
diff --git a/scipy/ndimage/_filters.py b/scipy/ndimage/_filters.py
--- a/scipy/ndimage/_filters.py
+++ b/scipy/ndimage/_filters.py
@@ -883,11 +883,13 @@ def convolve(input, weights, output=None, mode='reflect', cval=0.0,
     cval : scalar, optional
         Value to fill past edges of input if `mode` is 'constant'. Default
         is 0.0
-    origin : int, optional
-        Controls the origin of the input signal, which is where the
-        filter is centered to produce the first element of the output.
-        Positive values shift the filter to the right, and negative values
-        shift the filter to the left. Default is 0.
+    origin : int or sequence, optional
+        Controls the placement of the filter on the input array's pixels.
+        A value of 0 (the default) centers the filter over the pixel, with
+        positive values shifting the filter to the right, and negative ones
+        to the left. By passing a sequence of origins with length equal to
+        the number of dimensions of the input array, different shifts can
+        be specified along each axis.
 
     Returns
     -------


Test patch: