summaryrefslogtreecommitdiff
path: root/numpy/lib
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/lib')
-rw-r--r--numpy/lib/arraysetops.py3
-rw-r--r--numpy/lib/format.py4
-rw-r--r--numpy/lib/function_base.py2
-rw-r--r--numpy/lib/npyio.py4
-rw-r--r--numpy/lib/shape_base.py2
-rw-r--r--numpy/lib/src/_compiled_base.c24
-rw-r--r--numpy/lib/tests/test_arraysetops.py4
-rw-r--r--numpy/lib/tests/test_function_base.py22
-rw-r--r--numpy/lib/tests/test_nanfunctions.py4
-rw-r--r--numpy/lib/tests/test_twodim_base.py34
-rw-r--r--numpy/lib/twodim_base.py15
11 files changed, 85 insertions, 33 deletions
diff --git a/numpy/lib/arraysetops.py b/numpy/lib/arraysetops.py
index 5cd535703..691550579 100644
--- a/numpy/lib/arraysetops.py
+++ b/numpy/lib/arraysetops.py
@@ -163,8 +163,7 @@ def unique(ar, return_index=False, return_inverse=False):
ar = ar.flatten()
except AttributeError:
if not return_inverse and not return_index:
- items = sorted(set(ar))
- return np.asarray(items)
+ return np.sort(list(set(ar)))
else:
ar = np.asanyarray(ar).flatten()
diff --git a/numpy/lib/format.py b/numpy/lib/format.py
index 4cfbbe05d..631e92959 100644
--- a/numpy/lib/format.py
+++ b/numpy/lib/format.py
@@ -407,7 +407,7 @@ def write_array(fp, array, version=(1, 0)):
for chunk in numpy.nditer(
array, flags=['external_loop', 'buffered', 'zerosize_ok'],
buffersize=buffersize, order='F'):
- fp.write(chunk.tostring('C'))
+ fp.write(chunk.tobytes('C'))
else:
if isfileobj(fp):
array.tofile(fp)
@@ -415,7 +415,7 @@ def write_array(fp, array, version=(1, 0)):
for chunk in numpy.nditer(
array, flags=['external_loop', 'buffered', 'zerosize_ok'],
buffersize=buffersize, order='C'):
- fp.write(chunk.tostring('C'))
+ fp.write(chunk.tobytes('C'))
def read_array(fp):
diff --git a/numpy/lib/function_base.py b/numpy/lib/function_base.py
index 21a531211..7427545b8 100644
--- a/numpy/lib/function_base.py
+++ b/numpy/lib/function_base.py
@@ -1810,9 +1810,11 @@ def cov(m, y=None, rowvar=1, bias=0, ddof=None):
"ddof must be integer")
# Handles complex arrays too
+ m = np.asarray(m)
if y is None:
dtype = np.result_type(m, np.float64)
else:
+ y = np.asarray(y)
dtype = np.result_type(m, y, np.float64)
X = array(m, ndmin=2, dtype=dtype)
diff --git a/numpy/lib/npyio.py b/numpy/lib/npyio.py
index af259cfef..8cd779f4d 100644
--- a/numpy/lib/npyio.py
+++ b/numpy/lib/npyio.py
@@ -668,6 +668,7 @@ def loadtxt(fname, dtype=float, comments='#', delimiter=None,
The returned array will have at least `ndmin` dimensions.
Otherwise mono-dimensional axes will be squeezed.
Legal values: 0 (default), 1 or 2.
+
.. versionadded:: 1.6.0
Returns
@@ -911,14 +912,17 @@ def savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='',
.. versionadded:: 1.5.0
header : str, optional
String that will be written at the beginning of the file.
+
.. versionadded:: 1.7.0
footer : str, optional
String that will be written at the end of the file.
+
.. versionadded:: 1.7.0
comments : str, optional
String that will be prepended to the ``header`` and ``footer`` strings,
to mark them as comments. Default: '# ', as expected by e.g.
``numpy.loadtxt``.
+
.. versionadded:: 1.7.0
Character separating lines.
diff --git a/numpy/lib/shape_base.py b/numpy/lib/shape_base.py
index 4fdaba349..c299c1976 100644
--- a/numpy/lib/shape_base.py
+++ b/numpy/lib/shape_base.py
@@ -638,7 +638,7 @@ def dsplit(ary, indices_or_sections):
"""
if len(_nx.shape(ary)) < 3:
- raise ValueError('vsplit only works on arrays of 3 or more dimensions')
+ raise ValueError('dsplit only works on arrays of 3 or more dimensions')
return split(ary, indices_or_sections, 2)
def get_array_prepare(*args):
diff --git a/numpy/lib/src/_compiled_base.c b/numpy/lib/src/_compiled_base.c
index 0f238a12a..652268f24 100644
--- a/numpy/lib/src/_compiled_base.c
+++ b/numpy/lib/src/_compiled_base.c
@@ -681,8 +681,15 @@ arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)
slopes[i] = (dy[i + 1] - dy[i])/(dx[i + 1] - dx[i]);
}
for (i = 0; i < lenx; i++) {
- npy_intp j = binary_search(dz[i], dx, lenxp);
+ const double x = dz[i];
+ npy_intp j;
+ if (npy_isnan(x)) {
+ dres[i] = x;
+ continue;
+ }
+
+ j = binary_search(x, dx, lenxp);
if (j == -1) {
dres[i] = lval;
}
@@ -693,7 +700,7 @@ arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)
dres[i] = rval;
}
else {
- dres[i] = slopes[j]*(dz[i] - dx[j]) + dy[j];
+ dres[i] = slopes[j]*(x - dx[j]) + dy[j];
}
}
NPY_END_ALLOW_THREADS;
@@ -702,8 +709,15 @@ arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)
else {
NPY_BEGIN_ALLOW_THREADS;
for (i = 0; i < lenx; i++) {
- npy_intp j = binary_search(dz[i], dx, lenxp);
+ const double x = dz[i];
+ npy_intp j;
+
+ if (npy_isnan(x)) {
+ dres[i] = x;
+ continue;
+ }
+ j = binary_search(x, dx, lenxp);
if (j == -1) {
dres[i] = lval;
}
@@ -714,8 +728,8 @@ arr_interp(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwdict)
dres[i] = rval;
}
else {
- double slope = (dy[j + 1] - dy[j])/(dx[j + 1] - dx[j]);
- dres[i] = slope*(dz[i] - dx[j]) + dy[j];
+ const double slope = (dy[j + 1] - dy[j])/(dx[j + 1] - dx[j]);
+ dres[i] = slope*(x - dx[j]) + dy[j];
}
}
NPY_END_ALLOW_THREADS;
diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py
index 5934ca05a..e44ccd12b 100644
--- a/numpy/lib/tests/test_arraysetops.py
+++ b/numpy/lib/tests/test_arraysetops.py
@@ -65,6 +65,10 @@ class TestSetOps(TestCase):
bb = np.array(list(zip(b, b)), dt)
check_all(aa, bb, i1, i2, dt)
+ # test for ticket #2799
+ aa = [1.+0.j, 1- 1.j, 1]
+ assert_array_equal(np.unique(aa), [ 1.-1.j, 1.+0.j])
+
def test_intersect1d(self):
# unique inputs
a = np.array([5, 7, 1, 2])
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index 82d90311e..3e102cf6a 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -1228,6 +1228,10 @@ class TestCorrCoef(TestCase):
[0.66318558, 0.88157256, 0.71483595, -0.51366032, 1., 0.98317823],
[0.51532523, 0.78052386, 0.83053601, -0.66173113, 0.98317823, 1.]])
+ def test_non_array(self):
+ assert_almost_equal(np.corrcoef([0, 1, 0], [1, 0, 1]),
+ [[1., -1.], [-1., 1.]])
+
def test_simple(self):
assert_almost_equal(corrcoef(self.A), self.res1)
assert_almost_equal(corrcoef(self.A, self.B), self.res2)
@@ -1246,8 +1250,8 @@ class TestCorrCoef(TestCase):
assert_allclose(np.corrcoef(x, y), np.array([[1., -1.j], [1.j, 1.]]))
def test_empty(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RuntimeWarning)
+ with warnings.catch_warnings(record=True):
+ warnings.simplefilter('always', RuntimeWarning)
assert_array_equal(corrcoef(np.array([])), np.nan)
assert_array_equal(corrcoef(np.array([]).reshape(0, 2)),
np.array([]).reshape(0, 0))
@@ -1256,8 +1260,8 @@ class TestCorrCoef(TestCase):
def test_wrong_ddof(self):
x = np.array([[0, 2], [1, 1], [2, 0]]).T
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RuntimeWarning)
+ with warnings.catch_warnings(record=True):
+ warnings.simplefilter('always', RuntimeWarning)
assert_array_equal(corrcoef(x, ddof=5),
np.array([[np.nan, np.nan], [np.nan, np.nan]]))
@@ -1277,8 +1281,8 @@ class TestCov(TestCase):
assert_allclose(cov(x, y), np.array([[1., -1.j], [1.j, 1.]]))
def test_empty(self):
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RuntimeWarning)
+ with warnings.catch_warnings(record=True):
+ warnings.simplefilter('always', RuntimeWarning)
assert_array_equal(cov(np.array([])), np.nan)
assert_array_equal(cov(np.array([]).reshape(0, 2)),
np.array([]).reshape(0, 0))
@@ -1287,8 +1291,8 @@ class TestCov(TestCase):
def test_wrong_ddof(self):
x = np.array([[0, 2], [1, 1], [2, 0]]).T
- with warnings.catch_warnings():
- warnings.simplefilter('ignore', RuntimeWarning)
+ with warnings.catch_warnings(record=True):
+ warnings.simplefilter('always', RuntimeWarning)
assert_array_equal(cov(x, ddof=5),
np.array([[np.inf, -np.inf], [-np.inf, np.inf]]))
@@ -1514,6 +1518,8 @@ class TestInterp(TestCase):
assert_almost_equal(np.interp(x0, x, y), x0)
x0 = np.float64(.3)
assert_almost_equal(np.interp(x0, x, y), x0)
+ x0 = np.nan
+ assert_almost_equal(np.interp(x0, x, y), x0)
def test_zero_dimensional_interpolation_point(self):
x = np.linspace(0, 1, 5)
diff --git a/numpy/lib/tests/test_nanfunctions.py b/numpy/lib/tests/test_nanfunctions.py
index af01a7167..df332dfb1 100644
--- a/numpy/lib/tests/test_nanfunctions.py
+++ b/numpy/lib/tests/test_nanfunctions.py
@@ -130,8 +130,8 @@ class TestNanFunctions_ArgminArgmax(TestCase):
def test_result_values(self):
for f, fcmp in zip(self.nanfuncs, [np.greater, np.less]):
for row in _ndat:
- with warnings.catch_warnings():
- warnings.simplefilter('ignore')
+ with warnings.catch_warnings(record=True):
+ warnings.simplefilter('always')
ind = f(row)
val = row[ind]
# comparing with NaN is tricky as the result
diff --git a/numpy/lib/tests/test_twodim_base.py b/numpy/lib/tests/test_twodim_base.py
index 8d0275a25..022c45bd0 100644
--- a/numpy/lib/tests/test_twodim_base.py
+++ b/numpy/lib/tests/test_twodim_base.py
@@ -275,16 +275,40 @@ class TestTri(TestCase):
assert_array_equal(tri(3, dtype=bool), out.astype(bool))
-def test_tril_triu():
+def test_tril_triu_ndim2():
for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
a = np.ones((2, 2), dtype=dtype)
b = np.tril(a)
c = np.triu(a)
- assert_array_equal(b, [[1, 0], [1, 1]])
- assert_array_equal(c, b.T)
+ yield assert_array_equal, b, [[1, 0], [1, 1]]
+ yield assert_array_equal, c, b.T
# should return the same dtype as the original array
- assert_equal(b.dtype, a.dtype)
- assert_equal(c.dtype, a.dtype)
+ yield assert_equal, b.dtype, a.dtype
+ yield assert_equal, c.dtype, a.dtype
+
+def test_tril_triu_ndim3():
+ for dtype in np.typecodes['AllFloat'] + np.typecodes['AllInteger']:
+ a = np.array([
+ [[1, 1], [1, 1]],
+ [[1, 1], [1, 0]],
+ [[1, 1], [0, 0]],
+ ], dtype=dtype)
+ a_tril_desired = np.array([
+ [[1, 0], [1, 1]],
+ [[1, 0], [1, 0]],
+ [[1, 0], [0, 0]],
+ ], dtype=dtype)
+ a_triu_desired = np.array([
+ [[1, 1], [0, 1]],
+ [[1, 1], [0, 0]],
+ [[1, 1], [0, 0]],
+ ], dtype=dtype)
+ a_triu_observed = np.triu(a)
+ a_tril_observed = np.tril(a)
+ yield assert_array_equal, a_triu_observed, a_triu_desired
+ yield assert_array_equal, a_tril_observed, a_tril_desired
+ yield assert_equal, a_triu_observed.dtype, a.dtype
+ yield assert_equal, a_tril_observed.dtype, a.dtype
def test_mask_indices():
diff --git a/numpy/lib/twodim_base.py b/numpy/lib/twodim_base.py
index 12c0f9bb3..336f23c64 100644
--- a/numpy/lib/twodim_base.py
+++ b/numpy/lib/twodim_base.py
@@ -25,7 +25,7 @@ def fliplr(m):
Parameters
----------
m : array_like
- Input array.
+ Input array, must be at least 2-D.
Returns
-------
@@ -40,8 +40,7 @@ def fliplr(m):
Notes
-----
- Equivalent to A[:,::-1]. Does not require the array to be
- two-dimensional.
+ Equivalent to A[:,::-1]. Requires the array to be at least 2-D.
Examples
--------
@@ -431,7 +430,7 @@ def tril(m, k=0):
"""
m = asanyarray(m)
- out = multiply(tri(m.shape[0], m.shape[1], k=k, dtype=m.dtype), m)
+ out = multiply(tri(m.shape[-2], m.shape[-1], k=k, dtype=m.dtype), m)
return out
@@ -458,7 +457,7 @@ def triu(m, k=0):
"""
m = asanyarray(m)
- out = multiply((1 - tri(m.shape[0], m.shape[1], k - 1, dtype=m.dtype)), m)
+ out = multiply((1 - tri(m.shape[-2], m.shape[-1], k - 1, dtype=m.dtype)), m)
return out
@@ -650,14 +649,14 @@ def histogram2d(x, y, bins=10, range=None, normed=False, weights=None):
>>> fig = plt.figure(figsize=(7, 3))
>>> ax = fig.add_subplot(131)
- >>> ax.set_title('imshow:\nequidistant')
+ >>> ax.set_title('imshow: equidistant')
>>> im = plt.imshow(H, interpolation='nearest', origin='low',
extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
pcolormesh can display exact bin edges:
>>> ax = fig.add_subplot(132)
- >>> ax.set_title('pcolormesh:\nexact bin edges')
+ >>> ax.set_title('pcolormesh: exact bin edges')
>>> X, Y = np.meshgrid(xedges, yedges)
>>> ax.pcolormesh(X, Y, H)
>>> ax.set_aspect('equal')
@@ -665,7 +664,7 @@ def histogram2d(x, y, bins=10, range=None, normed=False, weights=None):
NonUniformImage displays exact bin edges with interpolation:
>>> ax = fig.add_subplot(133)
- >>> ax.set_title('NonUniformImage:\ninterpolated')
+ >>> ax.set_title('NonUniformImage: interpolated')
>>> im = mpl.image.NonUniformImage(ax, interpolation='bilinear')
>>> xcenters = xedges[:-1] + 0.5 * (xedges[1:] - xedges[:-1])
>>> ycenters = yedges[:-1] + 0.5 * (yedges[1:] - yedges[:-1])