summaryrefslogtreecommitdiff
path: root/numpy/lib
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/lib')
-rw-r--r--numpy/lib/arraypad.py29
-rw-r--r--numpy/lib/function_base.py74
-rw-r--r--numpy/lib/index_tricks.py16
-rw-r--r--numpy/lib/polynomial.py77
-rw-r--r--numpy/lib/tests/test_io.py30
-rw-r--r--numpy/lib/twodim_base.py2
6 files changed, 192 insertions, 36 deletions
diff --git a/numpy/lib/arraypad.py b/numpy/lib/arraypad.py
index 7569e7651..069e1fab3 100644
--- a/numpy/lib/arraypad.py
+++ b/numpy/lib/arraypad.py
@@ -207,23 +207,20 @@ def _get_linear_ramps(padded, axis, width_pair, end_value_pair):
"""
edge_pair = _get_edges(padded, axis, width_pair)
- left_ramp = np.linspace(
- start=end_value_pair[0],
- stop=edge_pair[0].squeeze(axis), # Dimensions is replaced by linspace
- num=width_pair[0],
- endpoint=False,
- dtype=padded.dtype,
- axis=axis,
- )
-
- right_ramp = np.linspace(
- start=end_value_pair[1],
- stop=edge_pair[1].squeeze(axis), # Dimension is replaced by linspace
- num=width_pair[1],
- endpoint=False,
- dtype=padded.dtype,
- axis=axis,
+ left_ramp, right_ramp = (
+ np.linspace(
+ start=end_value,
+ stop=edge.squeeze(axis), # Dimension is replaced by linspace
+ num=width,
+ endpoint=False,
+ dtype=padded.dtype,
+ axis=axis
+ )
+ for end_value, edge, width in zip(
+ end_value_pair, edge_pair, width_pair
+ )
)
+
# Reverse linear space in appropriate dimension
right_ramp = right_ramp[_slice_at_axis(slice(None, None, -1), axis)]
diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py
index 1053598b1..6ea9cc4de 100644
--- a/numpy/lib/function_base.py
+++ b/numpy/lib/function_base.py
@@ -431,10 +431,13 @@ def asarray_chkfinite(a, dtype=None, order=None):
of lists and ndarrays. Success requires no NaNs or Infs.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
- order : {'C', 'F'}, optional
- Whether to use row-major (C-style) or
- column-major (Fortran-style) memory representation.
- Defaults to 'C'.
+ order : {'C', 'F', 'A', 'K'}, optional
+ Memory layout. 'A' and 'K' depend on the order of input array a.
+ 'C' row-major (C-style),
+ 'F' column-major (Fortran-style) memory representation.
+ 'A' (any) means 'F' if `a` is Fortran contiguous, 'C' otherwise
+ 'K' (keep) preserve input order
+ Defaults to 'C'.
Returns
-------
@@ -2543,6 +2546,69 @@ def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue):
for backwards compatibility with previous versions of this function. These
arguments had no effect on the return values of the function and can be
safely ignored in this and previous versions of numpy.
+
+ Examples
+ --------
+ In this example we generate two random arrays, ``xarr`` and ``yarr``, and
+ compute the row-wise and column-wise Pearson correlation coefficients,
+ ``R``. Since ``rowvar`` is true by default, we first find the row-wise
+ Pearson correlation coefficients between the variables of ``xarr``.
+
+ >>> import numpy as np
+ >>> rng = np.random.default_rng(seed=42)
+ >>> xarr = rng.random((3, 3))
+ >>> xarr
+ array([[0.77395605, 0.43887844, 0.85859792],
+ [0.69736803, 0.09417735, 0.97562235],
+ [0.7611397 , 0.78606431, 0.12811363]])
+ >>> R1 = np.corrcoef(xarr)
+ >>> R1
+ array([[ 1. , 0.99256089, -0.68080986],
+ [ 0.99256089, 1. , -0.76492172],
+ [-0.68080986, -0.76492172, 1. ]])
+
+ If we add another set of variables and observations ``yarr``, we can
+ compute the row-wise Pearson correlation coefficients between the
+ variables in ``xarr`` and ``yarr``.
+
+ >>> yarr = rng.random((3, 3))
+ >>> yarr
+ array([[0.45038594, 0.37079802, 0.92676499],
+ [0.64386512, 0.82276161, 0.4434142 ],
+ [0.22723872, 0.55458479, 0.06381726]])
+ >>> R2 = np.corrcoef(xarr, yarr)
+ >>> R2
+ array([[ 1. , 0.99256089, -0.68080986, 0.75008178, -0.934284 ,
+ -0.99004057],
+ [ 0.99256089, 1. , -0.76492172, 0.82502011, -0.97074098,
+ -0.99981569],
+ [-0.68080986, -0.76492172, 1. , -0.99507202, 0.89721355,
+ 0.77714685],
+ [ 0.75008178, 0.82502011, -0.99507202, 1. , -0.93657855,
+ -0.83571711],
+ [-0.934284 , -0.97074098, 0.89721355, -0.93657855, 1. ,
+ 0.97517215],
+ [-0.99004057, -0.99981569, 0.77714685, -0.83571711, 0.97517215,
+ 1. ]])
+
+ Finally if we use the option ``rowvar=False``, the columns are now
+ being treated as the variables and we will find the column-wise Pearson
+ correlation coefficients between variables in ``xarr`` and ``yarr``.
+
+ >>> R3 = np.corrcoef(xarr, yarr, rowvar=False)
+ >>> R3
+ array([[ 1. , 0.77598074, -0.47458546, -0.75078643, -0.9665554 ,
+ 0.22423734],
+ [ 0.77598074, 1. , -0.92346708, -0.99923895, -0.58826587,
+ -0.44069024],
+ [-0.47458546, -0.92346708, 1. , 0.93773029, 0.23297648,
+ 0.75137473],
+ [-0.75078643, -0.99923895, 0.93773029, 1. , 0.55627469,
+ 0.47536961],
+ [-0.9665554 , -0.58826587, 0.23297648, 0.55627469, 1. ,
+ -0.46666491],
+ [ 0.22423734, -0.44069024, 0.75137473, 0.47536961, -0.46666491,
+ 1. ]])
"""
if bias is not np._NoValue or ddof is not np._NoValue:
diff --git a/numpy/lib/index_tricks.py b/numpy/lib/index_tricks.py
index d528b3e10..cba713ede 100644
--- a/numpy/lib/index_tricks.py
+++ b/numpy/lib/index_tricks.py
@@ -611,8 +611,9 @@ class ndindex:
Parameters
----------
- `*args` : ints
- The size of each dimension of the array.
+ shape : ints, or a single tuple of ints
+ The size of each dimension of the array can be passed as
+ individual parameters or as the elements of a tuple.
See Also
--------
@@ -620,6 +621,7 @@ class ndindex:
Examples
--------
+ # dimensions as individual arguments
>>> for index in np.ndindex(3, 2, 1):
... print(index)
(0, 0, 0)
@@ -629,6 +631,16 @@ class ndindex:
(2, 0, 0)
(2, 1, 0)
+ # same dimensions - but in a tuple (3, 2, 1)
+ >>> for index in np.ndindex((3, 2, 1)):
+ ... print(index)
+ (0, 0, 0)
+ (0, 1, 0)
+ (1, 0, 0)
+ (1, 1, 0)
+ (2, 0, 0)
+ (2, 1, 0)
+
"""
def __init__(self, *shape):
diff --git a/numpy/lib/polynomial.py b/numpy/lib/polynomial.py
index 5a0fa5431..1c124cc0e 100644
--- a/numpy/lib/polynomial.py
+++ b/numpy/lib/polynomial.py
@@ -46,6 +46,12 @@ def poly(seq_of_zeros):
"""
Find the coefficients of a polynomial with the given sequence of roots.
+ .. note::
+ This forms part of the old polynomial API. Since version 1.4, the
+ new polynomial API defined in `numpy.polynomial` is preferred.
+ A summary of the differences can be found in the
+ :doc:`transition guide </reference/routines.polynomials>`.
+
Returns the coefficients of the polynomial whose leading coefficient
is one for the given sequence of zeros (multiple roots must be included
in the sequence as many times as their multiplicity; see Examples).
@@ -168,6 +174,12 @@ def roots(p):
"""
Return the roots of a polynomial with coefficients given in p.
+ .. note::
+ This forms part of the old polynomial API. Since version 1.4, the
+ new polynomial API defined in `numpy.polynomial` is preferred.
+ A summary of the differences can be found in the
+ :doc:`transition guide </reference/routines.polynomials>`.
+
The values in the rank-1 array `p` are coefficients of a polynomial.
If the length of `p` is n+1 then the polynomial is described by::
@@ -258,6 +270,12 @@ def polyint(p, m=1, k=None):
"""
Return an antiderivative (indefinite integral) of a polynomial.
+ .. note::
+ This forms part of the old polynomial API. Since version 1.4, the
+ new polynomial API defined in `numpy.polynomial` is preferred.
+ A summary of the differences can be found in the
+ :doc:`transition guide </reference/routines.polynomials>`.
+
The returned order `m` antiderivative `P` of polynomial `p` satisfies
:math:`\\frac{d^m}{dx^m}P(x) = p(x)` and is defined up to `m - 1`
integration constants `k`. The constants determine the low-order
@@ -357,6 +375,12 @@ def polyder(p, m=1):
"""
Return the derivative of the specified order of a polynomial.
+ .. note::
+ This forms part of the old polynomial API. Since version 1.4, the
+ new polynomial API defined in `numpy.polynomial` is preferred.
+ A summary of the differences can be found in the
+ :doc:`transition guide </reference/routines.polynomials>`.
+
Parameters
----------
p : poly1d or sequence
@@ -431,6 +455,12 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
"""
Least squares polynomial fit.
+ .. note::
+ This forms part of the old polynomial API. Since version 1.4, the
+ new polynomial API defined in `numpy.polynomial` is preferred.
+ A summary of the differences can be found in the
+ :doc:`transition guide </reference/routines.polynomials>`.
+
Fit a polynomial ``p(x) = p[0] * x**deg + ... + p[deg]`` of degree `deg`
to points `(x, y)`. Returns a vector of coefficients `p` that minimises
the squared error in the order `deg`, `deg-1`, ... `0`.
@@ -464,11 +494,12 @@ def polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False):
cov : bool or str, optional
If given and not `False`, return not just the estimate but also its
covariance matrix. By default, the covariance are scaled by
- chi2/sqrt(N-dof), i.e., the weights are presumed to be unreliable
- except in a relative sense and everything is scaled such that the
- reduced chi2 is unity. This scaling is omitted if ``cov='unscaled'``,
- as is relevant for the case that the weights are 1/sigma**2, with
- sigma known to be a reliable estimate of the uncertainty.
+ chi2/dof, where dof = M - (deg + 1), i.e., the weights are presumed
+ to be unreliable except in a relative sense and everything is scaled
+ such that the reduced chi2 is unity. This scaling is omitted if
+ ``cov='unscaled'``, as is relevant for the case that the weights are
+ 1/sigma**2, with sigma known to be a reliable estimate of the
+ uncertainty.
Returns
-------
@@ -667,6 +698,12 @@ def polyval(p, x):
"""
Evaluate a polynomial at specific values.
+ .. note::
+ This forms part of the old polynomial API. Since version 1.4, the
+ new polynomial API defined in `numpy.polynomial` is preferred.
+ A summary of the differences can be found in the
+ :doc:`transition guide </reference/routines.polynomials>`.
+
If `p` is of length N, this function returns the value:
``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]``
@@ -744,6 +781,12 @@ def polyadd(a1, a2):
"""
Find the sum of two polynomials.
+ .. note::
+ This forms part of the old polynomial API. Since version 1.4, the
+ new polynomial API defined in `numpy.polynomial` is preferred.
+ A summary of the differences can be found in the
+ :doc:`transition guide </reference/routines.polynomials>`.
+
Returns the polynomial resulting from the sum of two input polynomials.
Each input must be either a poly1d object or a 1D sequence of polynomial
coefficients, from highest to lowest degree.
@@ -806,6 +849,12 @@ def polysub(a1, a2):
"""
Difference (subtraction) of two polynomials.
+ .. note::
+ This forms part of the old polynomial API. Since version 1.4, the
+ new polynomial API defined in `numpy.polynomial` is preferred.
+ A summary of the differences can be found in the
+ :doc:`transition guide </reference/routines.polynomials>`.
+
Given two polynomials `a1` and `a2`, returns ``a1 - a2``.
`a1` and `a2` can be either array_like sequences of the polynomials'
coefficients (including coefficients equal to zero), or `poly1d` objects.
@@ -854,6 +903,12 @@ def polymul(a1, a2):
"""
Find the product of two polynomials.
+ .. note::
+ This forms part of the old polynomial API. Since version 1.4, the
+ new polynomial API defined in `numpy.polynomial` is preferred.
+ A summary of the differences can be found in the
+ :doc:`transition guide </reference/routines.polynomials>`.
+
Finds the polynomial resulting from the multiplication of the two input
polynomials. Each input must be either a poly1d object or a 1D sequence
of polynomial coefficients, from highest to lowest degree.
@@ -915,6 +970,12 @@ def polydiv(u, v):
"""
Returns the quotient and remainder of polynomial division.
+ .. note::
+ This forms part of the old polynomial API. Since version 1.4, the
+ new polynomial API defined in `numpy.polynomial` is preferred.
+ A summary of the differences can be found in the
+ :doc:`transition guide </reference/routines.polynomials>`.
+
The input arrays are the coefficients (including any coefficients
equal to zero) of the "numerator" (dividend) and "denominator"
(divisor) polynomials, respectively.
@@ -1009,6 +1070,12 @@ class poly1d:
"""
A one-dimensional polynomial class.
+ .. note::
+ This forms part of the old polynomial API. Since version 1.4, the
+ new polynomial API defined in `numpy.polynomial` is preferred.
+ A summary of the differences can be found in the
+ :doc:`transition guide </reference/routines.polynomials>`.
+
A convenience class, used to encapsulate "natural" operations on
polynomials so that said operations may take on their customary
form in code (see Examples).
diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py
index 664bfe6e5..959e63fa2 100644
--- a/numpy/lib/tests/test_io.py
+++ b/numpy/lib/tests/test_io.py
@@ -13,7 +13,8 @@ from tempfile import NamedTemporaryFile
from io import BytesIO, StringIO
from datetime import datetime
import locale
-from multiprocessing import Process
+from multiprocessing import Process, Value
+from ctypes import c_bool
import numpy as np
import numpy.ma as ma
@@ -574,16 +575,29 @@ class TestSaveTxt:
@pytest.mark.slow
@requires_memory(free_bytes=7e9)
def test_large_zip(self):
- def check_large_zip():
- # The test takes at least 6GB of memory, writes a file larger than 4GB
- test_data = np.asarray([np.random.rand(np.random.randint(50,100),4)
- for i in range(800000)], dtype=object)
- with tempdir() as tmpdir:
- np.savez(os.path.join(tmpdir, 'test.npz'), test_data=test_data)
+ def check_large_zip(memoryerror_raised):
+ memoryerror_raised.value = False
+ try:
+ # The test takes at least 6GB of memory, writes a file larger
+ # than 4GB
+ test_data = np.asarray([np.random.rand(
+ np.random.randint(50,100),4)
+ for i in range(800000)], dtype=object)
+ with tempdir() as tmpdir:
+ np.savez(os.path.join(tmpdir, 'test.npz'),
+ test_data=test_data)
+ except MemoryError:
+ memoryerror_raised.value = True
+ raise
# run in a subprocess to ensure memory is released on PyPy, see gh-15775
- p = Process(target=check_large_zip)
+ # Use an object in shared memory to re-raise the MemoryError exception
+ # in our process if needed, see gh-16889
+ memoryerror_raised = Value(c_bool)
+ p = Process(target=check_large_zip, args=(memoryerror_raised,))
p.start()
p.join()
+ if memoryerror_raised.value:
+ raise MemoryError("Child process raised a MemoryError exception")
assert p.exitcode == 0
class LoadTxtBase:
diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py
index 2bb4c78a5..cd7484241 100644
--- a/numpy/lib/twodim_base.py
+++ b/numpy/lib/twodim_base.py
@@ -675,7 +675,7 @@ def histogram2d(x, y, bins=10, range=None, normed=None, weights=None,
>>> fig = plt.figure(figsize=(7, 3))
>>> ax = fig.add_subplot(131, title='imshow: square bins')
- >>> plt.imshow(H, interpolation='nearest', origin='low',
+ >>> plt.imshow(H, interpolation='nearest', origin='lower',
... extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
<matplotlib.image.AxesImage object at 0x...>