ronantakizawa/codereview-bench huggingface dataset:
Repository: scipy/scipy
File: benchmarks/benchmarks/integrate.py (Python)

Code before:
        [1e-10, 1e-11],
    )

    param_names = ["rule", "ndim", "fdim", "rtol"]

    def setup(self, rule, ndim, fdim, rtol):
        self.ndim = ndim
        self.fdim = fdim

        self.rtol = rtol
        self.atol = 0

        self.a = np.zeros(self.ndim)
        self.b = np.repeat(1, self.ndim)
        self.rule = rule

        self.pool = ThreadPoolExecutor(2)

        if rule == "genz-malik" and ndim == 1:
            raise SkipNotImplemented(f"{rule} not defined for 1D integrals")

        if (rule == "gk-15" or rule == "gk-21") and ndim > 5:
            raise SkipNotImplemented(f"{rule} uses too much memory for ndim > 5")

        if rule == "gk-21" and ndim >= 5 and fdim == 8 and not is_xslow():
            raise SkipNotImplemented(f"Takes too long to run in CI")

    def f(self, x):
        npoints, ndim = x.shape[0], x.shape[-1]

        r = np.repeat(0.5, self.fdim)
        alphas = np.repeat(0.1, self.fdim * ndim).reshape(self.fdim, ndim)
        x_reshaped = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)

        return np.cos(2*np.pi*r + np.sum(alphas * x_reshaped, axis=-1))

    def time_plain(self, rule, ndim, fdim, rtol):
        cubature(
            f=self.f,
            a=self.a,
            b=self.b,
            rule=self.rule,
            rtol=self.rtol,
            atol=self.atol,
        )

    def time_threads(self, rule, ndim, fdim, rtol):
        cubature(
            f=self.f,
            a=self.a,
            b=self.b,

Review comment (refactor):
```suggestion
            raise SkipNotImplemented("Takes too long to run in CI")
```

Code after:
        [1e-10, 1e-11],
    )

    param_names = ["rule", "ndim", "fdim", "rtol"]

    def setup(self, rule, ndim, fdim, rtol):
        self.ndim = ndim
        self.fdim = fdim

        self.rtol = rtol
        self.atol = 0

        self.a = np.zeros(self.ndim)
        self.b = np.repeat(1, self.ndim)
        self.rule = rule

        self.pool = ThreadPoolExecutor(2)

        if rule == "genz-malik" and ndim == 1:
            raise SkipNotImplemented(f"{rule} not defined for 1D integrals")

        if (rule == "gk-15" or rule == "gk-21") and ndim > 5:
            raise SkipNotImplemented(f"{rule} uses too much memory for ndim > 5")

        if rule == "gk-21" and ndim >= 5 and fdim == 8 and not is_xslow():
            raise SkipNotImplemented("Takes too long to run in CI")

    def f(self, x):
        npoints, ndim = x.shape[0], x.shape[-1]

        r = np.repeat(0.5, self.fdim)
        alphas = np.repeat(0.1, self.fdim * ndim).reshape(self.fdim, ndim)
        x_reshaped = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)

        return np.cos(2*np.pi*r + np.sum(alphas * x_reshaped, axis=-1))

    def time_plain(self, rule, ndim, fdim, rtol):
        cubature(
            f=self.f,
            a=self.a,
            b=self.b,
            rule=self.rule,
            rtol=self.rtol,
            atol=self.atol,
        )

    def time_threads(self, rule, ndim, fdim, rtol):
        cubature(
            f=self.f,
            a=self.a,
            b=self.b,
Repository: scipy/scipy
File: scipy/stats/_quantile.py (Python)

Code before:
    # preserved in the output. Does not support zero-length `x`. For side='right',
    # NaNs in `y` are inserted to the left, in contrast with np.searchsorted.
    xp = array_namespace(x, y) if xp is None else xp
    x, y = _broadcast_arrays((x, y), axis=-1, xp=xp)

    a = xp.full(y.shape, 0)
    n = xp.count_nonzero(~xp.isnan(x), axis=-1, keepdims=True)
    b = xp.broadcast_to(n, y.shape)

    if side=='right':
        n_nans = x.shape[-1] - n
        a, b = a + n_nans, b + n_nans
        b = xp.where(n > 0, b, b - 1)  # handle all nan case?
        x, y = -xp.flip(x, axis=-1), -y

    # while xp.any(b - a > 1):
    # refactored to for loop with ~log2(n) iterations for JAX JIT
    for i in range(int(math.log2(x.shape[-1])) + 1):
        c = (a + b) // 2
        x0 = xp.take_along_axis(x, c, axis=-1)
        j = x0 >= y
        b = xp.where(j, c, b)
        a = xp.where(j, a, c)

    b = xp.where(y <= xp.min(x, axis=-1, keepdims=True), 0, b)
    return b if side == 'left' else  x.shape[-1] - b


Review comment (suggestion):
```suggestion
    return b if side == 'left' else x.shape[-1] - b
```

Code after:
    # preserved in the output. Does not support zero-length `x`. For side='right',
    # NaNs in `y` are inserted to the left, in contrast with np.searchsorted.
    xp = array_namespace(x, y) if xp is None else xp
    x, y = _broadcast_arrays((x, y), axis=-1, xp=xp)

    a = xp.full(y.shape, 0, device=xp_device(x))
    n = xp.count_nonzero(~xp.isnan(x), axis=-1, keepdims=True)
    b = xp.broadcast_to(n, y.shape)

    if side=='right':
        n_nans = x.shape[-1] - n
        a, b = a + n_nans, b + n_nans
        b = xp.where(n > 0, b, b - 1)  # handle all nan case?
        x, y = -xp.flip(x, axis=-1), -y

    # while xp.any(b - a > 1):
    # refactored to for loop with ~log2(n) iterations for JAX JIT
    for i in range(int(math.log2(x.shape[-1])) + 1):
        c = (a + b) // 2
        x0 = xp.take_along_axis(x, c, axis=-1)
        j = x0 >= y
        b = xp.where(j, c, b)
        a = xp.where(j, a, c)

    b = xp.where(y <= xp.min(x, axis=-1, keepdims=True), 0, b)
    return b if side == 'left' else x.shape[-1] - b
Repository: scipy/scipy
File: scipy/optimize/tests/test_optimize.py (Python)

Code before:
        assert_equal(res.nfev, res_default.nfev)

    def test_equal_bounds(self, workers, method):
        workers = workers or map
        if method not in ['l-bfgs-b', 'slsqp', 'trust-constr', 'tnc']:
            pytest.skip(f"{method} cannot use bounds")

        bounds = Bounds([0, 2.0, 0.], [10., 2.0, 10.])
        with MapWrapper(workers) as mf:
            res = optimize.minimize(
                rosen, self.x0, bounds=bounds, options={"workers": mf}, method=method
            )
        assert res.success
        assert_allclose(res.x[1], 2.0)


@pytest.mark.fail_slow(15)
def test_multiprocessing_too_many_open_files_23080():
    # https://github.com/scipy/scipy/issues/23080
    rng = np.random.default_rng()
    # should be enough fits to trigger the issue, which was due to a refcycle in
    # ScalarFunction
    for i in range(10):
        x0 = rng.uniform(-20, 20, size=3)
        with multiprocessing.Pool() as p:
            _minimize_bfgs(rosen, x0, workers=p.map)


Review comment (bug):
This test will only fail if the user has a limit on open files set low enough. What would you think about an assert_deallocated test instead?

https://github.com/scipy/scipy/blob/d33e485e0d899296b2cf72f38f5280ca20617a1a/scipy/optimize/tests/test_differentiable_functions.py#L992

Code after:
        assert_equal(res.x, res_default.x)
        assert_equal(res.nfev, res_default.nfev)

    def test_equal_bounds(self, workers, method):
        workers = workers or map
        if method not in ['l-bfgs-b', 'slsqp', 'trust-constr', 'tnc']:
            pytest.skip(f"{method} cannot use bounds")

        bounds = Bounds([0, 2.0, 0.], [10., 2.0, 10.])
        with MapWrapper(workers) as mf:
            res = optimize.minimize(
                rosen, self.x0, bounds=bounds, options={"workers": mf}, method=method
            )
        assert res.success
        assert_allclose(res.x[1], 2.0)


def test_multiprocessing_too_many_open_files_23080():
    # https://github.com/scipy/scipy/issues/23080
    x0 = np.array([0.9, 0.9])
    # check that ScalarHessWrapper doesn't keep pool object alive
    with assert_deallocated(multiprocessing.Pool, 2) as pool_obj:
        with pool_obj as p:
            _minimize_bfgs(rosen, x0, workers=p.map)
        del p
        del pool_obj
Repository: scipy/scipy
File: scipy/stats/_multivariate.py (Python)

Code before:

    """
    return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float)


def _validate_marginal_input(dimensions, multivariate_dims):
    """Determine if input dimensions can be marginalized. 

    Parameters
    ----------
    dimensions : float, ndarray
        Input dimensions to be marginalized 

    multivariate_dims : int
        Number of dimensions of multivariate distribution.

    Returns
    -------
    dims : ndarray
        Array of indices to marginalize
    """
    dims = np.copy(dimensions)
    dims = np.atleast_1d(dims)

    if len(dims) == 0:
        msg = ("Cannot marginalize all dimensions.")
        raise ValueError(msg)

    if not np.issubdtype(dims.dtype, np.integer):
        msg = ("Elements of `dimensions` must be integers - the indices "
                "of the marginal variables being retained.")
        raise ValueError(msg)

    original_dims = np.copy(dims)

    dims[dims < 0] = multivariate_dims + dims[dims < 0]

    if len(np.unique(dims)) != len(dims):
        msg = ("All elements of `dimensions` must be unique.")
        raise ValueError(msg)

    i_invalid = (dims < 0) | (dims >= multivariate_dims)
    if np.any(i_invalid):
        msg = (f"Dimensions {original_dims[i_invalid]} are invalid "
                f"for a distribution in {multivariate_dims} dimensions.")
        raise ValueError(msg)

    return dims


class _PSD:

Review comment (suggestion):
nitpick:

```suggestion
        msg = "Cannot marginalize all dimensions."
```

Code after:

    """
    return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float)


def _validate_marginal_input(dimensions, multivariate_dims):
    """Determine if input dimensions can be marginalized.

    Parameters
    ----------
    dimensions : float, ndarray
        Input dimensions to be marginalized
    multivariate_dims : int
        Number of dimensions of multivariate distribution.

    Returns
    -------
    dims : ndarray
        Array of indices to marginalize
    """
    dims = np.copy(dimensions)
    dims = np.atleast_1d(dims)

    if len(dims) == 0:
        msg = "Cannot marginalize all dimensions."
        raise ValueError(msg)

    if not np.issubdtype(dims.dtype, np.integer):
        msg = ("Elements of `dimensions` must be integers - the indices "
               "of the marginal variables being retained.")
        raise ValueError(msg)

    original_dims = np.copy(dims)

    dims[dims < 0] += multivariate_dims

    if len(np.unique(dims)) != len(dims):
        msg = "All elements of `dimensions` must be unique."
        raise ValueError(msg)

    i_invalid = (dims < 0) | (dims >= multivariate_dims)
    if np.any(i_invalid):
        msg = (f"Dimensions {original_dims[i_invalid]} are invalid "
               f"for a distribution in {multivariate_dims} dimensions.")
        raise ValueError(msg)

    return dims


class _PSD:
    """
Repository: scipy/scipy
File: scipy/stats/_multivariate.py (Python)

Code before:
        cond = factor[t] * np.finfo(t).eps
    eps = cond * np.max(abs(spectrum))
    return eps


def _pinv_1d(v, eps=1e-5):
    """A helper function for computing the pseudoinverse.

    Parameters
    ----------
    v : iterable of numbers
        This may be thought of as a vector of eigenvalues or singular values.
    eps : float
        Values with magnitude no greater than eps are considered negligible.

    Returns
    -------
    v_pinv : 1d float ndarray
        A vector of pseudo-inverted numbers.

    """
    return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float)


def _validate_marginal_input(dimensions, multivariate_dims):
    """Determine if input dimensions can be marginalized. 

    Parameters
    ----------
    dimensions : float, ndarray
        Input dimensions to be marginalized 

    multivariate_dims : int
        Number of dimensions of multivariate distribution.

    Returns
    -------
    dims : ndarray
        Array of indices to marginalize
    """
    dims = np.copy(dimensions)
    dims = np.atleast_1d(dims)

    if len(dims) == 0:
        msg = ("Cannot marginalize all dimensions.")
        raise ValueError(msg)

    if not np.issubdtype(dims.dtype, np.integer):
        msg = ("Elements of `dimensions` must be integers - the indices "
                "of the marginal variables being retained.")
        raise ValueError(msg)

Review comment (suggestion):
nitpick:
```suggestion
    """Determine if input dimensions can be marginalized.
```

Code after:
        cond = factor[t] * np.finfo(t).eps
    eps = cond * np.max(abs(spectrum))
    return eps


def _pinv_1d(v, eps=1e-5):
    """A helper function for computing the pseudoinverse.

    Parameters
    ----------
    v : iterable of numbers
        This may be thought of as a vector of eigenvalues or singular values.
    eps : float
        Values with magnitude no greater than eps are considered negligible.

    Returns
    -------
    v_pinv : 1d float ndarray
        A vector of pseudo-inverted numbers.

    """
    return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float)


def _validate_marginal_input(dimensions, multivariate_dims):
    """Determine if input dimensions can be marginalized.

    Parameters
    ----------
    dimensions : float, ndarray
        Input dimensions to be marginalized
    multivariate_dims : int
        Number of dimensions of multivariate distribution.

    Returns
    -------
    dims : ndarray
        Array of indices to marginalize
    """
    dims = np.copy(dimensions)
    dims = np.atleast_1d(dims)

    if len(dims) == 0:
        msg = "Cannot marginalize all dimensions."
        raise ValueError(msg)

    if not np.issubdtype(dims.dtype, np.integer):
        msg = ("Elements of `dimensions` must be integers - the indices "
               "of the marginal variables being retained.")
        raise ValueError(msg)
Repository: scipy/scipy
File: scipy/stats/_multivariate.py (Python)

Code before:
def _pinv_1d(v, eps=1e-5):
    """A helper function for computing the pseudoinverse.

    Parameters
    ----------
    v : iterable of numbers
        This may be thought of as a vector of eigenvalues or singular values.
    eps : float
        Values with magnitude no greater than eps are considered negligible.

    Returns
    -------
    v_pinv : 1d float ndarray
        A vector of pseudo-inverted numbers.

    """
    return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float)


def _validate_marginal_input(dimensions, multivariate_dims):
    """Determine if input dimensions can be marginalized. 

    Parameters
    ----------
    dimensions : float, ndarray
        Input dimensions to be marginalized 

    multivariate_dims : int
        Number of dimensions of multivariate distribution.

    Returns
    -------
    dims : ndarray
        Array of indices to marginalize
    """
    dims = np.copy(dimensions)
    dims = np.atleast_1d(dims)

    if len(dims) == 0:
        msg = ("Cannot marginalize all dimensions.")
        raise ValueError(msg)

    if not np.issubdtype(dims.dtype, np.integer):
        msg = ("Elements of `dimensions` must be integers - the indices "
                "of the marginal variables being retained.")
        raise ValueError(msg)

    original_dims = np.copy(dims)

    dims[dims < 0] = multivariate_dims + dims[dims < 0]


Review comment (suggestion):
nitpick:
```suggestion
        Input dimensions to be marginalized
```

Code after:
def _pinv_1d(v, eps=1e-5):
    """A helper function for computing the pseudoinverse.

    Parameters
    ----------
    v : iterable of numbers
        This may be thought of as a vector of eigenvalues or singular values.
    eps : float
        Values with magnitude no greater than eps are considered negligible.

    Returns
    -------
    v_pinv : 1d float ndarray
        A vector of pseudo-inverted numbers.

    """
    return np.array([0 if abs(x) <= eps else 1/x for x in v], dtype=float)


def _validate_marginal_input(dimensions, multivariate_dims):
    """Determine if input dimensions can be marginalized.

    Parameters
    ----------
    dimensions : float, ndarray
        Input dimensions to be marginalized
    multivariate_dims : int
        Number of dimensions of multivariate distribution.

    Returns
    -------
    dims : ndarray
        Array of indices to marginalize
    """
    dims = np.copy(dimensions)
    dims = np.atleast_1d(dims)

    if len(dims) == 0:
        msg = "Cannot marginalize all dimensions."
        raise ValueError(msg)

    if not np.issubdtype(dims.dtype, np.integer):
        msg = ("Elements of `dimensions` must be integers - the indices "
               "of the marginal variables being retained.")
        raise ValueError(msg)

    original_dims = np.copy(dims)

    dims[dims < 0] += multivariate_dims

    if len(np.unique(dims)) != len(dims):
Repository: scipy/scipy
File: scipy/odr/__init__.py (Python)

Code before:
"""
=================================================
Orthogonal distance regression (:mod:`scipy.odr`)
=================================================

.. currentmodule:: scipy.odr

.. deprecated:: 1.17.0
    `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
    `github.com/HugoMVale/odrpack-python <https://github.com/HugoMVale/odrpack-python/>`_
    instead.

    The following example shows a brief comparison of the APIs::

        import numpy as np
        import scipy.odr
        import odrpack

        # Classic "Pearson data" that motivates ODR.
        # Errors are in both variables, and if you don't account for this,
        # doing a linear fit of X vs. Y or Y vs. X will give you quit
        # different results.
        p_x = np.array([0., .9, 1.8, 2.6, 3.3, 4.4, 5.2, 6.1, 6.5, 7.4])
        p_y = np.array([5.9, 5.4, 4.4, 4.6, 3.5, 3.7, 2.8, 2.8, 2.4, 1.5])
        p_sx = np.array([.03, .03, .04, .035, .07, .11, .13, .22, .74, 1.])
        p_sy = np.array([1., .74, .5, .35, .22, .22, .12, .12, .1, .04])

        # Old-style
        # The RealData class takes care of details like turning
        # standard-deviation error bars into weights.
        p_dat = scipy.odr.RealData(p_x, p_y, sx=p_sx, sy=p_sy)
        # Note, parameters come before `x` in scipy.odr
        p_mod = scipy.odr.Model(lambda beta, x: beta[0] + beta[1]*x)
        p_odr = scipy.odr.ODR(p_dat, p_mod, beta0=[1., 1.])
        old_out = p_odr.run()

Review comment (suggestion):
The PyPI link might be more stable.
```suggestion
    `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
```

Code after:
"""
=================================================
Orthogonal distance regression (:mod:`scipy.odr`)
=================================================

.. currentmodule:: scipy.odr

.. deprecated:: 1.17.0
    `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
    `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
    instead.

    The following example shows a brief comparison of the APIs::

        import numpy as np
        import scipy.odr
        import odrpack

        # Classic "Pearson data" that motivates ODR.
        # Errors are in both variables, and if you don't account for this,
        # doing a linear fit of X vs. Y or Y vs. X will give you quite
        # different results.
        p_x = np.array([0., .9, 1.8, 2.6, 3.3, 4.4, 5.2, 6.1, 6.5, 7.4])
        p_y = np.array([5.9, 5.4, 4.4, 4.6, 3.5, 3.7, 2.8, 2.8, 2.4, 1.5])
        p_sx = np.array([.03, .03, .04, .035, .07, .11, .13, .22, .74, 1.])
        p_sy = np.array([1., .74, .5, .35, .22, .22, .12, .12, .1, .04])

        # Old-style
        # The RealData class takes care of details like turning
        # standard-deviation error bars into weights.
        p_dat = scipy.odr.RealData(p_x, p_y, sx=p_sx, sy=p_sy)
        # Note, parameters come before `x` in scipy.odr
        p_mod = scipy.odr.Model(lambda beta, x: beta[0] + beta[1]*x)
        p_odr = scipy.odr.ODR(p_dat, p_mod, beta0=[1., 1.])
        old_out = p_odr.run()
Repository: scipy/scipy
File: scipy/odr/models.py (Python)

Code before:
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.odr` namespace for importing the functions
# included below.


__all__ = [  # noqa: F822
    'Model', 'exponential', 'multilinear', 'unilinear',
    'quadratic', 'polynomial'
]


def __dir__():
    return __all__


def __getattr__(name):
    if name not in __all__:
        raise AttributeError(
            "`scipy.odr.models` is deprecated and will be removed in SciPy 1.19.0 and "
            f"has no attribute {name}.")

    import warnings
    from . import _models
    warnings.warn("`scipy.odr` is deprecated and will be removed in SciPy 1.19.0",
                  category=DeprecationWarning, stacklevel=2)

    return getattr(_models, name)


Review comment (suggestion):
I think it would be helpful to also include the version in which the deprecation began (that's how I interpret https://docs.scipy.org/doc/scipy/dev/core-dev/index.html#deprecations, anyway) and the replacement URL. I've heard arguments against extra text in warnings like that before, but that's what I think I'd want as a user.

Code after:
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.odr` namespace for importing the functions
# included below.


__all__ = [  # noqa: F822
    'Model', 'exponential', 'multilinear', 'unilinear',
    'quadratic', 'polynomial'
]


def __dir__():
    return __all__


def __getattr__(name):
    msg = ("`scipy.odr` is deprecated as of version 1.17.0 and will be removed in "
           "SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.")
    if name not in __all__:
        raise AttributeError(
            f"`scipy.odr.models` has no attribute {name}. In addition, {msg}")

    import warnings
    from . import _models
    warnings.warn(msg, category=DeprecationWarning, stacklevel=2)

    return getattr(_models, name)
Repository: scipy/scipy
File: scipy/odr/models.py (Python)

Code before:
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.odr` namespace for importing the functions
# included below.

from scipy._lib.deprecation import _sub_module_deprecation

__all__ = [  # noqa: F822
    'Model', 'exponential', 'multilinear', 'unilinear',
    'quadratic', 'polynomial'
]


def __dir__():
    return __all__


def __getattr__(name):
    return _sub_module_deprecation(sub_package="odr", module="models",
                                   private_modules=["_models"], all=__all__,
                                   attribute=name)


Review comment (suggestion):
In order to see:
```
<ipython-input-3-f86819d5bc3c>:1: DeprecationWarning: `scipy.odr` is deprecated as of version 1.17.0 and will be removed in SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.
  from scipy import odr
```
when I run:
```python3
from scipy import odr
```
I had to set:
```suggestion
    warnings.warn(msg, category=DeprecationWarning, stacklevel=5)
```
I needed `stacklevel=3` for `from scipy.odr import ODR` and such.

Code after:
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.odr` namespace for importing the functions
# included below.


__all__ = [  # noqa: F822
    'Model', 'exponential', 'multilinear', 'unilinear',
    'quadratic', 'polynomial'
]


def __dir__():
    return __all__


def __getattr__(name):
    msg = ("`scipy.odr` is deprecated as of version 1.17.0 and will be removed in "
           "SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.")
    if name not in __all__:
        raise AttributeError(
            f"`scipy.odr.models` has no attribute {name}. In addition, {msg}")

    import warnings
    from . import _models
    warnings.warn(msg, category=DeprecationWarning, stacklevel=2)

    return getattr(_models, name)