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

Issue:
BUG: scipy.stats.multivariate_normal.logpdf mutates some inputs
### Describe your issue.

`scipy.stats.multivariate_normal.logpdf` does in-place mutation of the shape of some inputs.

### Reproducing Code Example

```python
from scipy.stats import multivariate_normal
import numpy as np

args = [np.array(1., np.float32), np.array(2., np.float64), np.array(3., np.float64)]
print([x.shape for x in args])
# [(), (), ()]

multivariate_normal.logpdf(*args)
print([x.shape for x in args])
# [(), (1,), (1, 1)]
```


### Error message

```shell
N/A
```


### SciPy/NumPy/Python version information

1.7.1 1.21.2 sys.version_info(major=3, minor=7, micro=12, releaselevel='final', serial=0)


Discussion:
I think the fix should be as simple as using `np.reshape` here: https://github.com/scipy/scipy/blob/7bd50b768387b1c05ceb55ecc99b84c0350a5807/scipy/stats/_multivariate.py#L398-L400

Assuming this side-effect is not intended, I can prepare a PR.
Thanks, @jakevdp, that's definitely a bug.  A PR would be welcome!

Resolving patch:
diff --git a/scipy/stats/_multivariate.py b/scipy/stats/_multivariate.py
--- a/scipy/stats/_multivariate.py
+++ b/scipy/stats/_multivariate.py
@@ -396,8 +396,8 @@ def _process_parameters(self, dim, mean, cov):
         cov = np.asarray(cov, dtype=float)
 
         if dim == 1:
-            mean.shape = (1,)
-            cov.shape = (1, 1)
+            mean = mean.reshape(1)
+            cov = cov.reshape(1, 1)
 
         if mean.ndim != 1 or mean.shape[0] != dim:
             raise ValueError("Array 'mean' must be a vector of length %d." %
@@ -4125,8 +4125,8 @@ def _process_parameters(self, loc, shape, df):
             dim = loc.size
 
         if dim == 1:
-            loc.shape = (1,)
-            shape.shape = (1, 1)
+            loc = loc.reshape(1)
+            shape = shape.reshape(1, 1)
 
         if loc.ndim != 1 or loc.shape[0] != dim:
             raise ValueError("Array 'loc' must be a vector of length %d." %


Test patch:
Repository: scipy/scipy

Issue:
BUG: distributions' var method does not respect broadcasting
### Describe your issue.

It seems that since scipy 1.7.0, the `.var()` method of scipy distributions like `norm` or `logistic` does not respect the broadcasting rule. I would expect the following reproducing assertation pass.

### Reproducing Code Example

```python
import numpy as np
import scipy.stats as sp
assert (sp.norm(np.zeros(2), np.array([[1], [2]])).var() == sp.norm(np.zeros(2), np.array([[1, 1], [2, 2]])).var()).all()
```


### Error message

```shell
AssertionError
```


### SciPy/NumPy/Python version information

1.7.1 1.19.5 sys.version_info(major=3, minor=7, micro=12, releaselevel='final', serial=0)


Discussion:
Seems like a bug in `argsreduce` here:

https://github.com/scipy/scipy/blob/c30fefc2446a7cb93de1b45765e243345d5929db/scipy/stats/_distn_infrastructure.py#L572

When all the values are valid, it doesn't broadcast the arrays to correct shape. But if any invalid values are given, it will return the correct output:

```python
>>> import scipy.stats as sp
>>> sp.norm.var([0,0], [[1],[float('nan')]])
array([[ 1.,  1.],
       [nan, nan]])
```

Resolving patch:
diff --git a/scipy/stats/_distn_infrastructure.py b/scipy/stats/_distn_infrastructure.py
--- a/scipy/stats/_distn_infrastructure.py
+++ b/scipy/stats/_distn_infrastructure.py
@@ -568,8 +568,9 @@ def argsreduce(cond, *args):
         newargs = [newargs, ]
 
     if np.all(cond):
-        # Nothing to do
-        return newargs
+        # broadcast arrays with cond
+        *newargs, cond = np.broadcast_arrays(*newargs, cond)
+        return [arg.ravel() for arg in newargs]
 
     s = cond.shape
     # np.extract returns flattened arrays, which are not broadcastable together


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
@@ -6054,6 +6054,17 @@ def test_support_broadcasting_gh13294_regression():
     assert b2.shape == ex_b2.shape
 
 
+def test_stats_broadcasting_gh14953_regression():
+    # test case in gh14953
+    loc = [0., 0.]
+    scale = [[1.], [2.], [3.]]
+    assert_equal(stats.norm.var(loc, scale), [[1., 1.], [4., 4.], [9., 9.]])
+    # test some edge cases
+    loc = np.empty((0, ))
+    scale = np.empty((1, 0))
+    assert stats.norm.var(loc, scale).shape == (1, 0)
+
+
 # Check a few values of the cosine distribution's cdf, sf, ppf and
 # isf methods.  Expected values were computed with mpmath.
Repository: scipy/scipy

Issue:
add QhullError to the public API for scipy.spatial?
A recent PR to scikit-image (not yet merged) involves use of `QhullError` as imported from `scipy.spatial.qhull`, but it looks like this is not public API (reference discussion at https://github.com/scikit-image/scikit-image/pull/6008/files#r744350997). My question is whether this attribute should be public? The use case is to check for this error type and return a sensible result when a convex hull for an object cannot be found.

It seems this would just involve adding it to `__all__` [here](https://github.com/scipy/scipy/blob/7c904a77ad3d239bc35f18222810c9454e5441c3/scipy/spatial/_qhull.pyx#L31) so that it can be imported using `from scipy.spatial import QhullError`.

ping @czgdp1807 and @rgommers who worked on defining the `scipy.spatial` API recently in #14923



Discussion:
Not sure what Ralf thinks, but most of the work under the hood is done by Qhull so at first glance it doesn't seem like a bad idea to make the error object public/"official." 

Handling degenerate conditions/lack of general position can also be a pain for many of the diagrams so if we can leave that to Qhull as much as possible that might be a win (and folks would presumably want to be able to catch those errors sometimes). Maybe there are downsides I'm not thinking of though.
> My question is whether this attribute should be public? The use case is to check for this error type and return a sensible result when a convex hull for an object cannot be found.

When I integrated the UNU.RAN library, I made a decision to make the error object `UNURANError` public for the same reason @grlee77 mentioned. Not sure if it applies to Qhull but generally having the error object public also improves the readability of the user code (e.g. in a try...except block, instead of `except RuntimeError`, we could have `except QhullError` which is much more informative). 
So would it be OK for me to submit a PR based on @grlee77 suggestion? 

Seems reasonable to me. Submitting a PR sounds good, thanks @boazmohar.


Resolving patch:
diff --git a/scipy/spatial/__init__.py b/scipy/spatial/__init__.py
--- a/scipy/spatial/__init__.py
+++ b/scipy/spatial/__init__.py
@@ -91,6 +91,12 @@
    procrustes
    geometric_slerp
 
+Warnings / Errors used in :mod:`scipy.spatial`
+----------------------------------------------
+.. autosummary::
+   :toctree: generated/
+   QhullError
+
 """
 
 from ._kdtree import *


Test patch:
Repository: scipy/scipy

Issue:
Might be j<=i+k?
https://github.com/scipy/scipy/blob/47bb6febaa10658c72962b9615d5d5aa2513fa3a/scipy/linalg/special_matrices.py#L24


Discussion:
Indeed.

```
In [9]: from scipy.linalg import tri

In [10]: i, j, k = 3, 5, 2

In [11]: A = tri(i, j, k, dtype=int)

In [12]: A
Out[12]:
array([[1, 1, 1, 0, 0],
       [1, 1, 1, 1, 0],
       [1, 1, 1, 1, 1]])

In [13]: for i in range(i):
    ...:     for j in range(j):
    ...:         if i <= j+k:
    ...:             assert A[i,j]==1
    ...:
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-13-4ac88054cc46> in <module>
      2     for j in range(j):
      3         if i <= j+k:
----> 4             assert A[i,j]==1
      5

AssertionError:

In [14]: for i in range(i):
    ...:     for j in range(j):
    ...:         if j <= i+k:
    ...:             assert A[i,j]==1
    ...:# no assertion error
```

Resolving patch:
diff --git a/scipy/linalg/_special_matrices.py b/scipy/linalg/_special_matrices.py
--- a/scipy/linalg/_special_matrices.py
+++ b/scipy/linalg/_special_matrices.py
@@ -21,7 +21,7 @@ def tri(N, M=None, k=0, dtype=None):
     """
     Construct (N, M) matrix filled with ones at and below the kth diagonal.
 
-    The matrix has A[i,j] == 1 for i <= j + k
+    The matrix has A[i,j] == 1 for j <= i + k
 
     Parameters
     ----------


Test patch:
Repository: scipy/scipy

Issue:
`stats.contingency` not listed as public API 
Follow-up on https://github.com/scipy/scipy/pull/14898#issuecomment-950387176: `stats.continency` is public I believe, because the namespace is used in http://scipy.github.io/devdocs/reference/stats.html#contingency-table-functions and the functions there are not present in the main namespace. There was some discussion on an issue or PR about that, but probably not on the mailing list.

The bug report here is that `contingency` is not listed as a public submodule in http://scipy.github.io/devdocs/reference/index.html#api-definition.


Discussion:
@Smit-create could you take this along in your public API test PR?

Resolving patch:
diff --git a/scipy/stats/contingency.py b/scipy/stats/contingency.py
--- a/scipy/stats/contingency.py
+++ b/scipy/stats/contingency.py
@@ -156,7 +156,7 @@ def chi2_contingency(observed, correction=True, lambda_=None):
         By default, the statistic computed in this test is Pearson's
         chi-squared statistic [2]_.  `lambda_` allows a statistic from the
         Cressie-Read power divergence family [3]_ to be used instead.  See
-        `power_divergence` for details.
+        `scipy.stats.power_divergence` for details.
 
     Returns
     -------
@@ -171,12 +171,12 @@ def chi2_contingency(observed, correction=True, lambda_=None):
 
     See Also
     --------
-    contingency.expected_freq
-    fisher_exact
-    chisquare
-    power_divergence
-    barnard_exact
-    boschloo_exact
+    scipy.stats.contingency.expected_freq
+    scipy.stats.fisher_exact
+    scipy.stats.chisquare
+    scipy.stats.power_divergence
+    scipy.stats.barnard_exact
+    scipy.stats.boschloo_exact
 
     Notes
     -----


Test patch:
diff --git a/scipy/_lib/tests/test_public_api.py b/scipy/_lib/tests/test_public_api.py
--- a/scipy/_lib/tests/test_public_api.py
+++ b/scipy/_lib/tests/test_public_api.py
@@ -84,6 +84,7 @@ def test_dir_testing():
     "spatial.transform",
     "special",
     "stats",
+    "stats.contingency",
     "stats.distributions",
     "stats.mstats",
     "stats.qmc",
@@ -201,7 +202,6 @@ def test_dir_testing():
     'scipy.special.specfun',
     'scipy.special.spfun_stats',
     'scipy.stats.biasedurn',
-    'scipy.stats.contingency',
     'scipy.stats.kde',
     'scipy.stats.morestats',
     'scipy.stats.mstats_basic',
Repository: scipy/scipy

Issue:
scipy.sparse.linalg.inv cannot take ndarray as argument despite what documentation says
The documentation ([scipy.sparse.linalg.inv](https://docs.scipy.org/doc/scipy/reference/reference/generated/scipy.sparse.linalg.inv.html#scipy.sparse.linalg.inv)) says

> Parameters
>
>   A(M,M) ndarray or sparse matrix
>
>   square matrix to be inverted

But this code
```
import numpy as np
from scipy.sparse import linalg
linalg.inv(np.array([[1, 2], [3, 4]]))
```
throws:
```
TypeError: Input must be a sparse matrix
```




Discussion:
I suspect the best option here is to fix the docs.
Would it be possible for `scipy.sparse.linalg.inv` to call `np.linalg.inv` if `A` is an `ndarray`?
@gdupras, yes, that's possible, and it may have been the original intent of the docstring author, but the explicit check for a sparse input has been there for many years, so I suspect there isn't much demand for that convenience.  @perimosocordiae, @pv: any preferences?
May be best to fix the docs here, since it is not clear which `inv` to dispatch to otherwise (scipy? numpy?).

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
@@ -33,19 +33,19 @@ def inv(A):
 
     Parameters
     ----------
-    A : (M,M) ndarray or sparse matrix
+    A : (M, M) sparse matrix
         square matrix to be inverted
 
     Returns
     -------
-    Ainv : (M,M) ndarray or sparse matrix
+    Ainv : (M, M) sparse matrix
         inverse of `A`
 
     Notes
     -----
     This computes the sparse inverse of `A`. If the inverse of `A` is expected
     to be non-sparse, it will likely be faster to convert `A` to dense and use
-    scipy.linalg.inv.
+    `scipy.linalg.inv`.
 
     Examples
     --------
@@ -66,10 +66,11 @@ def inv(A):
     .. versionadded:: 0.12.0
 
     """
-    #check input
+    # Check input
     if not (scipy.sparse.isspmatrix(A) or is_pydata_spmatrix(A)):
         raise TypeError('Input must be a sparse matrix')
 
+    # Use sparse direct solver to solve "AX = I" accurately
     I = _ident_like(A)
     Ainv = spsolve(A, I)
     return Ainv
@@ -92,7 +93,7 @@ def _onenorm_matrix_power_nnm(A, p):
         The 1-norm of the matrix power p of A.
 
     """
-    # check input
+    # Check input
     if int(p) != p or p < 0:
         raise ValueError('expected non-negative integer p')
     p = int(p)


Test patch:
Repository: scipy/scipy

Issue:
BUG: bounded L-BFGS-B doesn't work with a scalar.
### Describe your issue.

The  following example worked with 1.7.*, but not with version 1.8. @tylerjereddy, this needs to be fixed before the final release of 1.8.0. I have a PR incoming.

### Reproducing Code Example

```python
import numpy as np
from scipy.optimize import minimize, rosen

def f(x):
    return np.sum(x**2)
    
x0 = 17
res = minimize(f, x0, bounds=[(-100, 100)], method='L-BFGS-B')
```


### Error message

```shell
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/var/folders/m8/gwtcncws12jf60xw5n6knwnw0000gn/T/ipykernel_92447/1079589486.py in <module>
      6 
      7 x0 = 17
----> 8 res = minimize(f, x0, bounds=[(-100, 100)], method='L-BFGS-B')
      9 print(res)

~/Documents/Andy/programming/scipy/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
    664                                                        x_fixed, min_dim=2,
    665                                                        remove=1)
--> 666         bounds = standardize_bounds(bounds, x0, meth)
    667 
    668     if meth == 'nelder-mead':

~/Documents/Andy/programming/scipy/scipy/optimize/_minimize.py in standardize_bounds(bounds, x0, meth)
    927     elif meth in ('l-bfgs-b', 'tnc', 'slsqp', 'old'):
    928         if isinstance(bounds, Bounds):
--> 929             bounds = new_bounds_to_old(bounds.lb, bounds.ub, x0.shape[0])
    930     return bounds
    931 

IndexError: tuple index out of range
```


### SciPy/NumPy/Python version information

1.8.dev


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
@@ -513,7 +513,7 @@ def minimize(fun, x0, args=(), method=None, jac=None, hess=None,
     It should converge to the theoretical solution (1.4 ,1.7).
 
     """
-    x0 = np.asarray(x0)
+    x0 = np.atleast_1d(np.asarray(x0))
     if x0.dtype.kind in np.typecodes["AllInteger"]:
         x0 = np.asarray(x0, dtype=float)
 


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
@@ -1423,6 +1423,20 @@ def test_duplicate_evaluations(self, method):
                     "Duplicate evaluations made by {}".format(method))
 
 
+@pytest.mark.parametrize(
+    'method',
+    ['l-bfgs-b', 'tnc', 'Powell', 'Nelder-Mead']
+)
+def test_minimize_with_scalar(method):
+    # checks that minimize works with a scalar being provided to it.
+    def f(x):
+        return np.sum(x ** 2)
+
+    res = optimize.minimize(f, 17, bounds=[(-100, 100)], method=method)
+    assert res.success
+    assert_allclose(res.x, [0.0], atol=1e-5)
+
+
 class TestLBFGSBBounds:
     def setup_method(self):
         self.bounds = ((1, None), (None, None))
Repository: scipy/scipy

Issue:
DOC: Multivariate normal CDF docstring typo
I noticed that the docstring for the [multivariate normal `_cdf` function](https://github.com/scipy/scipy/blob/master/scipy/stats/_multivariate.py#L520) says 

```python
"""Log of the multivariate normal cumulative distribution function."""
```

However, I believe that this function is actually computing the standard, non-transformed CDF. 

Obviously this is extremely minor, but I thought it could be a good "first issue" for someone! 



Discussion:
Thanks @timleathart. True, It should have the same docstrings as `cdf`.
I'll take this on for a first issue - I use the library often and am looking to be more active fixing. Just will take me a minute to read over the PR process to make sure I'm doing it per the book
Thanks for your interest @bobcatCA!

Resolving patch:
diff --git a/scipy/stats/_multivariate.py b/scipy/stats/_multivariate.py
--- a/scipy/stats/_multivariate.py
+++ b/scipy/stats/_multivariate.py
@@ -518,7 +518,7 @@ def pdf(self, x, mean=None, cov=1, allow_singular=False):
         return _squeeze_output(out)
 
     def _cdf(self, x, mean, cov, maxpts, abseps, releps):
-        """Log of the multivariate normal cumulative distribution function.
+        """Multivariate normal cumulative distribution function.
 
         Parameters
         ----------


Test patch:
Repository: scipy/scipy

Issue:
BUG: `highs-ds` returns memoryviews instead of np.arrays for the dual values
According to the docs, the `highs-ds` method returns the Lagrangian multipliers (also known as *dual values*) corresponding to both the inequality/equality constraints and the upper/lower bounds as np.ndarray. However, for the latter it returns memoryviews.

# Reproducing Code Example

``` python
import numpy as np
from scipy.optimize import linprog

c = -1*np.array([300, 500])
A_ub = np.array([[1, 2], [1, 1], [0, 3]])
b_ub = np.array([170, 150, 180])
bounds = [(0, 100), (0, 100)]

# solve c'x  s.t.  A_ub*x <= b_ub,  0 <= x <= 100
result = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method="highs-ds")
for key in ['lower', 'upper', 'eqlin', 'ineqlin']:
    print(result[key]['marginals'])
```

yields

``` none
<MemoryView of 'ndarray' object>
<MemoryView of 'ndarray' object>
[]
[-250.   -0.   -0.]
```

---

I had a look at the Cython wrapper and it indeed returns a memoryview which isn't converted to np.ndarray:

https://github.com/scipy/scipy/blob/a0e129fc3ba89fd81a5fa7e5e4d6aa2ec635a674/scipy/optimize/_highs/cython/src/_highs_wrapper.pyx#L706

https://github.com/scipy/scipy/blob/a0e129fc3ba89fd81a5fa7e5e4d6aa2ec635a674/scipy/optimize/_linprog_highs.py#L385-L386




Discussion:
Thanks for reporting @jhelgert !  I do remember seeing this as well, should be a simple cast to `np.array`.  Would you like to submit a PR?

Resolving patch:
diff --git a/scipy/optimize/_linprog_highs.py b/scipy/optimize/_linprog_highs.py
--- a/scipy/optimize/_linprog_highs.py
+++ b/scipy/optimize/_linprog_highs.py
@@ -389,8 +389,8 @@ def _linprog_highs(lp, solver, time_limit=None, presolve=True,
         lamda = res['lambda']
         marg_ineqlin = np.array(lamda[:len(b_ub)])
         marg_eqlin = np.array(lamda[len(b_ub):])
-        marg_upper = res['marg_bnds'][1, :]
-        marg_lower = res['marg_bnds'][0, :]
+        marg_upper = np.array(res['marg_bnds'][1, :])
+        marg_lower = np.array(res['marg_bnds'][0, :])
     else:
         marg_ineqlin, marg_eqlin = None, None
         marg_upper, marg_lower = None, None


Test patch:
diff --git a/scipy/optimize/tests/test_linprog.py b/scipy/optimize/tests/test_linprog.py
--- a/scipy/optimize/tests/test_linprog.py
+++ b/scipy/optimize/tests/test_linprog.py
@@ -1172,6 +1172,10 @@ def test_optimize_result(self):
         assert_allclose(c @ res.x, res.fun)
         assert_allclose(b_eq - A_eq @ res.x, res.con, atol=1e-11)
         assert_allclose(b_ub - A_ub @ res.x, res.slack, atol=1e-11)
+        for key in ['eqlin', 'ineqlin', 'lower', 'upper']:
+            if key in res.keys():
+                assert isinstance(res[key]['marginals'], np.ndarray)
+                assert isinstance(res[key]['residual'], np.ndarray)
 
     #################
     # Bug Fix Tests #
Repository: scipy/scipy

Issue:
ENH: change version switcher to use the theme
The version switcher is now available on the theme side so we can update the badge logic we added in #14132

https://pydata-sphinx-theme.readthedocs.io/en/latest/user_guide/configuring.html?highlight=version#add-a-dropdown-to-switch-between-docs-versions

One thing I am not sure yet is if they handle colours like we do. If not I will raise it upstream as I think it's a handy visual help.

I believe this would close https://github.com/scipy/scipy.org/issues/423 and https://github.com/scipy/docs.scipy.org/issues/59


Discussion:

Resolving patch:
diff --git a/doc/source/conf.py b/doc/source/conf.py
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -154,7 +154,6 @@
         r"'U' mode is deprecated",  # sphinx io
         r"OpenSSL\.rand is deprecated",  # OpenSSL package in linkcheck
         r"Using or importing the ABCs from",  # 3.5 importlib._bootstrap
-        r"'contextfunction' is renamed to 'pass_context'",  # Jinja
         r"distutils Version",  # distutils
         ):
     warnings.filterwarnings(  # deal with other modules having bad imports
@@ -189,9 +188,16 @@
 html_theme_options = {
   "logo_link": "index",
   "github_url": "https://github.com/scipy/scipy",
-  "navbar_start": ["navbar-logo", "version"],
+  "navbar_end": ["version-switcher", "navbar-icon-links"],
+  "switcher": {
+      "json_url": "https://scipy.github.io/devdocs/_static/version_switcher.json"
+      "version_match": version,
+  }
 }
 
+if 'dev' in version:
+    html_theme_options["switcher"]["version_match"] = "dev"
+
 if 'versionwarning' in tags:
     # Specific to docs.scipy.org deployment.
     # See https://github.com/scipy/docs.scipy.org/blob/main/_static/versionwarning.js_t
@@ -200,14 +206,9 @@
            'script.src = "/doc/_static/versionwarning.js";\n'
            'document.head.appendChild(script);');
     html_context = {
-        'VERSIONCHECK_JS': src,
-        'versionwarning': True
+        'VERSIONCHECK_JS': src
     }
     html_js_files = ['versioncheck.js']
-else:
-    html_context = {
-        'versionwarning': False
-    }
 
 html_title = "%s v%s Manual" % (project, version)
 html_static_path = ['_static']


Test patch: