"Fossies" - the Fresh Open Source Software Archive

Member "numpy-1.16.4/numpy/lib/tests/test_function_base.py" (27 May 2019, 117817 Bytes) of package /linux/misc/numpy-1.16.4.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the last Fossies "Diffs" side-by-side code changes report for "test_function_base.py": 1.15.4_vs_1.16.0.

    1 from __future__ import division, absolute_import, print_function
    2 
    3 import operator
    4 import warnings
    5 import sys
    6 import decimal
    7 import pytest
    8 
    9 import numpy as np
   10 from numpy import ma
   11 from numpy.testing import (
   12     assert_, assert_equal, assert_array_equal, assert_almost_equal,
   13     assert_array_almost_equal, assert_raises, assert_allclose,
   14     assert_warns, assert_raises_regex, suppress_warnings, HAS_REFCOUNT,
   15     )
   16 import numpy.lib.function_base as nfb
   17 from numpy.random import rand
   18 from numpy.lib import (
   19     add_newdoc_ufunc, angle, average, bartlett, blackman, corrcoef, cov,
   20     delete, diff, digitize, extract, flipud, gradient, hamming, hanning,
   21     i0, insert, interp, kaiser, meshgrid, msort, piecewise, place, rot90,
   22     select, setxor1d, sinc, trapz, trim_zeros, unwrap, unique, vectorize
   23     )
   24 
   25 from numpy.compat import long
   26 
   27 
   28 def get_mat(n):
   29     data = np.arange(n)
   30     data = np.add.outer(data, data)
   31     return data
   32 
   33 
   34 class TestRot90(object):
   35     def test_basic(self):
   36         assert_raises(ValueError, rot90, np.ones(4))
   37         assert_raises(ValueError, rot90, np.ones((2,2,2)), axes=(0,1,2))
   38         assert_raises(ValueError, rot90, np.ones((2,2)), axes=(0,2))
   39         assert_raises(ValueError, rot90, np.ones((2,2)), axes=(1,1))
   40         assert_raises(ValueError, rot90, np.ones((2,2,2)), axes=(-2,1))
   41 
   42         a = [[0, 1, 2],
   43              [3, 4, 5]]
   44         b1 = [[2, 5],
   45               [1, 4],
   46               [0, 3]]
   47         b2 = [[5, 4, 3],
   48               [2, 1, 0]]
   49         b3 = [[3, 0],
   50               [4, 1],
   51               [5, 2]]
   52         b4 = [[0, 1, 2],
   53               [3, 4, 5]]
   54 
   55         for k in range(-3, 13, 4):
   56             assert_equal(rot90(a, k=k), b1)
   57         for k in range(-2, 13, 4):
   58             assert_equal(rot90(a, k=k), b2)
   59         for k in range(-1, 13, 4):
   60             assert_equal(rot90(a, k=k), b3)
   61         for k in range(0, 13, 4):
   62             assert_equal(rot90(a, k=k), b4)
   63 
   64         assert_equal(rot90(rot90(a, axes=(0,1)), axes=(1,0)), a)
   65         assert_equal(rot90(a, k=1, axes=(1,0)), rot90(a, k=-1, axes=(0,1)))
   66 
   67     def test_axes(self):
   68         a = np.ones((50, 40, 3))
   69         assert_equal(rot90(a).shape, (40, 50, 3))
   70         assert_equal(rot90(a, axes=(0,2)), rot90(a, axes=(0,-1)))
   71         assert_equal(rot90(a, axes=(1,2)), rot90(a, axes=(-2,-1)))
   72 
   73     def test_rotation_axes(self):
   74         a = np.arange(8).reshape((2,2,2))
   75 
   76         a_rot90_01 = [[[2, 3],
   77                        [6, 7]],
   78                       [[0, 1],
   79                        [4, 5]]]
   80         a_rot90_12 = [[[1, 3],
   81                        [0, 2]],
   82                       [[5, 7],
   83                        [4, 6]]]
   84         a_rot90_20 = [[[4, 0],
   85                        [6, 2]],
   86                       [[5, 1],
   87                        [7, 3]]]
   88         a_rot90_10 = [[[4, 5],
   89                        [0, 1]],
   90                       [[6, 7],
   91                        [2, 3]]]
   92 
   93         assert_equal(rot90(a, axes=(0, 1)), a_rot90_01)
   94         assert_equal(rot90(a, axes=(1, 0)), a_rot90_10)
   95         assert_equal(rot90(a, axes=(1, 2)), a_rot90_12)
   96 
   97         for k in range(1,5):
   98             assert_equal(rot90(a, k=k, axes=(2, 0)),
   99                          rot90(a_rot90_20, k=k-1, axes=(2, 0)))
  100 
  101 
  102 class TestFlip(object):
  103 
  104     def test_axes(self):
  105         assert_raises(np.AxisError, np.flip, np.ones(4), axis=1)
  106         assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=2)
  107         assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=-3)
  108         assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=(0, 3))
  109 
  110     def test_basic_lr(self):
  111         a = get_mat(4)
  112         b = a[:, ::-1]
  113         assert_equal(np.flip(a, 1), b)
  114         a = [[0, 1, 2],
  115              [3, 4, 5]]
  116         b = [[2, 1, 0],
  117              [5, 4, 3]]
  118         assert_equal(np.flip(a, 1), b)
  119 
  120     def test_basic_ud(self):
  121         a = get_mat(4)
  122         b = a[::-1, :]
  123         assert_equal(np.flip(a, 0), b)
  124         a = [[0, 1, 2],
  125              [3, 4, 5]]
  126         b = [[3, 4, 5],
  127              [0, 1, 2]]
  128         assert_equal(np.flip(a, 0), b)
  129 
  130     def test_3d_swap_axis0(self):
  131         a = np.array([[[0, 1],
  132                        [2, 3]],
  133                       [[4, 5],
  134                        [6, 7]]])
  135 
  136         b = np.array([[[4, 5],
  137                        [6, 7]],
  138                       [[0, 1],
  139                        [2, 3]]])
  140 
  141         assert_equal(np.flip(a, 0), b)
  142 
  143     def test_3d_swap_axis1(self):
  144         a = np.array([[[0, 1],
  145                        [2, 3]],
  146                       [[4, 5],
  147                        [6, 7]]])
  148 
  149         b = np.array([[[2, 3],
  150                        [0, 1]],
  151                       [[6, 7],
  152                        [4, 5]]])
  153 
  154         assert_equal(np.flip(a, 1), b)
  155 
  156     def test_3d_swap_axis2(self):
  157         a = np.array([[[0, 1],
  158                        [2, 3]],
  159                       [[4, 5],
  160                        [6, 7]]])
  161 
  162         b = np.array([[[1, 0],
  163                        [3, 2]],
  164                       [[5, 4],
  165                        [7, 6]]])
  166 
  167         assert_equal(np.flip(a, 2), b)
  168 
  169     def test_4d(self):
  170         a = np.arange(2 * 3 * 4 * 5).reshape(2, 3, 4, 5)
  171         for i in range(a.ndim):
  172             assert_equal(np.flip(a, i),
  173                          np.flipud(a.swapaxes(0, i)).swapaxes(i, 0))
  174 
  175     def test_default_axis(self):
  176         a = np.array([[1, 2, 3],
  177                       [4, 5, 6]])
  178         b = np.array([[6, 5, 4],
  179                       [3, 2, 1]])
  180         assert_equal(np.flip(a), b)
  181 
  182     def test_multiple_axes(self):
  183         a = np.array([[[0, 1],
  184                        [2, 3]],
  185                       [[4, 5],
  186                        [6, 7]]])
  187 
  188         assert_equal(np.flip(a, axis=()), a)
  189 
  190         b = np.array([[[5, 4],
  191                        [7, 6]],
  192                       [[1, 0],
  193                        [3, 2]]])
  194 
  195         assert_equal(np.flip(a, axis=(0, 2)), b)
  196 
  197         c = np.array([[[3, 2],
  198                        [1, 0]],
  199                       [[7, 6],
  200                        [5, 4]]])
  201 
  202         assert_equal(np.flip(a, axis=(1, 2)), c)
  203 
  204 
  205 class TestAny(object):
  206 
  207     def test_basic(self):
  208         y1 = [0, 0, 1, 0]
  209         y2 = [0, 0, 0, 0]
  210         y3 = [1, 0, 1, 0]
  211         assert_(np.any(y1))
  212         assert_(np.any(y3))
  213         assert_(not np.any(y2))
  214 
  215     def test_nd(self):
  216         y1 = [[0, 0, 0], [0, 1, 0], [1, 1, 0]]
  217         assert_(np.any(y1))
  218         assert_array_equal(np.sometrue(y1, axis=0), [1, 1, 0])
  219         assert_array_equal(np.sometrue(y1, axis=1), [0, 1, 1])
  220 
  221 
  222 class TestAll(object):
  223 
  224     def test_basic(self):
  225         y1 = [0, 1, 1, 0]
  226         y2 = [0, 0, 0, 0]
  227         y3 = [1, 1, 1, 1]
  228         assert_(not np.all(y1))
  229         assert_(np.all(y3))
  230         assert_(not np.all(y2))
  231         assert_(np.all(~np.array(y2)))
  232 
  233     def test_nd(self):
  234         y1 = [[0, 0, 1], [0, 1, 1], [1, 1, 1]]
  235         assert_(not np.all(y1))
  236         assert_array_equal(np.alltrue(y1, axis=0), [0, 0, 1])
  237         assert_array_equal(np.alltrue(y1, axis=1), [0, 0, 1])
  238 
  239 
  240 class TestCopy(object):
  241 
  242     def test_basic(self):
  243         a = np.array([[1, 2], [3, 4]])
  244         a_copy = np.copy(a)
  245         assert_array_equal(a, a_copy)
  246         a_copy[0, 0] = 10
  247         assert_equal(a[0, 0], 1)
  248         assert_equal(a_copy[0, 0], 10)
  249 
  250     def test_order(self):
  251         # It turns out that people rely on np.copy() preserving order by
  252         # default; changing this broke scikit-learn:
  253         # github.com/scikit-learn/scikit-learn/commit/7842748cf777412c506a8c0ed28090711d3a3783  # noqa
  254         a = np.array([[1, 2], [3, 4]])
  255         assert_(a.flags.c_contiguous)
  256         assert_(not a.flags.f_contiguous)
  257         a_fort = np.array([[1, 2], [3, 4]], order="F")
  258         assert_(not a_fort.flags.c_contiguous)
  259         assert_(a_fort.flags.f_contiguous)
  260         a_copy = np.copy(a)
  261         assert_(a_copy.flags.c_contiguous)
  262         assert_(not a_copy.flags.f_contiguous)
  263         a_fort_copy = np.copy(a_fort)
  264         assert_(not a_fort_copy.flags.c_contiguous)
  265         assert_(a_fort_copy.flags.f_contiguous)
  266 
  267 
  268 class TestAverage(object):
  269 
  270     def test_basic(self):
  271         y1 = np.array([1, 2, 3])
  272         assert_(average(y1, axis=0) == 2.)
  273         y2 = np.array([1., 2., 3.])
  274         assert_(average(y2, axis=0) == 2.)
  275         y3 = [0., 0., 0.]
  276         assert_(average(y3, axis=0) == 0.)
  277 
  278         y4 = np.ones((4, 4))
  279         y4[0, 1] = 0
  280         y4[1, 0] = 2
  281         assert_almost_equal(y4.mean(0), average(y4, 0))
  282         assert_almost_equal(y4.mean(1), average(y4, 1))
  283 
  284         y5 = rand(5, 5)
  285         assert_almost_equal(y5.mean(0), average(y5, 0))
  286         assert_almost_equal(y5.mean(1), average(y5, 1))
  287 
  288     def test_weights(self):
  289         y = np.arange(10)
  290         w = np.arange(10)
  291         actual = average(y, weights=w)
  292         desired = (np.arange(10) ** 2).sum() * 1. / np.arange(10).sum()
  293         assert_almost_equal(actual, desired)
  294 
  295         y1 = np.array([[1, 2, 3], [4, 5, 6]])
  296         w0 = [1, 2]
  297         actual = average(y1, weights=w0, axis=0)
  298         desired = np.array([3., 4., 5.])
  299         assert_almost_equal(actual, desired)
  300 
  301         w1 = [0, 0, 1]
  302         actual = average(y1, weights=w1, axis=1)
  303         desired = np.array([3., 6.])
  304         assert_almost_equal(actual, desired)
  305 
  306         # This should raise an error. Can we test for that ?
  307         # assert_equal(average(y1, weights=w1), 9./2.)
  308 
  309         # 2D Case
  310         w2 = [[0, 0, 1], [0, 0, 2]]
  311         desired = np.array([3., 6.])
  312         assert_array_equal(average(y1, weights=w2, axis=1), desired)
  313         assert_equal(average(y1, weights=w2), 5.)
  314 
  315         y3 = rand(5).astype(np.float32)
  316         w3 = rand(5).astype(np.float64)
  317 
  318         assert_(np.average(y3, weights=w3).dtype == np.result_type(y3, w3))
  319 
  320     def test_returned(self):
  321         y = np.array([[1, 2, 3], [4, 5, 6]])
  322 
  323         # No weights
  324         avg, scl = average(y, returned=True)
  325         assert_equal(scl, 6.)
  326 
  327         avg, scl = average(y, 0, returned=True)
  328         assert_array_equal(scl, np.array([2., 2., 2.]))
  329 
  330         avg, scl = average(y, 1, returned=True)
  331         assert_array_equal(scl, np.array([3., 3.]))
  332 
  333         # With weights
  334         w0 = [1, 2]
  335         avg, scl = average(y, weights=w0, axis=0, returned=True)
  336         assert_array_equal(scl, np.array([3., 3., 3.]))
  337 
  338         w1 = [1, 2, 3]
  339         avg, scl = average(y, weights=w1, axis=1, returned=True)
  340         assert_array_equal(scl, np.array([6., 6.]))
  341 
  342         w2 = [[0, 0, 1], [1, 2, 3]]
  343         avg, scl = average(y, weights=w2, axis=1, returned=True)
  344         assert_array_equal(scl, np.array([1., 6.]))
  345 
  346     def test_subclasses(self):
  347         class subclass(np.ndarray):
  348             pass
  349         a = np.array([[1,2],[3,4]]).view(subclass)
  350         w = np.array([[1,2],[3,4]]).view(subclass)
  351 
  352         assert_equal(type(np.average(a)), subclass)
  353         assert_equal(type(np.average(a, weights=w)), subclass)
  354 
  355     def test_upcasting(self):
  356         types = [('i4', 'i4', 'f8'), ('i4', 'f4', 'f8'), ('f4', 'i4', 'f8'),
  357                  ('f4', 'f4', 'f4'), ('f4', 'f8', 'f8')]
  358         for at, wt, rt in types:
  359             a = np.array([[1,2],[3,4]], dtype=at)
  360             w = np.array([[1,2],[3,4]], dtype=wt)
  361             assert_equal(np.average(a, weights=w).dtype, np.dtype(rt))
  362 
  363     def test_object_dtype(self):
  364         a = np.array([decimal.Decimal(x) for x in range(10)])
  365         w = np.array([decimal.Decimal(1) for _ in range(10)])
  366         w /= w.sum()
  367         assert_almost_equal(a.mean(0), average(a, weights=w))
  368 
  369 class TestSelect(object):
  370     choices = [np.array([1, 2, 3]),
  371                np.array([4, 5, 6]),
  372                np.array([7, 8, 9])]
  373     conditions = [np.array([False, False, False]),
  374                   np.array([False, True, False]),
  375                   np.array([False, False, True])]
  376 
  377     def _select(self, cond, values, default=0):
  378         output = []
  379         for m in range(len(cond)):
  380             output += [V[m] for V, C in zip(values, cond) if C[m]] or [default]
  381         return output
  382 
  383     def test_basic(self):
  384         choices = self.choices
  385         conditions = self.conditions
  386         assert_array_equal(select(conditions, choices, default=15),
  387                            self._select(conditions, choices, default=15))
  388 
  389         assert_equal(len(choices), 3)
  390         assert_equal(len(conditions), 3)
  391 
  392     def test_broadcasting(self):
  393         conditions = [np.array(True), np.array([False, True, False])]
  394         choices = [1, np.arange(12).reshape(4, 3)]
  395         assert_array_equal(select(conditions, choices), np.ones((4, 3)))
  396         # default can broadcast too:
  397         assert_equal(select([True], [0], default=[0]).shape, (1,))
  398 
  399     def test_return_dtype(self):
  400         assert_equal(select(self.conditions, self.choices, 1j).dtype,
  401                      np.complex_)
  402         # But the conditions need to be stronger then the scalar default
  403         # if it is scalar.
  404         choices = [choice.astype(np.int8) for choice in self.choices]
  405         assert_equal(select(self.conditions, choices).dtype, np.int8)
  406 
  407         d = np.array([1, 2, 3, np.nan, 5, 7])
  408         m = np.isnan(d)
  409         assert_equal(select([m], [d]), [0, 0, 0, np.nan, 0, 0])
  410 
  411     def test_deprecated_empty(self):
  412         with warnings.catch_warnings(record=True):
  413             warnings.simplefilter("always")
  414             assert_equal(select([], [], 3j), 3j)
  415 
  416         with warnings.catch_warnings():
  417             warnings.simplefilter("always")
  418             assert_warns(DeprecationWarning, select, [], [])
  419             warnings.simplefilter("error")
  420             assert_raises(DeprecationWarning, select, [], [])
  421 
  422     def test_non_bool_deprecation(self):
  423         choices = self.choices
  424         conditions = self.conditions[:]
  425         with warnings.catch_warnings():
  426             warnings.filterwarnings("always")
  427             conditions[0] = conditions[0].astype(np.int_)
  428             assert_warns(DeprecationWarning, select, conditions, choices)
  429             conditions[0] = conditions[0].astype(np.uint8)
  430             assert_warns(DeprecationWarning, select, conditions, choices)
  431             warnings.filterwarnings("error")
  432             assert_raises(DeprecationWarning, select, conditions, choices)
  433 
  434     def test_many_arguments(self):
  435         # This used to be limited by NPY_MAXARGS == 32
  436         conditions = [np.array([False])] * 100
  437         choices = [np.array([1])] * 100
  438         select(conditions, choices)
  439 
  440 
  441 class TestInsert(object):
  442 
  443     def test_basic(self):
  444         a = [1, 2, 3]
  445         assert_equal(insert(a, 0, 1), [1, 1, 2, 3])
  446         assert_equal(insert(a, 3, 1), [1, 2, 3, 1])
  447         assert_equal(insert(a, [1, 1, 1], [1, 2, 3]), [1, 1, 2, 3, 2, 3])
  448         assert_equal(insert(a, 1, [1, 2, 3]), [1, 1, 2, 3, 2, 3])
  449         assert_equal(insert(a, [1, -1, 3], 9), [1, 9, 2, 9, 3, 9])
  450         assert_equal(insert(a, slice(-1, None, -1), 9), [9, 1, 9, 2, 9, 3])
  451         assert_equal(insert(a, [-1, 1, 3], [7, 8, 9]), [1, 8, 2, 7, 3, 9])
  452         b = np.array([0, 1], dtype=np.float64)
  453         assert_equal(insert(b, 0, b[0]), [0., 0., 1.])
  454         assert_equal(insert(b, [], []), b)
  455         # Bools will be treated differently in the future:
  456         # assert_equal(insert(a, np.array([True]*4), 9), [9, 1, 9, 2, 9, 3, 9])
  457         with warnings.catch_warnings(record=True) as w:
  458             warnings.filterwarnings('always', '', FutureWarning)
  459             assert_equal(
  460                 insert(a, np.array([True] * 4), 9), [1, 9, 9, 9, 9, 2, 3])
  461             assert_(w[0].category is FutureWarning)
  462 
  463     def test_multidim(self):
  464         a = [[1, 1, 1]]
  465         r = [[2, 2, 2],
  466              [1, 1, 1]]
  467         assert_equal(insert(a, 0, [1]), [1, 1, 1, 1])
  468         assert_equal(insert(a, 0, [2, 2, 2], axis=0), r)
  469         assert_equal(insert(a, 0, 2, axis=0), r)
  470         assert_equal(insert(a, 2, 2, axis=1), [[1, 1, 2, 1]])
  471 
  472         a = np.array([[1, 1], [2, 2], [3, 3]])
  473         b = np.arange(1, 4).repeat(3).reshape(3, 3)
  474         c = np.concatenate(
  475             (a[:, 0:1], np.arange(1, 4).repeat(3).reshape(3, 3).T,
  476              a[:, 1:2]), axis=1)
  477         assert_equal(insert(a, [1], [[1], [2], [3]], axis=1), b)
  478         assert_equal(insert(a, [1], [1, 2, 3], axis=1), c)
  479         # scalars behave differently, in this case exactly opposite:
  480         assert_equal(insert(a, 1, [1, 2, 3], axis=1), b)
  481         assert_equal(insert(a, 1, [[1], [2], [3]], axis=1), c)
  482 
  483         a = np.arange(4).reshape(2, 2)
  484         assert_equal(insert(a[:, :1], 1, a[:, 1], axis=1), a)
  485         assert_equal(insert(a[:1,:], 1, a[1,:], axis=0), a)
  486 
  487         # negative axis value
  488         a = np.arange(24).reshape((2, 3, 4))
  489         assert_equal(insert(a, 1, a[:,:, 3], axis=-1),
  490                      insert(a, 1, a[:,:, 3], axis=2))
  491         assert_equal(insert(a, 1, a[:, 2,:], axis=-2),
  492                      insert(a, 1, a[:, 2,:], axis=1))
  493 
  494         # invalid axis value
  495         assert_raises(np.AxisError, insert, a, 1, a[:, 2, :], axis=3)
  496         assert_raises(np.AxisError, insert, a, 1, a[:, 2, :], axis=-4)
  497 
  498         # negative axis value
  499         a = np.arange(24).reshape((2, 3, 4))
  500         assert_equal(insert(a, 1, a[:, :, 3], axis=-1),
  501                      insert(a, 1, a[:, :, 3], axis=2))
  502         assert_equal(insert(a, 1, a[:, 2, :], axis=-2),
  503                      insert(a, 1, a[:, 2, :], axis=1))
  504 
  505     def test_0d(self):
  506         # This is an error in the future
  507         a = np.array(1)
  508         with warnings.catch_warnings(record=True) as w:
  509             warnings.filterwarnings('always', '', DeprecationWarning)
  510             assert_equal(insert(a, [], 2, axis=0), np.array(2))
  511             assert_(w[0].category is DeprecationWarning)
  512 
  513     def test_subclass(self):
  514         class SubClass(np.ndarray):
  515             pass
  516         a = np.arange(10).view(SubClass)
  517         assert_(isinstance(np.insert(a, 0, [0]), SubClass))
  518         assert_(isinstance(np.insert(a, [], []), SubClass))
  519         assert_(isinstance(np.insert(a, [0, 1], [1, 2]), SubClass))
  520         assert_(isinstance(np.insert(a, slice(1, 2), [1, 2]), SubClass))
  521         assert_(isinstance(np.insert(a, slice(1, -2, -1), []), SubClass))
  522         # This is an error in the future:
  523         a = np.array(1).view(SubClass)
  524         assert_(isinstance(np.insert(a, 0, [0]), SubClass))
  525 
  526     def test_index_array_copied(self):
  527         x = np.array([1, 1, 1])
  528         np.insert([0, 1, 2], x, [3, 4, 5])
  529         assert_equal(x, np.array([1, 1, 1]))
  530 
  531     def test_structured_array(self):
  532         a = np.array([(1, 'a'), (2, 'b'), (3, 'c')],
  533                      dtype=[('foo', 'i'), ('bar', 'a1')])
  534         val = (4, 'd')
  535         b = np.insert(a, 0, val)
  536         assert_array_equal(b[0], np.array(val, dtype=b.dtype))
  537         val = [(4, 'd')] * 2
  538         b = np.insert(a, [0, 2], val)
  539         assert_array_equal(b[[0, 3]], np.array(val, dtype=b.dtype))
  540 
  541 
  542 class TestAmax(object):
  543 
  544     def test_basic(self):
  545         a = [3, 4, 5, 10, -3, -5, 6.0]
  546         assert_equal(np.amax(a), 10.0)
  547         b = [[3, 6.0, 9.0],
  548              [4, 10.0, 5.0],
  549              [8, 3.0, 2.0]]
  550         assert_equal(np.amax(b, axis=0), [8.0, 10.0, 9.0])
  551         assert_equal(np.amax(b, axis=1), [9.0, 10.0, 8.0])
  552 
  553 
  554 class TestAmin(object):
  555 
  556     def test_basic(self):
  557         a = [3, 4, 5, 10, -3, -5, 6.0]
  558         assert_equal(np.amin(a), -5.0)
  559         b = [[3, 6.0, 9.0],
  560              [4, 10.0, 5.0],
  561              [8, 3.0, 2.0]]
  562         assert_equal(np.amin(b, axis=0), [3.0, 3.0, 2.0])
  563         assert_equal(np.amin(b, axis=1), [3.0, 4.0, 2.0])
  564 
  565 
  566 class TestPtp(object):
  567 
  568     def test_basic(self):
  569         a = np.array([3, 4, 5, 10, -3, -5, 6.0])
  570         assert_equal(a.ptp(axis=0), 15.0)
  571         b = np.array([[3, 6.0, 9.0],
  572                       [4, 10.0, 5.0],
  573                       [8, 3.0, 2.0]])
  574         assert_equal(b.ptp(axis=0), [5.0, 7.0, 7.0])
  575         assert_equal(b.ptp(axis=-1), [6.0, 6.0, 6.0])
  576 
  577         assert_equal(b.ptp(axis=0, keepdims=True), [[5.0, 7.0, 7.0]])
  578         assert_equal(b.ptp(axis=(0,1), keepdims=True), [[8.0]])
  579 
  580 
  581 class TestCumsum(object):
  582 
  583     def test_basic(self):
  584         ba = [1, 2, 10, 11, 6, 5, 4]
  585         ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
  586         for ctype in [np.int8, np.uint8, np.int16, np.uint16, np.int32,
  587                       np.uint32, np.float32, np.float64, np.complex64,
  588                       np.complex128]:
  589             a = np.array(ba, ctype)
  590             a2 = np.array(ba2, ctype)
  591 
  592             tgt = np.array([1, 3, 13, 24, 30, 35, 39], ctype)
  593             assert_array_equal(np.cumsum(a, axis=0), tgt)
  594 
  595             tgt = np.array(
  596                 [[1, 2, 3, 4], [6, 8, 10, 13], [16, 11, 14, 18]], ctype)
  597             assert_array_equal(np.cumsum(a2, axis=0), tgt)
  598 
  599             tgt = np.array(
  600                 [[1, 3, 6, 10], [5, 11, 18, 27], [10, 13, 17, 22]], ctype)
  601             assert_array_equal(np.cumsum(a2, axis=1), tgt)
  602 
  603 
  604 class TestProd(object):
  605 
  606     def test_basic(self):
  607         ba = [1, 2, 10, 11, 6, 5, 4]
  608         ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
  609         for ctype in [np.int16, np.uint16, np.int32, np.uint32,
  610                       np.float32, np.float64, np.complex64, np.complex128]:
  611             a = np.array(ba, ctype)
  612             a2 = np.array(ba2, ctype)
  613             if ctype in ['1', 'b']:
  614                 assert_raises(ArithmeticError, np.prod, a)
  615                 assert_raises(ArithmeticError, np.prod, a2, 1)
  616             else:
  617                 assert_equal(a.prod(axis=0), 26400)
  618                 assert_array_equal(a2.prod(axis=0),
  619                                    np.array([50, 36, 84, 180], ctype))
  620                 assert_array_equal(a2.prod(axis=-1),
  621                                    np.array([24, 1890, 600], ctype))
  622 
  623 
  624 class TestCumprod(object):
  625 
  626     def test_basic(self):
  627         ba = [1, 2, 10, 11, 6, 5, 4]
  628         ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
  629         for ctype in [np.int16, np.uint16, np.int32, np.uint32,
  630                       np.float32, np.float64, np.complex64, np.complex128]:
  631             a = np.array(ba, ctype)
  632             a2 = np.array(ba2, ctype)
  633             if ctype in ['1', 'b']:
  634                 assert_raises(ArithmeticError, np.cumprod, a)
  635                 assert_raises(ArithmeticError, np.cumprod, a2, 1)
  636                 assert_raises(ArithmeticError, np.cumprod, a)
  637             else:
  638                 assert_array_equal(np.cumprod(a, axis=-1),
  639                                    np.array([1, 2, 20, 220,
  640                                              1320, 6600, 26400], ctype))
  641                 assert_array_equal(np.cumprod(a2, axis=0),
  642                                    np.array([[1, 2, 3, 4],
  643                                              [5, 12, 21, 36],
  644                                              [50, 36, 84, 180]], ctype))
  645                 assert_array_equal(np.cumprod(a2, axis=-1),
  646                                    np.array([[1, 2, 6, 24],
  647                                              [5, 30, 210, 1890],
  648                                              [10, 30, 120, 600]], ctype))
  649 
  650 
  651 class TestDiff(object):
  652 
  653     def test_basic(self):
  654         x = [1, 4, 6, 7, 12]
  655         out = np.array([3, 2, 1, 5])
  656         out2 = np.array([-1, -1, 4])
  657         out3 = np.array([0, 5])
  658         assert_array_equal(diff(x), out)
  659         assert_array_equal(diff(x, n=2), out2)
  660         assert_array_equal(diff(x, n=3), out3)
  661 
  662         x = [1.1, 2.2, 3.0, -0.2, -0.1]
  663         out = np.array([1.1, 0.8, -3.2, 0.1])
  664         assert_almost_equal(diff(x), out)
  665 
  666         x = [True, True, False, False]
  667         out = np.array([False, True, False])
  668         out2 = np.array([True, True])
  669         assert_array_equal(diff(x), out)
  670         assert_array_equal(diff(x, n=2), out2)
  671 
  672     def test_axis(self):
  673         x = np.zeros((10, 20, 30))
  674         x[:, 1::2, :] = 1
  675         exp = np.ones((10, 19, 30))
  676         exp[:, 1::2, :] = -1
  677         assert_array_equal(diff(x), np.zeros((10, 20, 29)))
  678         assert_array_equal(diff(x, axis=-1), np.zeros((10, 20, 29)))
  679         assert_array_equal(diff(x, axis=0), np.zeros((9, 20, 30)))
  680         assert_array_equal(diff(x, axis=1), exp)
  681         assert_array_equal(diff(x, axis=-2), exp)
  682         assert_raises(np.AxisError, diff, x, axis=3)
  683         assert_raises(np.AxisError, diff, x, axis=-4)
  684 
  685     def test_nd(self):
  686         x = 20 * rand(10, 20, 30)
  687         out1 = x[:, :, 1:] - x[:, :, :-1]
  688         out2 = out1[:, :, 1:] - out1[:, :, :-1]
  689         out3 = x[1:, :, :] - x[:-1, :, :]
  690         out4 = out3[1:, :, :] - out3[:-1, :, :]
  691         assert_array_equal(diff(x), out1)
  692         assert_array_equal(diff(x, n=2), out2)
  693         assert_array_equal(diff(x, axis=0), out3)
  694         assert_array_equal(diff(x, n=2, axis=0), out4)
  695 
  696     def test_n(self):
  697         x = list(range(3))
  698         assert_raises(ValueError, diff, x, n=-1)
  699         output = [diff(x, n=n) for n in range(1, 5)]
  700         expected = [[1, 1], [0], [], []]
  701         assert_(diff(x, n=0) is x)
  702         for n, (expected, out) in enumerate(zip(expected, output), start=1):
  703             assert_(type(out) is np.ndarray)
  704             assert_array_equal(out, expected)
  705             assert_equal(out.dtype, np.int_)
  706             assert_equal(len(out), max(0, len(x) - n))
  707 
  708     def test_times(self):
  709         x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)
  710         expected = [
  711             np.array([1, 1], dtype='timedelta64[D]'),
  712             np.array([0], dtype='timedelta64[D]'),
  713         ]
  714         expected.extend([np.array([], dtype='timedelta64[D]')] * 3)
  715         for n, exp in enumerate(expected, start=1):
  716             out = diff(x, n=n)
  717             assert_array_equal(out, exp)
  718             assert_equal(out.dtype, exp.dtype)
  719 
  720     def test_subclass(self):
  721         x = ma.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]],
  722                      mask=[[False, False], [True, False],
  723                            [False, True], [True, True], [False, False]])
  724         out = diff(x)
  725         assert_array_equal(out.data, [[1], [1], [1], [1], [1]])
  726         assert_array_equal(out.mask, [[False], [True],
  727                                       [True], [True], [False]])
  728         assert_(type(out) is type(x))
  729 
  730         out3 = diff(x, n=3)
  731         assert_array_equal(out3.data, [[], [], [], [], []])
  732         assert_array_equal(out3.mask, [[], [], [], [], []])
  733         assert_(type(out3) is type(x))
  734 
  735     def test_prepend(self):
  736         x = np.arange(5) + 1
  737         assert_array_equal(diff(x, prepend=0), np.ones(5))
  738         assert_array_equal(diff(x, prepend=[0]), np.ones(5))
  739         assert_array_equal(np.cumsum(np.diff(x, prepend=0)), x)
  740         assert_array_equal(diff(x, prepend=[-1, 0]), np.ones(6))
  741 
  742         x = np.arange(4).reshape(2, 2)
  743         result = np.diff(x, axis=1, prepend=0)
  744         expected = [[0, 1], [2, 1]]
  745         assert_array_equal(result, expected)
  746         result = np.diff(x, axis=1, prepend=[[0], [0]])
  747         assert_array_equal(result, expected)
  748 
  749         result = np.diff(x, axis=0, prepend=0)
  750         expected = [[0, 1], [2, 2]]
  751         assert_array_equal(result, expected)
  752         result = np.diff(x, axis=0, prepend=[[0, 0]])
  753         assert_array_equal(result, expected)
  754 
  755         assert_raises(ValueError, np.diff, x, prepend=np.zeros((3,3)))
  756 
  757         assert_raises(np.AxisError, diff, x, prepend=0, axis=3)
  758 
  759     def test_append(self):
  760         x = np.arange(5)
  761         result = diff(x, append=0)
  762         expected = [1, 1, 1, 1, -4]
  763         assert_array_equal(result, expected)
  764         result = diff(x, append=[0])
  765         assert_array_equal(result, expected)
  766         result = diff(x, append=[0, 2])
  767         expected = expected + [2]
  768         assert_array_equal(result, expected)
  769 
  770         x = np.arange(4).reshape(2, 2)
  771         result = np.diff(x, axis=1, append=0)
  772         expected = [[1, -1], [1, -3]]
  773         assert_array_equal(result, expected)
  774         result = np.diff(x, axis=1, append=[[0], [0]])
  775         assert_array_equal(result, expected)
  776 
  777         result = np.diff(x, axis=0, append=0)
  778         expected = [[2, 2], [-2, -3]]
  779         assert_array_equal(result, expected)
  780         result = np.diff(x, axis=0, append=[[0, 0]])
  781         assert_array_equal(result, expected)
  782 
  783         assert_raises(ValueError, np.diff, x, append=np.zeros((3,3)))
  784 
  785         assert_raises(np.AxisError, diff, x, append=0, axis=3)
  786 
  787 
  788 class TestDelete(object):
  789 
  790     def setup(self):
  791         self.a = np.arange(5)
  792         self.nd_a = np.arange(5).repeat(2).reshape(1, 5, 2)
  793 
  794     def _check_inverse_of_slicing(self, indices):
  795         a_del = delete(self.a, indices)
  796         nd_a_del = delete(self.nd_a, indices, axis=1)
  797         msg = 'Delete failed for obj: %r' % indices
  798         # NOTE: The cast should be removed after warning phase for bools
  799         if not isinstance(indices, (slice, int, long, np.integer)):
  800             indices = np.asarray(indices, dtype=np.intp)
  801             indices = indices[(indices >= 0) & (indices < 5)]
  802         assert_array_equal(setxor1d(a_del, self.a[indices, ]), self.a,
  803                            err_msg=msg)
  804         xor = setxor1d(nd_a_del[0,:, 0], self.nd_a[0, indices, 0])
  805         assert_array_equal(xor, self.nd_a[0,:, 0], err_msg=msg)
  806 
  807     def test_slices(self):
  808         lims = [-6, -2, 0, 1, 2, 4, 5]
  809         steps = [-3, -1, 1, 3]
  810         for start in lims:
  811             for stop in lims:
  812                 for step in steps:
  813                     s = slice(start, stop, step)
  814                     self._check_inverse_of_slicing(s)
  815 
  816     def test_fancy(self):
  817         # Deprecation/FutureWarning tests should be kept after change.
  818         self._check_inverse_of_slicing(np.array([[0, 1], [2, 1]]))
  819         with warnings.catch_warnings():
  820             warnings.filterwarnings('error', category=DeprecationWarning)
  821             assert_raises(DeprecationWarning, delete, self.a, [100])
  822             assert_raises(DeprecationWarning, delete, self.a, [-100])
  823         with warnings.catch_warnings(record=True) as w:
  824             warnings.filterwarnings('always', category=FutureWarning)
  825             self._check_inverse_of_slicing([0, -1, 2, 2])
  826             obj = np.array([True, False, False], dtype=bool)
  827             self._check_inverse_of_slicing(obj)
  828             assert_(w[0].category is FutureWarning)
  829             assert_(w[1].category is FutureWarning)
  830 
  831     def test_single(self):
  832         self._check_inverse_of_slicing(0)
  833         self._check_inverse_of_slicing(-4)
  834 
  835     def test_0d(self):
  836         a = np.array(1)
  837         with warnings.catch_warnings(record=True) as w:
  838             warnings.filterwarnings('always', '', DeprecationWarning)
  839             assert_equal(delete(a, [], axis=0), a)
  840             assert_(w[0].category is DeprecationWarning)
  841 
  842     def test_subclass(self):
  843         class SubClass(np.ndarray):
  844             pass
  845         a = self.a.view(SubClass)
  846         assert_(isinstance(delete(a, 0), SubClass))
  847         assert_(isinstance(delete(a, []), SubClass))
  848         assert_(isinstance(delete(a, [0, 1]), SubClass))
  849         assert_(isinstance(delete(a, slice(1, 2)), SubClass))
  850         assert_(isinstance(delete(a, slice(1, -2)), SubClass))
  851 
  852     def test_array_order_preserve(self):
  853         # See gh-7113
  854         k = np.arange(10).reshape(2, 5, order='F')
  855         m = delete(k, slice(60, None), axis=1)
  856 
  857         # 'k' is Fortran ordered, and 'm' should have the
  858         # same ordering as 'k' and NOT become C ordered
  859         assert_equal(m.flags.c_contiguous, k.flags.c_contiguous)
  860         assert_equal(m.flags.f_contiguous, k.flags.f_contiguous)
  861 
  862 
  863 class TestGradient(object):
  864 
  865     def test_basic(self):
  866         v = [[1, 1], [3, 4]]
  867         x = np.array(v)
  868         dx = [np.array([[2., 3.], [2., 3.]]),
  869               np.array([[0., 0.], [1., 1.]])]
  870         assert_array_equal(gradient(x), dx)
  871         assert_array_equal(gradient(v), dx)
  872 
  873     def test_args(self):
  874         dx = np.cumsum(np.ones(5))
  875         dx_uneven = [1., 2., 5., 9., 11.]
  876         f_2d = np.arange(25).reshape(5, 5)
  877 
  878         # distances must be scalars or have size equal to gradient[axis]
  879         gradient(np.arange(5), 3.)
  880         gradient(np.arange(5), np.array(3.))
  881         gradient(np.arange(5), dx)
  882         # dy is set equal to dx because scalar
  883         gradient(f_2d, 1.5)
  884         gradient(f_2d, np.array(1.5))
  885 
  886         gradient(f_2d, dx_uneven, dx_uneven)
  887         # mix between even and uneven spaces and
  888         # mix between scalar and vector
  889         gradient(f_2d, dx, 2)
  890 
  891         # 2D but axis specified
  892         gradient(f_2d, dx, axis=1)
  893 
  894         # 2d coordinate arguments are not yet allowed
  895         assert_raises_regex(ValueError, '.*scalars or 1d',
  896             gradient, f_2d, np.stack([dx]*2, axis=-1), 1)
  897 
  898     def test_badargs(self):
  899         f_2d = np.arange(25).reshape(5, 5)
  900         x = np.cumsum(np.ones(5))
  901 
  902         # wrong sizes
  903         assert_raises(ValueError, gradient, f_2d, x, np.ones(2))
  904         assert_raises(ValueError, gradient, f_2d, 1, np.ones(2))
  905         assert_raises(ValueError, gradient, f_2d, np.ones(2), np.ones(2))
  906         # wrong number of arguments
  907         assert_raises(TypeError, gradient, f_2d, x)
  908         assert_raises(TypeError, gradient, f_2d, x, axis=(0,1))
  909         assert_raises(TypeError, gradient, f_2d, x, x, x)
  910         assert_raises(TypeError, gradient, f_2d, 1, 1, 1)
  911         assert_raises(TypeError, gradient, f_2d, x, x, axis=1)
  912         assert_raises(TypeError, gradient, f_2d, 1, 1, axis=1)
  913 
  914     def test_datetime64(self):
  915         # Make sure gradient() can handle special types like datetime64
  916         x = np.array(
  917             ['1910-08-16', '1910-08-11', '1910-08-10', '1910-08-12',
  918              '1910-10-12', '1910-12-12', '1912-12-12'],
  919             dtype='datetime64[D]')
  920         dx = np.array(
  921             [-5, -3, 0, 31, 61, 396, 731],
  922             dtype='timedelta64[D]')
  923         assert_array_equal(gradient(x), dx)
  924         assert_(dx.dtype == np.dtype('timedelta64[D]'))
  925 
  926     def test_masked(self):
  927         # Make sure that gradient supports subclasses like masked arrays
  928         x = np.ma.array([[1, 1], [3, 4]],
  929                         mask=[[False, False], [False, False]])
  930         out = gradient(x)[0]
  931         assert_equal(type(out), type(x))
  932         # And make sure that the output and input don't have aliased mask
  933         # arrays
  934         assert_(x.mask is not out.mask)
  935         # Also check that edge_order=2 doesn't alter the original mask
  936         x2 = np.ma.arange(5)
  937         x2[2] = np.ma.masked
  938         np.gradient(x2, edge_order=2)
  939         assert_array_equal(x2.mask, [False, False, True, False, False])
  940 
  941     def test_second_order_accurate(self):
  942         # Testing that the relative numerical error is less that 3% for
  943         # this example problem. This corresponds to second order
  944         # accurate finite differences for all interior and boundary
  945         # points.
  946         x = np.linspace(0, 1, 10)
  947         dx = x[1] - x[0]
  948         y = 2 * x ** 3 + 4 * x ** 2 + 2 * x
  949         analytical = 6 * x ** 2 + 8 * x + 2
  950         num_error = np.abs((np.gradient(y, dx, edge_order=2) / analytical) - 1)
  951         assert_(np.all(num_error < 0.03) == True)
  952 
  953         # test with unevenly spaced
  954         np.random.seed(0)
  955         x = np.sort(np.random.random(10))
  956         y = 2 * x ** 3 + 4 * x ** 2 + 2 * x
  957         analytical = 6 * x ** 2 + 8 * x + 2
  958         num_error = np.abs((np.gradient(y, x, edge_order=2) / analytical) - 1)
  959         assert_(np.all(num_error < 0.03) == True)
  960 
  961     def test_spacing(self):
  962         f = np.array([0, 2., 3., 4., 5., 5.])
  963         f = np.tile(f, (6,1)) + f.reshape(-1, 1)
  964         x_uneven = np.array([0., 0.5, 1., 3., 5., 7.])
  965         x_even = np.arange(6.)
  966 
  967         fdx_even_ord1 = np.tile([2., 1.5, 1., 1., 0.5, 0.], (6,1))
  968         fdx_even_ord2 = np.tile([2.5, 1.5, 1., 1., 0.5, -0.5], (6,1))
  969         fdx_uneven_ord1 = np.tile([4., 3., 1.7, 0.5, 0.25, 0.], (6,1))
  970         fdx_uneven_ord2 = np.tile([5., 3., 1.7, 0.5, 0.25, -0.25], (6,1))
  971 
  972         # evenly spaced
  973         for edge_order, exp_res in [(1, fdx_even_ord1), (2, fdx_even_ord2)]:
  974             res1 = gradient(f, 1., axis=(0,1), edge_order=edge_order)
  975             res2 = gradient(f, x_even, x_even,
  976                             axis=(0,1), edge_order=edge_order)
  977             res3 = gradient(f, x_even, x_even,
  978                             axis=None, edge_order=edge_order)
  979             assert_array_equal(res1, res2)
  980             assert_array_equal(res2, res3)
  981             assert_almost_equal(res1[0], exp_res.T)
  982             assert_almost_equal(res1[1], exp_res)
  983 
  984             res1 = gradient(f, 1., axis=0, edge_order=edge_order)
  985             res2 = gradient(f, x_even, axis=0, edge_order=edge_order)
  986             assert_(res1.shape == res2.shape)
  987             assert_almost_equal(res2, exp_res.T)
  988 
  989             res1 = gradient(f, 1., axis=1, edge_order=edge_order)
  990             res2 = gradient(f, x_even, axis=1, edge_order=edge_order)
  991             assert_(res1.shape == res2.shape)
  992             assert_array_equal(res2, exp_res)
  993 
  994         # unevenly spaced
  995         for edge_order, exp_res in [(1, fdx_uneven_ord1), (2, fdx_uneven_ord2)]:
  996             res1 = gradient(f, x_uneven, x_uneven,
  997                             axis=(0,1), edge_order=edge_order)
  998             res2 = gradient(f, x_uneven, x_uneven,
  999                             axis=None, edge_order=edge_order)
 1000             assert_array_equal(res1, res2)
 1001             assert_almost_equal(res1[0], exp_res.T)
 1002             assert_almost_equal(res1[1], exp_res)
 1003 
 1004             res1 = gradient(f, x_uneven, axis=0, edge_order=edge_order)
 1005             assert_almost_equal(res1, exp_res.T)
 1006 
 1007             res1 = gradient(f, x_uneven, axis=1, edge_order=edge_order)
 1008             assert_almost_equal(res1, exp_res)
 1009 
 1010         # mixed
 1011         res1 = gradient(f, x_even, x_uneven, axis=(0,1), edge_order=1)
 1012         res2 = gradient(f, x_uneven, x_even, axis=(1,0), edge_order=1)
 1013         assert_array_equal(res1[0], res2[1])
 1014         assert_array_equal(res1[1], res2[0])
 1015         assert_almost_equal(res1[0], fdx_even_ord1.T)
 1016         assert_almost_equal(res1[1], fdx_uneven_ord1)
 1017 
 1018         res1 = gradient(f, x_even, x_uneven, axis=(0,1), edge_order=2)
 1019         res2 = gradient(f, x_uneven, x_even, axis=(1,0), edge_order=2)
 1020         assert_array_equal(res1[0], res2[1])
 1021         assert_array_equal(res1[1], res2[0])
 1022         assert_almost_equal(res1[0], fdx_even_ord2.T)
 1023         assert_almost_equal(res1[1], fdx_uneven_ord2)
 1024 
 1025     def test_specific_axes(self):
 1026         # Testing that gradient can work on a given axis only
 1027         v = [[1, 1], [3, 4]]
 1028         x = np.array(v)
 1029         dx = [np.array([[2., 3.], [2., 3.]]),
 1030               np.array([[0., 0.], [1., 1.]])]
 1031         assert_array_equal(gradient(x, axis=0), dx[0])
 1032         assert_array_equal(gradient(x, axis=1), dx[1])
 1033         assert_array_equal(gradient(x, axis=-1), dx[1])
 1034         assert_array_equal(gradient(x, axis=(1, 0)), [dx[1], dx[0]])
 1035 
 1036         # test axis=None which means all axes
 1037         assert_almost_equal(gradient(x, axis=None), [dx[0], dx[1]])
 1038         # and is the same as no axis keyword given
 1039         assert_almost_equal(gradient(x, axis=None), gradient(x))
 1040 
 1041         # test vararg order
 1042         assert_array_equal(gradient(x, 2, 3, axis=(1, 0)),
 1043                            [dx[1]/2.0, dx[0]/3.0])
 1044         # test maximal number of varargs
 1045         assert_raises(TypeError, gradient, x, 1, 2, axis=1)
 1046 
 1047         assert_raises(np.AxisError, gradient, x, axis=3)
 1048         assert_raises(np.AxisError, gradient, x, axis=-3)
 1049         # assert_raises(TypeError, gradient, x, axis=[1,])
 1050 
 1051     def test_timedelta64(self):
 1052         # Make sure gradient() can handle special types like timedelta64
 1053         x = np.array(
 1054             [-5, -3, 10, 12, 61, 321, 300],
 1055             dtype='timedelta64[D]')
 1056         dx = np.array(
 1057             [2, 7, 7, 25, 154, 119, -21],
 1058             dtype='timedelta64[D]')
 1059         assert_array_equal(gradient(x), dx)
 1060         assert_(dx.dtype == np.dtype('timedelta64[D]'))
 1061 
 1062     def test_inexact_dtypes(self):
 1063         for dt in [np.float16, np.float32, np.float64]:
 1064             # dtypes should not be promoted in a different way to what diff does
 1065             x = np.array([1, 2, 3], dtype=dt)
 1066             assert_equal(gradient(x).dtype, np.diff(x).dtype)
 1067 
 1068     def test_values(self):
 1069         # needs at least 2 points for edge_order ==1
 1070         gradient(np.arange(2), edge_order=1)
 1071         # needs at least 3 points for edge_order ==1
 1072         gradient(np.arange(3), edge_order=2)
 1073 
 1074         assert_raises(ValueError, gradient, np.arange(0), edge_order=1)
 1075         assert_raises(ValueError, gradient, np.arange(0), edge_order=2)
 1076         assert_raises(ValueError, gradient, np.arange(1), edge_order=1)
 1077         assert_raises(ValueError, gradient, np.arange(1), edge_order=2)
 1078         assert_raises(ValueError, gradient, np.arange(2), edge_order=2)
 1079 
 1080 
 1081 class TestAngle(object):
 1082 
 1083     def test_basic(self):
 1084         x = [1 + 3j, np.sqrt(2) / 2.0 + 1j * np.sqrt(2) / 2,
 1085              1, 1j, -1, -1j, 1 - 3j, -1 + 3j]
 1086         y = angle(x)
 1087         yo = [
 1088             np.arctan(3.0 / 1.0),
 1089             np.arctan(1.0), 0, np.pi / 2, np.pi, -np.pi / 2.0,
 1090             -np.arctan(3.0 / 1.0), np.pi - np.arctan(3.0 / 1.0)]
 1091         z = angle(x, deg=1)
 1092         zo = np.array(yo) * 180 / np.pi
 1093         assert_array_almost_equal(y, yo, 11)
 1094         assert_array_almost_equal(z, zo, 11)
 1095 
 1096     def test_subclass(self):
 1097         x = np.ma.array([1 + 3j, 1, np.sqrt(2)/2 * (1 + 1j)])
 1098         x[1] = np.ma.masked
 1099         expected = np.ma.array([np.arctan(3.0 / 1.0), 0, np.arctan(1.0)])
 1100         expected[1] = np.ma.masked
 1101         actual = angle(x)
 1102         assert_equal(type(actual), type(expected))
 1103         assert_equal(actual.mask, expected.mask)
 1104         assert_equal(actual, expected)
 1105 
 1106 
 1107 class TestTrimZeros(object):
 1108 
 1109     """
 1110     Only testing for integer splits.
 1111 
 1112     """
 1113 
 1114     def test_basic(self):
 1115         a = np.array([0, 0, 1, 2, 3, 4, 0])
 1116         res = trim_zeros(a)
 1117         assert_array_equal(res, np.array([1, 2, 3, 4]))
 1118 
 1119     def test_leading_skip(self):
 1120         a = np.array([0, 0, 1, 0, 2, 3, 4, 0])
 1121         res = trim_zeros(a)
 1122         assert_array_equal(res, np.array([1, 0, 2, 3, 4]))
 1123 
 1124     def test_trailing_skip(self):
 1125         a = np.array([0, 0, 1, 0, 2, 3, 0, 4, 0])
 1126         res = trim_zeros(a)
 1127         assert_array_equal(res, np.array([1, 0, 2, 3, 0, 4]))
 1128 
 1129 
 1130 class TestExtins(object):
 1131 
 1132     def test_basic(self):
 1133         a = np.array([1, 3, 2, 1, 2, 3, 3])
 1134         b = extract(a > 1, a)
 1135         assert_array_equal(b, [3, 2, 2, 3, 3])
 1136 
 1137     def test_place(self):
 1138         # Make sure that non-np.ndarray objects
 1139         # raise an error instead of doing nothing
 1140         assert_raises(TypeError, place, [1, 2, 3], [True, False], [0, 1])
 1141 
 1142         a = np.array([1, 4, 3, 2, 5, 8, 7])
 1143         place(a, [0, 1, 0, 1, 0, 1, 0], [2, 4, 6])
 1144         assert_array_equal(a, [1, 2, 3, 4, 5, 6, 7])
 1145 
 1146         place(a, np.zeros(7), [])
 1147         assert_array_equal(a, np.arange(1, 8))
 1148 
 1149         place(a, [1, 0, 1, 0, 1, 0, 1], [8, 9])
 1150         assert_array_equal(a, [8, 2, 9, 4, 8, 6, 9])
 1151         assert_raises_regex(ValueError, "Cannot insert from an empty array",
 1152                             lambda: place(a, [0, 0, 0, 0, 0, 1, 0], []))
 1153 
 1154         # See Issue #6974
 1155         a = np.array(['12', '34'])
 1156         place(a, [0, 1], '9')
 1157         assert_array_equal(a, ['12', '9'])
 1158 
 1159     def test_both(self):
 1160         a = rand(10)
 1161         mask = a > 0.5
 1162         ac = a.copy()
 1163         c = extract(mask, a)
 1164         place(a, mask, 0)
 1165         place(a, mask, c)
 1166         assert_array_equal(a, ac)
 1167 
 1168 
 1169 class TestVectorize(object):
 1170 
 1171     def test_simple(self):
 1172         def addsubtract(a, b):
 1173             if a > b:
 1174                 return a - b
 1175             else:
 1176                 return a + b
 1177 
 1178         f = vectorize(addsubtract)
 1179         r = f([0, 3, 6, 9], [1, 3, 5, 7])
 1180         assert_array_equal(r, [1, 6, 1, 2])
 1181 
 1182     def test_scalar(self):
 1183         def addsubtract(a, b):
 1184             if a > b:
 1185                 return a - b
 1186             else:
 1187                 return a + b
 1188 
 1189         f = vectorize(addsubtract)
 1190         r = f([0, 3, 6, 9], 5)
 1191         assert_array_equal(r, [5, 8, 1, 4])
 1192 
 1193     def test_large(self):
 1194         x = np.linspace(-3, 2, 10000)
 1195         f = vectorize(lambda x: x)
 1196         y = f(x)
 1197         assert_array_equal(y, x)
 1198 
 1199     def test_ufunc(self):
 1200         import math
 1201         f = vectorize(math.cos)
 1202         args = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi, 2 * np.pi])
 1203         r1 = f(args)
 1204         r2 = np.cos(args)
 1205         assert_array_almost_equal(r1, r2)
 1206 
 1207     def test_keywords(self):
 1208 
 1209         def foo(a, b=1):
 1210             return a + b
 1211 
 1212         f = vectorize(foo)
 1213         args = np.array([1, 2, 3])
 1214         r1 = f(args)
 1215         r2 = np.array([2, 3, 4])
 1216         assert_array_equal(r1, r2)
 1217         r1 = f(args, 2)
 1218         r2 = np.array([3, 4, 5])
 1219         assert_array_equal(r1, r2)
 1220 
 1221     def test_keywords_no_func_code(self):
 1222         # This needs to test a function that has keywords but
 1223         # no func_code attribute, since otherwise vectorize will
 1224         # inspect the func_code.
 1225         import random
 1226         try:
 1227             vectorize(random.randrange)  # Should succeed
 1228         except Exception:
 1229             raise AssertionError()
 1230 
 1231     def test_keywords2_ticket_2100(self):
 1232         # Test kwarg support: enhancement ticket 2100
 1233 
 1234         def foo(a, b=1):
 1235             return a + b
 1236 
 1237         f = vectorize(foo)
 1238         args = np.array([1, 2, 3])
 1239         r1 = f(a=args)
 1240         r2 = np.array([2, 3, 4])
 1241         assert_array_equal(r1, r2)
 1242         r1 = f(b=1, a=args)
 1243         assert_array_equal(r1, r2)
 1244         r1 = f(args, b=2)
 1245         r2 = np.array([3, 4, 5])
 1246         assert_array_equal(r1, r2)
 1247 
 1248     def test_keywords3_ticket_2100(self):
 1249         # Test excluded with mixed positional and kwargs: ticket 2100
 1250         def mypolyval(x, p):
 1251             _p = list(p)
 1252             res = _p.pop(0)
 1253             while _p:
 1254                 res = res * x + _p.pop(0)
 1255             return res
 1256 
 1257         vpolyval = np.vectorize(mypolyval, excluded=['p', 1])
 1258         ans = [3, 6]
 1259         assert_array_equal(ans, vpolyval(x=[0, 1], p=[1, 2, 3]))
 1260         assert_array_equal(ans, vpolyval([0, 1], p=[1, 2, 3]))
 1261         assert_array_equal(ans, vpolyval([0, 1], [1, 2, 3]))
 1262 
 1263     def test_keywords4_ticket_2100(self):
 1264         # Test vectorizing function with no positional args.
 1265         @vectorize
 1266         def f(**kw):
 1267             res = 1.0
 1268             for _k in kw:
 1269                 res *= kw[_k]
 1270             return res
 1271 
 1272         assert_array_equal(f(a=[1, 2], b=[3, 4]), [3, 8])
 1273 
 1274     def test_keywords5_ticket_2100(self):
 1275         # Test vectorizing function with no kwargs args.
 1276         @vectorize
 1277         def f(*v):
 1278             return np.prod(v)
 1279 
 1280         assert_array_equal(f([1, 2], [3, 4]), [3, 8])
 1281 
 1282     def test_coverage1_ticket_2100(self):
 1283         def foo():
 1284             return 1
 1285 
 1286         f = vectorize(foo)
 1287         assert_array_equal(f(), 1)
 1288 
 1289     def test_assigning_docstring(self):
 1290         def foo(x):
 1291             """Original documentation"""
 1292             return x
 1293 
 1294         f = vectorize(foo)
 1295         assert_equal(f.__doc__, foo.__doc__)
 1296 
 1297         doc = "Provided documentation"
 1298         f = vectorize(foo, doc=doc)
 1299         assert_equal(f.__doc__, doc)
 1300 
 1301     def test_UnboundMethod_ticket_1156(self):
 1302         # Regression test for issue 1156
 1303         class Foo:
 1304             b = 2
 1305 
 1306             def bar(self, a):
 1307                 return a ** self.b
 1308 
 1309         assert_array_equal(vectorize(Foo().bar)(np.arange(9)),
 1310                            np.arange(9) ** 2)
 1311         assert_array_equal(vectorize(Foo.bar)(Foo(), np.arange(9)),
 1312                            np.arange(9) ** 2)
 1313 
 1314     def test_execution_order_ticket_1487(self):
 1315         # Regression test for dependence on execution order: issue 1487
 1316         f1 = vectorize(lambda x: x)
 1317         res1a = f1(np.arange(3))
 1318         res1b = f1(np.arange(0.1, 3))
 1319         f2 = vectorize(lambda x: x)
 1320         res2b = f2(np.arange(0.1, 3))
 1321         res2a = f2(np.arange(3))
 1322         assert_equal(res1a, res2a)
 1323         assert_equal(res1b, res2b)
 1324 
 1325     def test_string_ticket_1892(self):
 1326         # Test vectorization over strings: issue 1892.
 1327         f = np.vectorize(lambda x: x)
 1328         s = '0123456789' * 10
 1329         assert_equal(s, f(s))
 1330 
 1331     def test_cache(self):
 1332         # Ensure that vectorized func called exactly once per argument.
 1333         _calls = [0]
 1334 
 1335         @vectorize
 1336         def f(x):
 1337             _calls[0] += 1
 1338             return x ** 2
 1339 
 1340         f.cache = True
 1341         x = np.arange(5)
 1342         assert_array_equal(f(x), x * x)
 1343         assert_equal(_calls[0], len(x))
 1344 
 1345     def test_otypes(self):
 1346         f = np.vectorize(lambda x: x)
 1347         f.otypes = 'i'
 1348         x = np.arange(5)
 1349         assert_array_equal(f(x), x)
 1350 
 1351     def test_parse_gufunc_signature(self):
 1352         assert_equal(nfb._parse_gufunc_signature('(x)->()'), ([('x',)], [()]))
 1353         assert_equal(nfb._parse_gufunc_signature('(x,y)->()'),
 1354                      ([('x', 'y')], [()]))
 1355         assert_equal(nfb._parse_gufunc_signature('(x),(y)->()'),
 1356                      ([('x',), ('y',)], [()]))
 1357         assert_equal(nfb._parse_gufunc_signature('(x)->(y)'),
 1358                      ([('x',)], [('y',)]))
 1359         assert_equal(nfb._parse_gufunc_signature('(x)->(y),()'),
 1360                      ([('x',)], [('y',), ()]))
 1361         assert_equal(nfb._parse_gufunc_signature('(),(a,b,c),(d)->(d,e)'),
 1362                      ([(), ('a', 'b', 'c'), ('d',)], [('d', 'e')]))
 1363         with assert_raises(ValueError):
 1364             nfb._parse_gufunc_signature('(x)(y)->()')
 1365         with assert_raises(ValueError):
 1366             nfb._parse_gufunc_signature('(x),(y)->')
 1367         with assert_raises(ValueError):
 1368             nfb._parse_gufunc_signature('((x))->(x)')
 1369 
 1370     def test_signature_simple(self):
 1371         def addsubtract(a, b):
 1372             if a > b:
 1373                 return a - b
 1374             else:
 1375                 return a + b
 1376 
 1377         f = vectorize(addsubtract, signature='(),()->()')
 1378         r = f([0, 3, 6, 9], [1, 3, 5, 7])
 1379         assert_array_equal(r, [1, 6, 1, 2])
 1380 
 1381     def test_signature_mean_last(self):
 1382         def mean(a):
 1383             return a.mean()
 1384 
 1385         f = vectorize(mean, signature='(n)->()')
 1386         r = f([[1, 3], [2, 4]])
 1387         assert_array_equal(r, [2, 3])
 1388 
 1389     def test_signature_center(self):
 1390         def center(a):
 1391             return a - a.mean()
 1392 
 1393         f = vectorize(center, signature='(n)->(n)')
 1394         r = f([[1, 3], [2, 4]])
 1395         assert_array_equal(r, [[-1, 1], [-1, 1]])
 1396 
 1397     def test_signature_two_outputs(self):
 1398         f = vectorize(lambda x: (x, x), signature='()->(),()')
 1399         r = f([1, 2, 3])
 1400         assert_(isinstance(r, tuple) and len(r) == 2)
 1401         assert_array_equal(r[0], [1, 2, 3])
 1402         assert_array_equal(r[1], [1, 2, 3])
 1403 
 1404     def test_signature_outer(self):
 1405         f = vectorize(np.outer, signature='(a),(b)->(a,b)')
 1406         r = f([1, 2], [1, 2, 3])
 1407         assert_array_equal(r, [[1, 2, 3], [2, 4, 6]])
 1408 
 1409         r = f([[[1, 2]]], [1, 2, 3])
 1410         assert_array_equal(r, [[[[1, 2, 3], [2, 4, 6]]]])
 1411 
 1412         r = f([[1, 0], [2, 0]], [1, 2, 3])
 1413         assert_array_equal(r, [[[1, 2, 3], [0, 0, 0]],
 1414                                [[2, 4, 6], [0, 0, 0]]])
 1415 
 1416         r = f([1, 2], [[1, 2, 3], [0, 0, 0]])
 1417         assert_array_equal(r, [[[1, 2, 3], [2, 4, 6]],
 1418                                [[0, 0, 0], [0, 0, 0]]])
 1419 
 1420     def test_signature_computed_size(self):
 1421         f = vectorize(lambda x: x[:-1], signature='(n)->(m)')
 1422         r = f([1, 2, 3])
 1423         assert_array_equal(r, [1, 2])
 1424 
 1425         r = f([[1, 2, 3], [2, 3, 4]])
 1426         assert_array_equal(r, [[1, 2], [2, 3]])
 1427 
 1428     def test_signature_excluded(self):
 1429 
 1430         def foo(a, b=1):
 1431             return a + b
 1432 
 1433         f = vectorize(foo, signature='()->()', excluded={'b'})
 1434         assert_array_equal(f([1, 2, 3]), [2, 3, 4])
 1435         assert_array_equal(f([1, 2, 3], b=0), [1, 2, 3])
 1436 
 1437     def test_signature_otypes(self):
 1438         f = vectorize(lambda x: x, signature='(n)->(n)', otypes=['float64'])
 1439         r = f([1, 2, 3])
 1440         assert_equal(r.dtype, np.dtype('float64'))
 1441         assert_array_equal(r, [1, 2, 3])
 1442 
 1443     def test_signature_invalid_inputs(self):
 1444         f = vectorize(operator.add, signature='(n),(n)->(n)')
 1445         with assert_raises_regex(TypeError, 'wrong number of positional'):
 1446             f([1, 2])
 1447         with assert_raises_regex(
 1448                 ValueError, 'does not have enough dimensions'):
 1449             f(1, 2)
 1450         with assert_raises_regex(
 1451                 ValueError, 'inconsistent size for core dimension'):
 1452             f([1, 2], [1, 2, 3])
 1453 
 1454         f = vectorize(operator.add, signature='()->()')
 1455         with assert_raises_regex(TypeError, 'wrong number of positional'):
 1456             f(1, 2)
 1457 
 1458     def test_signature_invalid_outputs(self):
 1459 
 1460         f = vectorize(lambda x: x[:-1], signature='(n)->(n)')
 1461         with assert_raises_regex(
 1462                 ValueError, 'inconsistent size for core dimension'):
 1463             f([1, 2, 3])
 1464 
 1465         f = vectorize(lambda x: x, signature='()->(),()')
 1466         with assert_raises_regex(ValueError, 'wrong number of outputs'):
 1467             f(1)
 1468 
 1469         f = vectorize(lambda x: (x, x), signature='()->()')
 1470         with assert_raises_regex(ValueError, 'wrong number of outputs'):
 1471             f([1, 2])
 1472 
 1473     def test_size_zero_output(self):
 1474         # see issue 5868
 1475         f = np.vectorize(lambda x: x)
 1476         x = np.zeros([0, 5], dtype=int)
 1477         with assert_raises_regex(ValueError, 'otypes'):
 1478             f(x)
 1479 
 1480         f.otypes = 'i'
 1481         assert_array_equal(f(x), x)
 1482 
 1483         f = np.vectorize(lambda x: x, signature='()->()')
 1484         with assert_raises_regex(ValueError, 'otypes'):
 1485             f(x)
 1486 
 1487         f = np.vectorize(lambda x: x, signature='()->()', otypes='i')
 1488         assert_array_equal(f(x), x)
 1489 
 1490         f = np.vectorize(lambda x: x, signature='(n)->(n)', otypes='i')
 1491         assert_array_equal(f(x), x)
 1492 
 1493         f = np.vectorize(lambda x: x, signature='(n)->(n)')
 1494         assert_array_equal(f(x.T), x.T)
 1495 
 1496         f = np.vectorize(lambda x: [x], signature='()->(n)', otypes='i')
 1497         with assert_raises_regex(ValueError, 'new output dimensions'):
 1498             f(x)
 1499 
 1500 
 1501 class TestDigitize(object):
 1502 
 1503     def test_forward(self):
 1504         x = np.arange(-6, 5)
 1505         bins = np.arange(-5, 5)
 1506         assert_array_equal(digitize(x, bins), np.arange(11))
 1507 
 1508     def test_reverse(self):
 1509         x = np.arange(5, -6, -1)
 1510         bins = np.arange(5, -5, -1)
 1511         assert_array_equal(digitize(x, bins), np.arange(11))
 1512 
 1513     def test_random(self):
 1514         x = rand(10)
 1515         bin = np.linspace(x.min(), x.max(), 10)
 1516         assert_(np.all(digitize(x, bin) != 0))
 1517 
 1518     def test_right_basic(self):
 1519         x = [1, 5, 4, 10, 8, 11, 0]
 1520         bins = [1, 5, 10]
 1521         default_answer = [1, 2, 1, 3, 2, 3, 0]
 1522         assert_array_equal(digitize(x, bins), default_answer)
 1523         right_answer = [0, 1, 1, 2, 2, 3, 0]
 1524         assert_array_equal(digitize(x, bins, True), right_answer)
 1525 
 1526     def test_right_open(self):
 1527         x = np.arange(-6, 5)
 1528         bins = np.arange(-6, 4)
 1529         assert_array_equal(digitize(x, bins, True), np.arange(11))
 1530 
 1531     def test_right_open_reverse(self):
 1532         x = np.arange(5, -6, -1)
 1533         bins = np.arange(4, -6, -1)
 1534         assert_array_equal(digitize(x, bins, True), np.arange(11))
 1535 
 1536     def test_right_open_random(self):
 1537         x = rand(10)
 1538         bins = np.linspace(x.min(), x.max(), 10)
 1539         assert_(np.all(digitize(x, bins, True) != 10))
 1540 
 1541     def test_monotonic(self):
 1542         x = [-1, 0, 1, 2]
 1543         bins = [0, 0, 1]
 1544         assert_array_equal(digitize(x, bins, False), [0, 2, 3, 3])
 1545         assert_array_equal(digitize(x, bins, True), [0, 0, 2, 3])
 1546         bins = [1, 1, 0]
 1547         assert_array_equal(digitize(x, bins, False), [3, 2, 0, 0])
 1548         assert_array_equal(digitize(x, bins, True), [3, 3, 2, 0])
 1549         bins = [1, 1, 1, 1]
 1550         assert_array_equal(digitize(x, bins, False), [0, 0, 4, 4])
 1551         assert_array_equal(digitize(x, bins, True), [0, 0, 0, 4])
 1552         bins = [0, 0, 1, 0]
 1553         assert_raises(ValueError, digitize, x, bins)
 1554         bins = [1, 1, 0, 1]
 1555         assert_raises(ValueError, digitize, x, bins)
 1556 
 1557     def test_casting_error(self):
 1558         x = [1, 2, 3 + 1.j]
 1559         bins = [1, 2, 3]
 1560         assert_raises(TypeError, digitize, x, bins)
 1561         x, bins = bins, x
 1562         assert_raises(TypeError, digitize, x, bins)
 1563 
 1564     def test_return_type(self):
 1565         # Functions returning indices should always return base ndarrays
 1566         class A(np.ndarray):
 1567             pass
 1568         a = np.arange(5).view(A)
 1569         b = np.arange(1, 3).view(A)
 1570         assert_(not isinstance(digitize(b, a, False), A))
 1571         assert_(not isinstance(digitize(b, a, True), A))
 1572 
 1573     def test_large_integers_increasing(self):
 1574         # gh-11022
 1575         x = 2**54  # loses precision in a float
 1576         assert_equal(np.digitize(x, [x - 1, x + 1]), 1)
 1577 
 1578     @pytest.mark.xfail(
 1579         reason="gh-11022: np.core.multiarray._monoticity loses precision")
 1580     def test_large_integers_decreasing(self):
 1581         # gh-11022
 1582         x = 2**54  # loses precision in a float
 1583         assert_equal(np.digitize(x, [x + 1, x - 1]), 1)
 1584 
 1585 
 1586 class TestUnwrap(object):
 1587 
 1588     def test_simple(self):
 1589         # check that unwrap removes jumps greater that 2*pi
 1590         assert_array_equal(unwrap([1, 1 + 2 * np.pi]), [1, 1])
 1591         # check that unwrap maintains continuity
 1592         assert_(np.all(diff(unwrap(rand(10) * 100)) < np.pi))
 1593 
 1594 
 1595 class TestFilterwindows(object):
 1596 
 1597     def test_hanning(self):
 1598         # check symmetry
 1599         w = hanning(10)
 1600         assert_array_almost_equal(w, flipud(w), 7)
 1601         # check known value
 1602         assert_almost_equal(np.sum(w, axis=0), 4.500, 4)
 1603 
 1604     def test_hamming(self):
 1605         # check symmetry
 1606         w = hamming(10)
 1607         assert_array_almost_equal(w, flipud(w), 7)
 1608         # check known value
 1609         assert_almost_equal(np.sum(w, axis=0), 4.9400, 4)
 1610 
 1611     def test_bartlett(self):
 1612         # check symmetry
 1613         w = bartlett(10)
 1614         assert_array_almost_equal(w, flipud(w), 7)
 1615         # check known value
 1616         assert_almost_equal(np.sum(w, axis=0), 4.4444, 4)
 1617 
 1618     def test_blackman(self):
 1619         # check symmetry
 1620         w = blackman(10)
 1621         assert_array_almost_equal(w, flipud(w), 7)
 1622         # check known value
 1623         assert_almost_equal(np.sum(w, axis=0), 3.7800, 4)
 1624 
 1625 
 1626 class TestTrapz(object):
 1627 
 1628     def test_simple(self):
 1629         x = np.arange(-10, 10, .1)
 1630         r = trapz(np.exp(-.5 * x ** 2) / np.sqrt(2 * np.pi), dx=0.1)
 1631         # check integral of normal equals 1
 1632         assert_almost_equal(r, 1, 7)
 1633 
 1634     def test_ndim(self):
 1635         x = np.linspace(0, 1, 3)
 1636         y = np.linspace(0, 2, 8)
 1637         z = np.linspace(0, 3, 13)
 1638 
 1639         wx = np.ones_like(x) * (x[1] - x[0])
 1640         wx[0] /= 2
 1641         wx[-1] /= 2
 1642         wy = np.ones_like(y) * (y[1] - y[0])
 1643         wy[0] /= 2
 1644         wy[-1] /= 2
 1645         wz = np.ones_like(z) * (z[1] - z[0])
 1646         wz[0] /= 2
 1647         wz[-1] /= 2
 1648 
 1649         q = x[:, None, None] + y[None,:, None] + z[None, None,:]
 1650 
 1651         qx = (q * wx[:, None, None]).sum(axis=0)
 1652         qy = (q * wy[None, :, None]).sum(axis=1)
 1653         qz = (q * wz[None, None, :]).sum(axis=2)
 1654 
 1655         # n-d `x`
 1656         r = trapz(q, x=x[:, None, None], axis=0)
 1657         assert_almost_equal(r, qx)
 1658         r = trapz(q, x=y[None,:, None], axis=1)
 1659         assert_almost_equal(r, qy)
 1660         r = trapz(q, x=z[None, None,:], axis=2)
 1661         assert_almost_equal(r, qz)
 1662 
 1663         # 1-d `x`
 1664         r = trapz(q, x=x, axis=0)
 1665         assert_almost_equal(r, qx)
 1666         r = trapz(q, x=y, axis=1)
 1667         assert_almost_equal(r, qy)
 1668         r = trapz(q, x=z, axis=2)
 1669         assert_almost_equal(r, qz)
 1670 
 1671     def test_masked(self):
 1672         # Testing that masked arrays behave as if the function is 0 where
 1673         # masked
 1674         x = np.arange(5)
 1675         y = x * x
 1676         mask = x == 2
 1677         ym = np.ma.array(y, mask=mask)
 1678         r = 13.0  # sum(0.5 * (0 + 1) * 1.0 + 0.5 * (9 + 16))
 1679         assert_almost_equal(trapz(ym, x), r)
 1680 
 1681         xm = np.ma.array(x, mask=mask)
 1682         assert_almost_equal(trapz(ym, xm), r)
 1683 
 1684         xm = np.ma.array(x, mask=mask)
 1685         assert_almost_equal(trapz(y, xm), r)
 1686 
 1687 
 1688 class TestSinc(object):
 1689 
 1690     def test_simple(self):
 1691         assert_(sinc(0) == 1)
 1692         w = sinc(np.linspace(-1, 1, 100))
 1693         # check symmetry
 1694         assert_array_almost_equal(w, flipud(w), 7)
 1695 
 1696     def test_array_like(self):
 1697         x = [0, 0.5]
 1698         y1 = sinc(np.array(x))
 1699         y2 = sinc(list(x))
 1700         y3 = sinc(tuple(x))
 1701         assert_array_equal(y1, y2)
 1702         assert_array_equal(y1, y3)
 1703 
 1704 
 1705 class TestUnique(object):
 1706 
 1707     def test_simple(self):
 1708         x = np.array([4, 3, 2, 1, 1, 2, 3, 4, 0])
 1709         assert_(np.all(unique(x) == [0, 1, 2, 3, 4]))
 1710         assert_(unique(np.array([1, 1, 1, 1, 1])) == np.array([1]))
 1711         x = ['widget', 'ham', 'foo', 'bar', 'foo', 'ham']
 1712         assert_(np.all(unique(x) == ['bar', 'foo', 'ham', 'widget']))
 1713         x = np.array([5 + 6j, 1 + 1j, 1 + 10j, 10, 5 + 6j])
 1714         assert_(np.all(unique(x) == [1 + 1j, 1 + 10j, 5 + 6j, 10]))
 1715 
 1716 
 1717 class TestCheckFinite(object):
 1718 
 1719     def test_simple(self):
 1720         a = [1, 2, 3]
 1721         b = [1, 2, np.inf]
 1722         c = [1, 2, np.nan]
 1723         np.lib.asarray_chkfinite(a)
 1724         assert_raises(ValueError, np.lib.asarray_chkfinite, b)
 1725         assert_raises(ValueError, np.lib.asarray_chkfinite, c)
 1726 
 1727     def test_dtype_order(self):
 1728         # Regression test for missing dtype and order arguments
 1729         a = [1, 2, 3]
 1730         a = np.lib.asarray_chkfinite(a, order='F', dtype=np.float64)
 1731         assert_(a.dtype == np.float64)
 1732 
 1733 
 1734 class TestCorrCoef(object):
 1735     A = np.array(
 1736         [[0.15391142, 0.18045767, 0.14197213],
 1737          [0.70461506, 0.96474128, 0.27906989],
 1738          [0.9297531, 0.32296769, 0.19267156]])
 1739     B = np.array(
 1740         [[0.10377691, 0.5417086, 0.49807457],
 1741          [0.82872117, 0.77801674, 0.39226705],
 1742          [0.9314666, 0.66800209, 0.03538394]])
 1743     res1 = np.array(
 1744         [[1., 0.9379533, -0.04931983],
 1745          [0.9379533, 1., 0.30007991],
 1746          [-0.04931983, 0.30007991, 1.]])
 1747     res2 = np.array(
 1748         [[1., 0.9379533, -0.04931983, 0.30151751, 0.66318558, 0.51532523],
 1749          [0.9379533, 1., 0.30007991, -0.04781421, 0.88157256, 0.78052386],
 1750          [-0.04931983, 0.30007991, 1., -0.96717111, 0.71483595, 0.83053601],
 1751          [0.30151751, -0.04781421, -0.96717111, 1., -0.51366032, -0.66173113],
 1752          [0.66318558, 0.88157256, 0.71483595, -0.51366032, 1., 0.98317823],
 1753          [0.51532523, 0.78052386, 0.83053601, -0.66173113, 0.98317823, 1.]])
 1754 
 1755     def test_non_array(self):
 1756         assert_almost_equal(np.corrcoef([0, 1, 0], [1, 0, 1]),
 1757                             [[1., -1.], [-1.,  1.]])
 1758 
 1759     def test_simple(self):
 1760         tgt1 = corrcoef(self.A)
 1761         assert_almost_equal(tgt1, self.res1)
 1762         assert_(np.all(np.abs(tgt1) <= 1.0))
 1763 
 1764         tgt2 = corrcoef(self.A, self.B)
 1765         assert_almost_equal(tgt2, self.res2)
 1766         assert_(np.all(np.abs(tgt2) <= 1.0))
 1767 
 1768     def test_ddof(self):
 1769         # ddof raises DeprecationWarning
 1770         with suppress_warnings() as sup:
 1771             warnings.simplefilter("always")
 1772             assert_warns(DeprecationWarning, corrcoef, self.A, ddof=-1)
 1773             sup.filter(DeprecationWarning)
 1774             # ddof has no or negligible effect on the function
 1775             assert_almost_equal(corrcoef(self.A, ddof=-1), self.res1)
 1776             assert_almost_equal(corrcoef(self.A, self.B, ddof=-1), self.res2)
 1777             assert_almost_equal(corrcoef(self.A, ddof=3), self.res1)
 1778             assert_almost_equal(corrcoef(self.A, self.B, ddof=3), self.res2)
 1779 
 1780     def test_bias(self):
 1781         # bias raises DeprecationWarning
 1782         with suppress_warnings() as sup:
 1783             warnings.simplefilter("always")
 1784             assert_warns(DeprecationWarning, corrcoef, self.A, self.B, 1, 0)
 1785             assert_warns(DeprecationWarning, corrcoef, self.A, bias=0)
 1786             sup.filter(DeprecationWarning)
 1787             # bias has no or negligible effect on the function
 1788             assert_almost_equal(corrcoef(self.A, bias=1), self.res1)
 1789 
 1790     def test_complex(self):
 1791         x = np.array([[1, 2, 3], [1j, 2j, 3j]])
 1792         res = corrcoef(x)
 1793         tgt = np.array([[1., -1.j], [1.j, 1.]])
 1794         assert_allclose(res, tgt)
 1795         assert_(np.all(np.abs(res) <= 1.0))
 1796 
 1797     def test_xy(self):
 1798         x = np.array([[1, 2, 3]])
 1799         y = np.array([[1j, 2j, 3j]])
 1800         assert_allclose(np.corrcoef(x, y), np.array([[1., -1.j], [1.j, 1.]]))
 1801 
 1802     def test_empty(self):
 1803         with warnings.catch_warnings(record=True):
 1804             warnings.simplefilter('always', RuntimeWarning)
 1805             assert_array_equal(corrcoef(np.array([])), np.nan)
 1806             assert_array_equal(corrcoef(np.array([]).reshape(0, 2)),
 1807                                np.array([]).reshape(0, 0))
 1808             assert_array_equal(corrcoef(np.array([]).reshape(2, 0)),
 1809                                np.array([[np.nan, np.nan], [np.nan, np.nan]]))
 1810 
 1811     def test_extreme(self):
 1812         x = [[1e-100, 1e100], [1e100, 1e-100]]
 1813         with np.errstate(all='raise'):
 1814             c = corrcoef(x)
 1815         assert_array_almost_equal(c, np.array([[1., -1.], [-1., 1.]]))
 1816         assert_(np.all(np.abs(c) <= 1.0))
 1817 
 1818 
 1819 class TestCov(object):
 1820     x1 = np.array([[0, 2], [1, 1], [2, 0]]).T
 1821     res1 = np.array([[1., -1.], [-1., 1.]])
 1822     x2 = np.array([0.0, 1.0, 2.0], ndmin=2)
 1823     frequencies = np.array([1, 4, 1])
 1824     x2_repeats = np.array([[0.0], [1.0], [1.0], [1.0], [1.0], [2.0]]).T
 1825     res2 = np.array([[0.4, -0.4], [-0.4, 0.4]])
 1826     unit_frequencies = np.ones(3, dtype=np.integer)
 1827     weights = np.array([1.0, 4.0, 1.0])
 1828     res3 = np.array([[2. / 3., -2. / 3.], [-2. / 3., 2. / 3.]])
 1829     unit_weights = np.ones(3)
 1830     x3 = np.array([0.3942, 0.5969, 0.7730, 0.9918, 0.7964])
 1831 
 1832     def test_basic(self):
 1833         assert_allclose(cov(self.x1), self.res1)
 1834 
 1835     def test_complex(self):
 1836         x = np.array([[1, 2, 3], [1j, 2j, 3j]])
 1837         res = np.array([[1., -1.j], [1.j, 1.]])
 1838         assert_allclose(cov(x), res)
 1839         assert_allclose(cov(x, aweights=np.ones(3)), res)
 1840 
 1841     def test_xy(self):
 1842         x = np.array([[1, 2, 3]])
 1843         y = np.array([[1j, 2j, 3j]])
 1844         assert_allclose(cov(x, y), np.array([[1., -1.j], [1.j, 1.]]))
 1845 
 1846     def test_empty(self):
 1847         with warnings.catch_warnings(record=True):
 1848             warnings.simplefilter('always', RuntimeWarning)
 1849             assert_array_equal(cov(np.array([])), np.nan)
 1850             assert_array_equal(cov(np.array([]).reshape(0, 2)),
 1851                                np.array([]).reshape(0, 0))
 1852             assert_array_equal(cov(np.array([]).reshape(2, 0)),
 1853                                np.array([[np.nan, np.nan], [np.nan, np.nan]]))
 1854 
 1855     def test_wrong_ddof(self):
 1856         with warnings.catch_warnings(record=True):
 1857             warnings.simplefilter('always', RuntimeWarning)
 1858             assert_array_equal(cov(self.x1, ddof=5),
 1859                                np.array([[np.inf, -np.inf],
 1860                                          [-np.inf, np.inf]]))
 1861 
 1862     def test_1D_rowvar(self):
 1863         assert_allclose(cov(self.x3), cov(self.x3, rowvar=0))
 1864         y = np.array([0.0780, 0.3107, 0.2111, 0.0334, 0.8501])
 1865         assert_allclose(cov(self.x3, y), cov(self.x3, y, rowvar=0))
 1866 
 1867     def test_1D_variance(self):
 1868         assert_allclose(cov(self.x3, ddof=1), np.var(self.x3, ddof=1))
 1869 
 1870     def test_fweights(self):
 1871         assert_allclose(cov(self.x2, fweights=self.frequencies),
 1872                         cov(self.x2_repeats))
 1873         assert_allclose(cov(self.x1, fweights=self.frequencies),
 1874                         self.res2)
 1875         assert_allclose(cov(self.x1, fweights=self.unit_frequencies),
 1876                         self.res1)
 1877         nonint = self.frequencies + 0.5
 1878         assert_raises(TypeError, cov, self.x1, fweights=nonint)
 1879         f = np.ones((2, 3), dtype=np.integer)
 1880         assert_raises(RuntimeError, cov, self.x1, fweights=f)
 1881         f = np.ones(2, dtype=np.integer)
 1882         assert_raises(RuntimeError, cov, self.x1, fweights=f)
 1883         f = -1 * np.ones(3, dtype=np.integer)
 1884         assert_raises(ValueError, cov, self.x1, fweights=f)
 1885 
 1886     def test_aweights(self):
 1887         assert_allclose(cov(self.x1, aweights=self.weights), self.res3)
 1888         assert_allclose(cov(self.x1, aweights=3.0 * self.weights),
 1889                         cov(self.x1, aweights=self.weights))
 1890         assert_allclose(cov(self.x1, aweights=self.unit_weights), self.res1)
 1891         w = np.ones((2, 3))
 1892         assert_raises(RuntimeError, cov, self.x1, aweights=w)
 1893         w = np.ones(2)
 1894         assert_raises(RuntimeError, cov, self.x1, aweights=w)
 1895         w = -1.0 * np.ones(3)
 1896         assert_raises(ValueError, cov, self.x1, aweights=w)
 1897 
 1898     def test_unit_fweights_and_aweights(self):
 1899         assert_allclose(cov(self.x2, fweights=self.frequencies,
 1900                             aweights=self.unit_weights),
 1901                         cov(self.x2_repeats))
 1902         assert_allclose(cov(self.x1, fweights=self.frequencies,
 1903                             aweights=self.unit_weights),
 1904                         self.res2)
 1905         assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
 1906                             aweights=self.unit_weights),
 1907                         self.res1)
 1908         assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
 1909                             aweights=self.weights),
 1910                         self.res3)
 1911         assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
 1912                             aweights=3.0 * self.weights),
 1913                         cov(self.x1, aweights=self.weights))
 1914         assert_allclose(cov(self.x1, fweights=self.unit_frequencies,
 1915                             aweights=self.unit_weights),
 1916                         self.res1)
 1917 
 1918 
 1919 class Test_I0(object):
 1920 
 1921     def test_simple(self):
 1922         assert_almost_equal(
 1923             i0(0.5),
 1924             np.array(1.0634833707413234))
 1925 
 1926         A = np.array([0.49842636, 0.6969809, 0.22011976, 0.0155549])
 1927         assert_almost_equal(
 1928             i0(A),
 1929             np.array([1.06307822, 1.12518299, 1.01214991, 1.00006049]))
 1930 
 1931         B = np.array([[0.827002, 0.99959078],
 1932                       [0.89694769, 0.39298162],
 1933                       [0.37954418, 0.05206293],
 1934                       [0.36465447, 0.72446427],
 1935                       [0.48164949, 0.50324519]])
 1936         assert_almost_equal(
 1937             i0(B),
 1938             np.array([[1.17843223, 1.26583466],
 1939                       [1.21147086, 1.03898290],
 1940                       [1.03633899, 1.00067775],
 1941                       [1.03352052, 1.13557954],
 1942                       [1.05884290, 1.06432317]]))
 1943 
 1944 
 1945 class TestKaiser(object):
 1946 
 1947     def test_simple(self):
 1948         assert_(np.isfinite(kaiser(1, 1.0)))
 1949         assert_almost_equal(kaiser(0, 1.0),
 1950                             np.array([]))
 1951         assert_almost_equal(kaiser(2, 1.0),
 1952                             np.array([0.78984831, 0.78984831]))
 1953         assert_almost_equal(kaiser(5, 1.0),
 1954                             np.array([0.78984831, 0.94503323, 1.,
 1955                                       0.94503323, 0.78984831]))
 1956         assert_almost_equal(kaiser(5, 1.56789),
 1957                             np.array([0.58285404, 0.88409679, 1.,
 1958                                       0.88409679, 0.58285404]))
 1959 
 1960     def test_int_beta(self):
 1961         kaiser(3, 4)
 1962 
 1963 
 1964 class TestMsort(object):
 1965 
 1966     def test_simple(self):
 1967         A = np.array([[0.44567325, 0.79115165, 0.54900530],
 1968                       [0.36844147, 0.37325583, 0.96098397],
 1969                       [0.64864341, 0.52929049, 0.39172155]])
 1970         assert_almost_equal(
 1971             msort(A),
 1972             np.array([[0.36844147, 0.37325583, 0.39172155],
 1973                       [0.44567325, 0.52929049, 0.54900530],
 1974                       [0.64864341, 0.79115165, 0.96098397]]))
 1975 
 1976 
 1977 class TestMeshgrid(object):
 1978 
 1979     def test_simple(self):
 1980         [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7])
 1981         assert_array_equal(X, np.array([[1, 2, 3],
 1982                                         [1, 2, 3],
 1983                                         [1, 2, 3],
 1984                                         [1, 2, 3]]))
 1985         assert_array_equal(Y, np.array([[4, 4, 4],
 1986                                         [5, 5, 5],
 1987                                         [6, 6, 6],
 1988                                         [7, 7, 7]]))
 1989 
 1990     def test_single_input(self):
 1991         [X] = meshgrid([1, 2, 3, 4])
 1992         assert_array_equal(X, np.array([1, 2, 3, 4]))
 1993 
 1994     def test_no_input(self):
 1995         args = []
 1996         assert_array_equal([], meshgrid(*args))
 1997         assert_array_equal([], meshgrid(*args, copy=False))
 1998 
 1999     def test_indexing(self):
 2000         x = [1, 2, 3]
 2001         y = [4, 5, 6, 7]
 2002         [X, Y] = meshgrid(x, y, indexing='ij')
 2003         assert_array_equal(X, np.array([[1, 1, 1, 1],
 2004                                         [2, 2, 2, 2],
 2005                                         [3, 3, 3, 3]]))
 2006         assert_array_equal(Y, np.array([[4, 5, 6, 7],
 2007                                         [4, 5, 6, 7],
 2008                                         [4, 5, 6, 7]]))
 2009 
 2010         # Test expected shapes:
 2011         z = [8, 9]
 2012         assert_(meshgrid(x, y)[0].shape == (4, 3))
 2013         assert_(meshgrid(x, y, indexing='ij')[0].shape == (3, 4))
 2014         assert_(meshgrid(x, y, z)[0].shape == (4, 3, 2))
 2015         assert_(meshgrid(x, y, z, indexing='ij')[0].shape == (3, 4, 2))
 2016 
 2017         assert_raises(ValueError, meshgrid, x, y, indexing='notvalid')
 2018 
 2019     def test_sparse(self):
 2020         [X, Y] = meshgrid([1, 2, 3], [4, 5, 6, 7], sparse=True)
 2021         assert_array_equal(X, np.array([[1, 2, 3]]))
 2022         assert_array_equal(Y, np.array([[4], [5], [6], [7]]))
 2023 
 2024     def test_invalid_arguments(self):
 2025         # Test that meshgrid complains about invalid arguments
 2026         # Regression test for issue #4755:
 2027         # https://github.com/numpy/numpy/issues/4755
 2028         assert_raises(TypeError, meshgrid,
 2029                       [1, 2, 3], [4, 5, 6, 7], indices='ij')
 2030 
 2031     def test_return_type(self):
 2032         # Test for appropriate dtype in returned arrays.
 2033         # Regression test for issue #5297
 2034         # https://github.com/numpy/numpy/issues/5297
 2035         x = np.arange(0, 10, dtype=np.float32)
 2036         y = np.arange(10, 20, dtype=np.float64)
 2037 
 2038         X, Y = np.meshgrid(x,y)
 2039 
 2040         assert_(X.dtype == x.dtype)
 2041         assert_(Y.dtype == y.dtype)
 2042 
 2043         # copy
 2044         X, Y = np.meshgrid(x,y, copy=True)
 2045 
 2046         assert_(X.dtype == x.dtype)
 2047         assert_(Y.dtype == y.dtype)
 2048 
 2049         # sparse
 2050         X, Y = np.meshgrid(x,y, sparse=True)
 2051 
 2052         assert_(X.dtype == x.dtype)
 2053         assert_(Y.dtype == y.dtype)
 2054 
 2055     def test_writeback(self):
 2056         # Issue 8561
 2057         X = np.array([1.1, 2.2])
 2058         Y = np.array([3.3, 4.4])
 2059         x, y = np.meshgrid(X, Y, sparse=False, copy=True)
 2060 
 2061         x[0, :] = 0
 2062         assert_equal(x[0, :], 0)
 2063         assert_equal(x[1, :], X)
 2064 
 2065 
 2066 class TestPiecewise(object):
 2067 
 2068     def test_simple(self):
 2069         # Condition is single bool list
 2070         x = piecewise([0, 0], [True, False], [1])
 2071         assert_array_equal(x, [1, 0])
 2072 
 2073         # List of conditions: single bool list
 2074         x = piecewise([0, 0], [[True, False]], [1])
 2075         assert_array_equal(x, [1, 0])
 2076 
 2077         # Conditions is single bool array
 2078         x = piecewise([0, 0], np.array([True, False]), [1])
 2079         assert_array_equal(x, [1, 0])
 2080 
 2081         # Condition is single int array
 2082         x = piecewise([0, 0], np.array([1, 0]), [1])
 2083         assert_array_equal(x, [1, 0])
 2084 
 2085         # List of conditions: int array
 2086         x = piecewise([0, 0], [np.array([1, 0])], [1])
 2087         assert_array_equal(x, [1, 0])
 2088 
 2089         x = piecewise([0, 0], [[False, True]], [lambda x:-1])
 2090         assert_array_equal(x, [0, -1])
 2091 
 2092         assert_raises_regex(ValueError, '1 or 2 functions are expected',
 2093             piecewise, [0, 0], [[False, True]], [])
 2094         assert_raises_regex(ValueError, '1 or 2 functions are expected',
 2095             piecewise, [0, 0], [[False, True]], [1, 2, 3])
 2096 
 2097     def test_two_conditions(self):
 2098         x = piecewise([1, 2], [[True, False], [False, True]], [3, 4])
 2099         assert_array_equal(x, [3, 4])
 2100 
 2101     def test_scalar_domains_three_conditions(self):
 2102         x = piecewise(3, [True, False, False], [4, 2, 0])
 2103         assert_equal(x, 4)
 2104 
 2105     def test_default(self):
 2106         # No value specified for x[1], should be 0
 2107         x = piecewise([1, 2], [True, False], [2])
 2108         assert_array_equal(x, [2, 0])
 2109 
 2110         # Should set x[1] to 3
 2111         x = piecewise([1, 2], [True, False], [2, 3])
 2112         assert_array_equal(x, [2, 3])
 2113 
 2114     def test_0d(self):
 2115         x = np.array(3)
 2116         y = piecewise(x, x > 3, [4, 0])
 2117         assert_(y.ndim == 0)
 2118         assert_(y == 0)
 2119 
 2120         x = 5
 2121         y = piecewise(x, [True, False], [1, 0])
 2122         assert_(y.ndim == 0)
 2123         assert_(y == 1)
 2124 
 2125         # With 3 ranges (It was failing, before)
 2126         y = piecewise(x, [False, False, True], [1, 2, 3])
 2127         assert_array_equal(y, 3)
 2128 
 2129     def test_0d_comparison(self):
 2130         x = 3
 2131         y = piecewise(x, [x <= 3, x > 3], [4, 0])  # Should succeed.
 2132         assert_equal(y, 4)
 2133 
 2134         # With 3 ranges (It was failing, before)
 2135         x = 4
 2136         y = piecewise(x, [x <= 3, (x > 3) * (x <= 5), x > 5], [1, 2, 3])
 2137         assert_array_equal(y, 2)
 2138 
 2139         assert_raises_regex(ValueError, '2 or 3 functions are expected',
 2140             piecewise, x, [x <= 3, x > 3], [1])
 2141         assert_raises_regex(ValueError, '2 or 3 functions are expected',
 2142             piecewise, x, [x <= 3, x > 3], [1, 1, 1, 1])
 2143 
 2144     def test_0d_0d_condition(self):
 2145         x = np.array(3)
 2146         c = np.array(x > 3)
 2147         y = piecewise(x, [c], [1, 2])
 2148         assert_equal(y, 2)
 2149 
 2150     def test_multidimensional_extrafunc(self):
 2151         x = np.array([[-2.5, -1.5, -0.5],
 2152                       [0.5, 1.5, 2.5]])
 2153         y = piecewise(x, [x < 0, x >= 2], [-1, 1, 3])
 2154         assert_array_equal(y, np.array([[-1., -1., -1.],
 2155                                         [3., 3., 1.]]))
 2156 
 2157 
 2158 class TestBincount(object):
 2159 
 2160     def test_simple(self):
 2161         y = np.bincount(np.arange(4))
 2162         assert_array_equal(y, np.ones(4))
 2163 
 2164     def test_simple2(self):
 2165         y = np.bincount(np.array([1, 5, 2, 4, 1]))
 2166         assert_array_equal(y, np.array([0, 2, 1, 0, 1, 1]))
 2167 
 2168     def test_simple_weight(self):
 2169         x = np.arange(4)
 2170         w = np.array([0.2, 0.3, 0.5, 0.1])
 2171         y = np.bincount(x, w)
 2172         assert_array_equal(y, w)
 2173 
 2174     def test_simple_weight2(self):
 2175         x = np.array([1, 2, 4, 5, 2])
 2176         w = np.array([0.2, 0.3, 0.5, 0.1, 0.2])
 2177         y = np.bincount(x, w)
 2178         assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1]))
 2179 
 2180     def test_with_minlength(self):
 2181         x = np.array([0, 1, 0, 1, 1])
 2182         y = np.bincount(x, minlength=3)
 2183         assert_array_equal(y, np.array([2, 3, 0]))
 2184         x = []
 2185         y = np.bincount(x, minlength=0)
 2186         assert_array_equal(y, np.array([]))
 2187 
 2188     def test_with_minlength_smaller_than_maxvalue(self):
 2189         x = np.array([0, 1, 1, 2, 2, 3, 3])
 2190         y = np.bincount(x, minlength=2)
 2191         assert_array_equal(y, np.array([1, 2, 2, 2]))
 2192         y = np.bincount(x, minlength=0)
 2193         assert_array_equal(y, np.array([1, 2, 2, 2]))
 2194 
 2195     def test_with_minlength_and_weights(self):
 2196         x = np.array([1, 2, 4, 5, 2])
 2197         w = np.array([0.2, 0.3, 0.5, 0.1, 0.2])
 2198         y = np.bincount(x, w, 8)
 2199         assert_array_equal(y, np.array([0, 0.2, 0.5, 0, 0.5, 0.1, 0, 0]))
 2200 
 2201     def test_empty(self):
 2202         x = np.array([], dtype=int)
 2203         y = np.bincount(x)
 2204         assert_array_equal(x, y)
 2205 
 2206     def test_empty_with_minlength(self):
 2207         x = np.array([], dtype=int)
 2208         y = np.bincount(x, minlength=5)
 2209         assert_array_equal(y, np.zeros(5, dtype=int))
 2210 
 2211     def test_with_incorrect_minlength(self):
 2212         x = np.array([], dtype=int)
 2213         assert_raises_regex(TypeError,
 2214                             "'str' object cannot be interpreted",
 2215                             lambda: np.bincount(x, minlength="foobar"))
 2216         assert_raises_regex(ValueError,
 2217                             "must not be negative",
 2218                             lambda: np.bincount(x, minlength=-1))
 2219 
 2220         x = np.arange(5)
 2221         assert_raises_regex(TypeError,
 2222                             "'str' object cannot be interpreted",
 2223                             lambda: np.bincount(x, minlength="foobar"))
 2224         assert_raises_regex(ValueError,
 2225                             "must not be negative",
 2226                             lambda: np.bincount(x, minlength=-1))
 2227 
 2228     @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
 2229     def test_dtype_reference_leaks(self):
 2230         # gh-6805
 2231         intp_refcount = sys.getrefcount(np.dtype(np.intp))
 2232         double_refcount = sys.getrefcount(np.dtype(np.double))
 2233 
 2234         for j in range(10):
 2235             np.bincount([1, 2, 3])
 2236         assert_equal(sys.getrefcount(np.dtype(np.intp)), intp_refcount)
 2237         assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount)
 2238 
 2239         for j in range(10):
 2240             np.bincount([1, 2, 3], [4, 5, 6])
 2241         assert_equal(sys.getrefcount(np.dtype(np.intp)), intp_refcount)
 2242         assert_equal(sys.getrefcount(np.dtype(np.double)), double_refcount)
 2243 
 2244 
 2245 class TestInterp(object):
 2246 
 2247     def test_exceptions(self):
 2248         assert_raises(ValueError, interp, 0, [], [])
 2249         assert_raises(ValueError, interp, 0, [0], [1, 2])
 2250         assert_raises(ValueError, interp, 0, [0, 1], [1, 2], period=0)
 2251         assert_raises(ValueError, interp, 0, [], [], period=360)
 2252         assert_raises(ValueError, interp, 0, [0], [1, 2], period=360)
 2253 
 2254     def test_basic(self):
 2255         x = np.linspace(0, 1, 5)
 2256         y = np.linspace(0, 1, 5)
 2257         x0 = np.linspace(0, 1, 50)
 2258         assert_almost_equal(np.interp(x0, x, y), x0)
 2259 
 2260     def test_right_left_behavior(self):
 2261         # Needs range of sizes to test different code paths.
 2262         # size ==1 is special cased, 1 < size < 5 is linear search, and
 2263         # size >= 5 goes through local search and possibly binary search.
 2264         for size in range(1, 10):
 2265             xp = np.arange(size, dtype=np.double)
 2266             yp = np.ones(size, dtype=np.double)
 2267             incpts = np.array([-1, 0, size - 1, size], dtype=np.double)
 2268             decpts = incpts[::-1]
 2269 
 2270             incres = interp(incpts, xp, yp)
 2271             decres = interp(decpts, xp, yp)
 2272             inctgt = np.array([1, 1, 1, 1], dtype=float)
 2273             dectgt = inctgt[::-1]
 2274             assert_equal(incres, inctgt)
 2275             assert_equal(decres, dectgt)
 2276 
 2277             incres = interp(incpts, xp, yp, left=0)
 2278             decres = interp(decpts, xp, yp, left=0)
 2279             inctgt = np.array([0, 1, 1, 1], dtype=float)
 2280             dectgt = inctgt[::-1]
 2281             assert_equal(incres, inctgt)
 2282             assert_equal(decres, dectgt)
 2283 
 2284             incres = interp(incpts, xp, yp, right=2)
 2285             decres = interp(decpts, xp, yp, right=2)
 2286             inctgt = np.array([1, 1, 1, 2], dtype=float)
 2287             dectgt = inctgt[::-1]
 2288             assert_equal(incres, inctgt)
 2289             assert_equal(decres, dectgt)
 2290 
 2291             incres = interp(incpts, xp, yp, left=0, right=2)
 2292             decres = interp(decpts, xp, yp, left=0, right=2)
 2293             inctgt = np.array([0, 1, 1, 2], dtype=float)
 2294             dectgt = inctgt[::-1]
 2295             assert_equal(incres, inctgt)
 2296             assert_equal(decres, dectgt)
 2297 
 2298     def test_scalar_interpolation_point(self):
 2299         x = np.linspace(0, 1, 5)
 2300         y = np.linspace(0, 1, 5)
 2301         x0 = 0
 2302         assert_almost_equal(np.interp(x0, x, y), x0)
 2303         x0 = .3
 2304         assert_almost_equal(np.interp(x0, x, y), x0)
 2305         x0 = np.float32(.3)
 2306         assert_almost_equal(np.interp(x0, x, y), x0)
 2307         x0 = np.float64(.3)
 2308         assert_almost_equal(np.interp(x0, x, y), x0)
 2309         x0 = np.nan
 2310         assert_almost_equal(np.interp(x0, x, y), x0)
 2311 
 2312     def test_non_finite_behavior(self):
 2313         x = [1, 2, 2.5, 3, 4]
 2314         xp = [1, 2, 3, 4]
 2315         fp = [1, 2, np.inf, 4]
 2316         assert_almost_equal(np.interp(x, xp, fp), [1, 2, np.inf, np.inf, 4])
 2317         fp = [1, 2, np.nan, 4]
 2318         assert_almost_equal(np.interp(x, xp, fp), [1, 2, np.nan, np.nan, 4])
 2319 
 2320     def test_complex_interp(self):
 2321         # test complex interpolation
 2322         x = np.linspace(0, 1, 5)
 2323         y = np.linspace(0, 1, 5) + (1 + np.linspace(0, 1, 5))*1.0j
 2324         x0 = 0.3
 2325         y0 = x0 + (1+x0)*1.0j
 2326         assert_almost_equal(np.interp(x0, x, y), y0)
 2327         # test complex left and right
 2328         x0 = -1
 2329         left = 2 + 3.0j
 2330         assert_almost_equal(np.interp(x0, x, y, left=left), left)
 2331         x0 = 2.0
 2332         right = 2 + 3.0j
 2333         assert_almost_equal(np.interp(x0, x, y, right=right), right)
 2334         # test complex non finite
 2335         x = [1, 2, 2.5, 3, 4]
 2336         xp = [1, 2, 3, 4]
 2337         fp = [1, 2+1j, np.inf, 4]
 2338         y = [1, 2+1j, np.inf+0.5j, np.inf, 4]
 2339         assert_almost_equal(np.interp(x, xp, fp), y)
 2340         # test complex periodic
 2341         x = [-180, -170, -185, 185, -10, -5, 0, 365]
 2342         xp = [190, -190, 350, -350]
 2343         fp = [5+1.0j, 10+2j, 3+3j, 4+4j]
 2344         y = [7.5+1.5j, 5.+1.0j, 8.75+1.75j, 6.25+1.25j, 3.+3j, 3.25+3.25j,
 2345              3.5+3.5j, 3.75+3.75j]
 2346         assert_almost_equal(np.interp(x, xp, fp, period=360), y)
 2347 
 2348     def test_zero_dimensional_interpolation_point(self):
 2349         x = np.linspace(0, 1, 5)
 2350         y = np.linspace(0, 1, 5)
 2351         x0 = np.array(.3)
 2352         assert_almost_equal(np.interp(x0, x, y), x0)
 2353 
 2354         xp = np.array([0, 2, 4])
 2355         fp = np.array([1, -1, 1])
 2356 
 2357         actual = np.interp(np.array(1), xp, fp)
 2358         assert_equal(actual, 0)
 2359         assert_(isinstance(actual, np.float64))
 2360 
 2361         actual = np.interp(np.array(4.5), xp, fp, period=4)
 2362         assert_equal(actual, 0.5)
 2363         assert_(isinstance(actual, np.float64))
 2364 
 2365     def test_if_len_x_is_small(self):
 2366         xp = np.arange(0, 10, 0.0001)
 2367         fp = np.sin(xp)
 2368         assert_almost_equal(np.interp(np.pi, xp, fp), 0.0)
 2369 
 2370     def test_period(self):
 2371         x = [-180, -170, -185, 185, -10, -5, 0, 365]
 2372         xp = [190, -190, 350, -350]
 2373         fp = [5, 10, 3, 4]
 2374         y = [7.5, 5., 8.75, 6.25, 3., 3.25, 3.5, 3.75]
 2375         assert_almost_equal(np.interp(x, xp, fp, period=360), y)
 2376         x = np.array(x, order='F').reshape(2, -1)
 2377         y = np.array(y, order='C').reshape(2, -1)
 2378         assert_almost_equal(np.interp(x, xp, fp, period=360), y)
 2379 
 2380 
 2381 def compare_results(res, desired):
 2382     for i in range(len(desired)):
 2383         assert_array_equal(res[i], desired[i])
 2384 
 2385 
 2386 class TestPercentile(object):
 2387 
 2388     def test_basic(self):
 2389         x = np.arange(8) * 0.5
 2390         assert_equal(np.percentile(x, 0), 0.)
 2391         assert_equal(np.percentile(x, 100), 3.5)
 2392         assert_equal(np.percentile(x, 50), 1.75)
 2393         x[1] = np.nan
 2394         with warnings.catch_warnings(record=True) as w:
 2395             warnings.filterwarnings('always', '', RuntimeWarning)
 2396             assert_equal(np.percentile(x, 0), np.nan)
 2397             assert_equal(np.percentile(x, 0, interpolation='nearest'), np.nan)
 2398             assert_(w[0].category is RuntimeWarning)
 2399 
 2400     def test_api(self):
 2401         d = np.ones(5)
 2402         np.percentile(d, 5, None, None, False)
 2403         np.percentile(d, 5, None, None, False, 'linear')
 2404         o = np.ones((1,))
 2405         np.percentile(d, 5, None, o, False, 'linear')
 2406 
 2407     def test_2D(self):
 2408         x = np.array([[1, 1, 1],
 2409                       [1, 1, 1],
 2410                       [4, 4, 3],
 2411                       [1, 1, 1],
 2412                       [1, 1, 1]])
 2413         assert_array_equal(np.percentile(x, 50, axis=0), [1, 1, 1])
 2414 
 2415     def test_linear(self):
 2416 
 2417         # Test defaults
 2418         assert_equal(np.percentile(range(10), 50), 4.5)
 2419 
 2420         # explicitly specify interpolation_method 'linear' (the default)
 2421         assert_equal(np.percentile(range(10), 50,
 2422                                    interpolation='linear'), 4.5)
 2423 
 2424     def test_lower_higher(self):
 2425 
 2426         # interpolation_method 'lower'/'higher'
 2427         assert_equal(np.percentile(range(10), 50,
 2428                                    interpolation='lower'), 4)
 2429         assert_equal(np.percentile(range(10), 50,
 2430                                    interpolation='higher'), 5)
 2431 
 2432     def test_midpoint(self):
 2433         assert_equal(np.percentile(range(10), 51,
 2434                                    interpolation='midpoint'), 4.5)
 2435         assert_equal(np.percentile(range(11), 51,
 2436                                    interpolation='midpoint'), 5.5)
 2437         assert_equal(np.percentile(range(11), 50,
 2438                                    interpolation='midpoint'), 5)
 2439 
 2440     def test_nearest(self):
 2441         assert_equal(np.percentile(range(10), 51,
 2442                                    interpolation='nearest'), 5)
 2443         assert_equal(np.percentile(range(10), 49,
 2444                                    interpolation='nearest'), 4)
 2445 
 2446     def test_sequence(self):
 2447         x = np.arange(8) * 0.5
 2448         assert_equal(np.percentile(x, [0, 100, 50]), [0, 3.5, 1.75])
 2449 
 2450     def test_axis(self):
 2451         x = np.arange(12).reshape(3, 4)
 2452 
 2453         assert_equal(np.percentile(x, (25, 50, 100)), [2.75, 5.5, 11.0])
 2454 
 2455         r0 = [[2, 3, 4, 5], [4, 5, 6, 7], [8, 9, 10, 11]]
 2456         assert_equal(np.percentile(x, (25, 50, 100), axis=0), r0)
 2457 
 2458         r1 = [[0.75, 1.5, 3], [4.75, 5.5, 7], [8.75, 9.5, 11]]
 2459         assert_equal(np.percentile(x, (25, 50, 100), axis=1), np.array(r1).T)
 2460 
 2461         # ensure qth axis is always first as with np.array(old_percentile(..))
 2462         x = np.arange(3 * 4 * 5 * 6).reshape(3, 4, 5, 6)
 2463         assert_equal(np.percentile(x, (25, 50)).shape, (2,))
 2464         assert_equal(np.percentile(x, (25, 50, 75)).shape, (3,))
 2465         assert_equal(np.percentile(x, (25, 50), axis=0).shape, (2, 4, 5, 6))
 2466         assert_equal(np.percentile(x, (25, 50), axis=1).shape, (2, 3, 5, 6))
 2467         assert_equal(np.percentile(x, (25, 50), axis=2).shape, (2, 3, 4, 6))
 2468         assert_equal(np.percentile(x, (25, 50), axis=3).shape, (2, 3, 4, 5))
 2469         assert_equal(
 2470             np.percentile(x, (25, 50, 75), axis=1).shape, (3, 3, 5, 6))
 2471         assert_equal(np.percentile(x, (25, 50),
 2472                                    interpolation="higher").shape, (2,))
 2473         assert_equal(np.percentile(x, (25, 50, 75),
 2474                                    interpolation="higher").shape, (3,))
 2475         assert_equal(np.percentile(x, (25, 50), axis=0,
 2476                                    interpolation="higher").shape, (2, 4, 5, 6))
 2477         assert_equal(np.percentile(x, (25, 50), axis=1,
 2478                                    interpolation="higher").shape, (2, 3, 5, 6))
 2479         assert_equal(np.percentile(x, (25, 50), axis=2,
 2480                                    interpolation="higher").shape, (2, 3, 4, 6))
 2481         assert_equal(np.percentile(x, (25, 50), axis=3,
 2482                                    interpolation="higher").shape, (2, 3, 4, 5))
 2483         assert_equal(np.percentile(x, (25, 50, 75), axis=1,
 2484                                    interpolation="higher").shape, (3, 3, 5, 6))
 2485 
 2486     def test_scalar_q(self):
 2487         # test for no empty dimensions for compatibility with old percentile
 2488         x = np.arange(12).reshape(3, 4)
 2489         assert_equal(np.percentile(x, 50), 5.5)
 2490         assert_(np.isscalar(np.percentile(x, 50)))
 2491         r0 = np.array([4.,  5.,  6.,  7.])
 2492         assert_equal(np.percentile(x, 50, axis=0), r0)
 2493         assert_equal(np.percentile(x, 50, axis=0).shape, r0.shape)
 2494         r1 = np.array([1.5,  5.5,  9.5])
 2495         assert_almost_equal(np.percentile(x, 50, axis=1), r1)
 2496         assert_equal(np.percentile(x, 50, axis=1).shape, r1.shape)
 2497 
 2498         out = np.empty(1)
 2499         assert_equal(np.percentile(x, 50, out=out), 5.5)
 2500         assert_equal(out, 5.5)
 2501         out = np.empty(4)
 2502         assert_equal(np.percentile(x, 50, axis=0, out=out), r0)
 2503         assert_equal(out, r0)
 2504         out = np.empty(3)
 2505         assert_equal(np.percentile(x, 50, axis=1, out=out), r1)
 2506         assert_equal(out, r1)
 2507 
 2508         # test for no empty dimensions for compatibility with old percentile
 2509         x = np.arange(12).reshape(3, 4)
 2510         assert_equal(np.percentile(x, 50, interpolation='lower'), 5.)
 2511         assert_(np.isscalar(np.percentile(x, 50)))
 2512         r0 = np.array([4.,  5.,  6.,  7.])
 2513         c0 = np.percentile(x, 50, interpolation='lower', axis=0)
 2514         assert_equal(c0, r0)
 2515         assert_equal(c0.shape, r0.shape)
 2516         r1 = np.array([1.,  5.,  9.])
 2517         c1 = np.percentile(x, 50, interpolation='lower', axis=1)
 2518         assert_almost_equal(c1, r1)
 2519         assert_equal(c1.shape, r1.shape)
 2520 
 2521         out = np.empty((), dtype=x.dtype)
 2522         c = np.percentile(x, 50, interpolation='lower', out=out)
 2523         assert_equal(c, 5)
 2524         assert_equal(out, 5)
 2525         out = np.empty(4, dtype=x.dtype)
 2526         c = np.percentile(x, 50, interpolation='lower', axis=0, out=out)
 2527         assert_equal(c, r0)
 2528         assert_equal(out, r0)
 2529         out = np.empty(3, dtype=x.dtype)
 2530         c = np.percentile(x, 50, interpolation='lower', axis=1, out=out)
 2531         assert_equal(c, r1)
 2532         assert_equal(out, r1)
 2533 
 2534     def test_exception(self):
 2535         assert_raises(ValueError, np.percentile, [1, 2], 56,
 2536                       interpolation='foobar')
 2537         assert_raises(ValueError, np.percentile, [1], 101)
 2538         assert_raises(ValueError, np.percentile, [1], -1)
 2539         assert_raises(ValueError, np.percentile, [1], list(range(50)) + [101])
 2540         assert_raises(ValueError, np.percentile, [1], list(range(50)) + [-0.1])
 2541 
 2542     def test_percentile_list(self):
 2543         assert_equal(np.percentile([1, 2, 3], 0), 1)
 2544 
 2545     def test_percentile_out(self):
 2546         x = np.array([1, 2, 3])
 2547         y = np.zeros((3,))
 2548         p = (1, 2, 3)
 2549         np.percentile(x, p, out=y)
 2550         assert_equal(y, np.percentile(x, p))
 2551 
 2552         x = np.array([[1, 2, 3],
 2553                       [4, 5, 6]])
 2554 
 2555         y = np.zeros((3, 3))
 2556         np.percentile(x, p, axis=0, out=y)
 2557         assert_equal(y, np.percentile(x, p, axis=0))
 2558 
 2559         y = np.zeros((3, 2))
 2560         np.percentile(x, p, axis=1, out=y)
 2561         assert_equal(y, np.percentile(x, p, axis=1))
 2562 
 2563         x = np.arange(12).reshape(3, 4)
 2564         # q.dim > 1, float
 2565         r0 = np.array([[2.,  3.,  4., 5.], [4., 5., 6., 7.]])
 2566         out = np.empty((2, 4))
 2567         assert_equal(np.percentile(x, (25, 50), axis=0, out=out), r0)
 2568         assert_equal(out, r0)
 2569         r1 = np.array([[0.75,  4.75,  8.75], [1.5,  5.5,  9.5]])
 2570         out = np.empty((2, 3))
 2571         assert_equal(np.percentile(x, (25, 50), axis=1, out=out), r1)
 2572         assert_equal(out, r1)
 2573 
 2574         # q.dim > 1, int
 2575         r0 = np.array([[0,  1,  2, 3], [4, 5, 6, 7]])
 2576         out = np.empty((2, 4), dtype=x.dtype)
 2577         c = np.percentile(x, (25, 50), interpolation='lower', axis=0, out=out)
 2578         assert_equal(c, r0)
 2579         assert_equal(out, r0)
 2580         r1 = np.array([[0,  4,  8], [1,  5,  9]])
 2581         out = np.empty((2, 3), dtype=x.dtype)
 2582         c = np.percentile(x, (25, 50), interpolation='lower', axis=1, out=out)
 2583         assert_equal(c, r1)
 2584         assert_equal(out, r1)
 2585 
 2586     def test_percentile_empty_dim(self):
 2587         # empty dims are preserved
 2588         d = np.arange(11 * 2).reshape(11, 1, 2, 1)
 2589         assert_array_equal(np.percentile(d, 50, axis=0).shape, (1, 2, 1))
 2590         assert_array_equal(np.percentile(d, 50, axis=1).shape, (11, 2, 1))
 2591         assert_array_equal(np.percentile(d, 50, axis=2).shape, (11, 1, 1))
 2592         assert_array_equal(np.percentile(d, 50, axis=3).shape, (11, 1, 2))
 2593         assert_array_equal(np.percentile(d, 50, axis=-1).shape, (11, 1, 2))
 2594         assert_array_equal(np.percentile(d, 50, axis=-2).shape, (11, 1, 1))
 2595         assert_array_equal(np.percentile(d, 50, axis=-3).shape, (11, 2, 1))
 2596         assert_array_equal(np.percentile(d, 50, axis=-4).shape, (1, 2, 1))
 2597 
 2598         assert_array_equal(np.percentile(d, 50, axis=2,
 2599                                          interpolation='midpoint').shape,
 2600                            (11, 1, 1))
 2601         assert_array_equal(np.percentile(d, 50, axis=-2,
 2602                                          interpolation='midpoint').shape,
 2603                            (11, 1, 1))
 2604 
 2605         assert_array_equal(np.array(np.percentile(d, [10, 50], axis=0)).shape,
 2606                            (2, 1, 2, 1))
 2607         assert_array_equal(np.array(np.percentile(d, [10, 50], axis=1)).shape,
 2608                            (2, 11, 2, 1))
 2609         assert_array_equal(np.array(np.percentile(d, [10, 50], axis=2)).shape,
 2610                            (2, 11, 1, 1))
 2611         assert_array_equal(np.array(np.percentile(d, [10, 50], axis=3)).shape,
 2612                            (2, 11, 1, 2))
 2613 
 2614     def test_percentile_no_overwrite(self):
 2615         a = np.array([2, 3, 4, 1])
 2616         np.percentile(a, [50], overwrite_input=False)
 2617         assert_equal(a, np.array([2, 3, 4, 1]))
 2618 
 2619         a = np.array([2, 3, 4, 1])
 2620         np.percentile(a, [50])
 2621         assert_equal(a, np.array([2, 3, 4, 1]))
 2622 
 2623     def test_no_p_overwrite(self):
 2624         p = np.linspace(0., 100., num=5)
 2625         np.percentile(np.arange(100.), p, interpolation="midpoint")
 2626         assert_array_equal(p, np.linspace(0., 100., num=5))
 2627         p = np.linspace(0., 100., num=5).tolist()
 2628         np.percentile(np.arange(100.), p, interpolation="midpoint")
 2629         assert_array_equal(p, np.linspace(0., 100., num=5).tolist())
 2630 
 2631     def test_percentile_overwrite(self):
 2632         a = np.array([2, 3, 4, 1])
 2633         b = np.percentile(a, [50], overwrite_input=True)
 2634         assert_equal(b, np.array([2.5]))
 2635 
 2636         b = np.percentile([2, 3, 4, 1], [50], overwrite_input=True)
 2637         assert_equal(b, np.array([2.5]))
 2638 
 2639     def test_extended_axis(self):
 2640         o = np.random.normal(size=(71, 23))
 2641         x = np.dstack([o] * 10)
 2642         assert_equal(np.percentile(x, 30, axis=(0, 1)), np.percentile(o, 30))
 2643         x = np.moveaxis(x, -1, 0)
 2644         assert_equal(np.percentile(x, 30, axis=(-2, -1)), np.percentile(o, 30))
 2645         x = x.swapaxes(0, 1).copy()
 2646         assert_equal(np.percentile(x, 30, axis=(0, -1)), np.percentile(o, 30))
 2647         x = x.swapaxes(0, 1).copy()
 2648 
 2649         assert_equal(np.percentile(x, [25, 60], axis=(0, 1, 2)),
 2650                      np.percentile(x, [25, 60], axis=None))
 2651         assert_equal(np.percentile(x, [25, 60], axis=(0,)),
 2652                      np.percentile(x, [25, 60], axis=0))
 2653 
 2654         d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))
 2655         np.random.shuffle(d.ravel())
 2656         assert_equal(np.percentile(d, 25,  axis=(0, 1, 2))[0],
 2657                      np.percentile(d[:,:,:, 0].flatten(), 25))
 2658         assert_equal(np.percentile(d, [10, 90], axis=(0, 1, 3))[:, 1],
 2659                      np.percentile(d[:,:, 1,:].flatten(), [10, 90]))
 2660         assert_equal(np.percentile(d, 25, axis=(3, 1, -4))[2],
 2661                      np.percentile(d[:,:, 2,:].flatten(), 25))
 2662         assert_equal(np.percentile(d, 25, axis=(3, 1, 2))[2],
 2663                      np.percentile(d[2,:,:,:].flatten(), 25))
 2664         assert_equal(np.percentile(d, 25, axis=(3, 2))[2, 1],
 2665                      np.percentile(d[2, 1,:,:].flatten(), 25))
 2666         assert_equal(np.percentile(d, 25, axis=(1, -2))[2, 1],
 2667                      np.percentile(d[2,:,:, 1].flatten(), 25))
 2668         assert_equal(np.percentile(d, 25, axis=(1, 3))[2, 2],
 2669                      np.percentile(d[2,:, 2,:].flatten(), 25))
 2670 
 2671     def test_extended_axis_invalid(self):
 2672         d = np.ones((3, 5, 7, 11))
 2673         assert_raises(np.AxisError, np.percentile, d, axis=-5, q=25)
 2674         assert_raises(np.AxisError, np.percentile, d, axis=(0, -5), q=25)
 2675         assert_raises(np.AxisError, np.percentile, d, axis=4, q=25)
 2676         assert_raises(np.AxisError, np.percentile, d, axis=(0, 4), q=25)
 2677         # each of these refers to the same axis twice
 2678         assert_raises(ValueError, np.percentile, d, axis=(1, 1), q=25)
 2679         assert_raises(ValueError, np.percentile, d, axis=(-1, -1), q=25)
 2680         assert_raises(ValueError, np.percentile, d, axis=(3, -1), q=25)
 2681 
 2682     def test_keepdims(self):
 2683         d = np.ones((3, 5, 7, 11))
 2684         assert_equal(np.percentile(d, 7, axis=None, keepdims=True).shape,
 2685                      (1, 1, 1, 1))
 2686         assert_equal(np.percentile(d, 7, axis=(0, 1), keepdims=True).shape,
 2687                      (1, 1, 7, 11))
 2688         assert_equal(np.percentile(d, 7, axis=(0, 3), keepdims=True).shape,
 2689                      (1, 5, 7, 1))
 2690         assert_equal(np.percentile(d, 7, axis=(1,), keepdims=True).shape,
 2691                      (3, 1, 7, 11))
 2692         assert_equal(np.percentile(d, 7, (0, 1, 2, 3), keepdims=True).shape,
 2693                      (1, 1, 1, 1))
 2694         assert_equal(np.percentile(d, 7, axis=(0, 1, 3), keepdims=True).shape,
 2695                      (1, 1, 7, 1))
 2696 
 2697         assert_equal(np.percentile(d, [1, 7], axis=(0, 1, 3),
 2698                                    keepdims=True).shape, (2, 1, 1, 7, 1))
 2699         assert_equal(np.percentile(d, [1, 7], axis=(0, 3),
 2700                                    keepdims=True).shape, (2, 1, 5, 7, 1))
 2701 
 2702     def test_out(self):
 2703         o = np.zeros((4,))
 2704         d = np.ones((3, 4))
 2705         assert_equal(np.percentile(d, 0, 0, out=o), o)
 2706         assert_equal(np.percentile(d, 0, 0, interpolation='nearest', out=o), o)
 2707         o = np.zeros((3,))
 2708         assert_equal(np.percentile(d, 1, 1, out=o), o)
 2709         assert_equal(np.percentile(d, 1, 1, interpolation='nearest', out=o), o)
 2710 
 2711         o = np.zeros(())
 2712         assert_equal(np.percentile(d, 2, out=o), o)
 2713         assert_equal(np.percentile(d, 2, interpolation='nearest', out=o), o)
 2714 
 2715     def test_out_nan(self):
 2716         with warnings.catch_warnings(record=True):
 2717             warnings.filterwarnings('always', '', RuntimeWarning)
 2718             o = np.zeros((4,))
 2719             d = np.ones((3, 4))
 2720             d[2, 1] = np.nan
 2721             assert_equal(np.percentile(d, 0, 0, out=o), o)
 2722             assert_equal(
 2723                 np.percentile(d, 0, 0, interpolation='nearest', out=o), o)
 2724             o = np.zeros((3,))
 2725             assert_equal(np.percentile(d, 1, 1, out=o), o)
 2726             assert_equal(
 2727                 np.percentile(d, 1, 1, interpolation='nearest', out=o), o)
 2728             o = np.zeros(())
 2729             assert_equal(np.percentile(d, 1, out=o), o)
 2730             assert_equal(
 2731                 np.percentile(d, 1, interpolation='nearest', out=o), o)
 2732 
 2733     def test_nan_behavior(self):
 2734         a = np.arange(24, dtype=float)
 2735         a[2] = np.nan
 2736         with warnings.catch_warnings(record=True) as w:
 2737             warnings.filterwarnings('always', '', RuntimeWarning)
 2738             assert_equal(np.percentile(a, 0.3), np.nan)
 2739             assert_equal(np.percentile(a, 0.3, axis=0), np.nan)
 2740             assert_equal(np.percentile(a, [0.3, 0.6], axis=0),
 2741                          np.array([np.nan] * 2))
 2742             assert_(w[0].category is RuntimeWarning)
 2743             assert_(w[1].category is RuntimeWarning)
 2744             assert_(w[2].category is RuntimeWarning)
 2745 
 2746         a = np.arange(24, dtype=float).reshape(2, 3, 4)
 2747         a[1, 2, 3] = np.nan
 2748         a[1, 1, 2] = np.nan
 2749 
 2750         # no axis
 2751         with warnings.catch_warnings(record=True) as w:
 2752             warnings.filterwarnings('always', '', RuntimeWarning)
 2753             assert_equal(np.percentile(a, 0.3), np.nan)
 2754             assert_equal(np.percentile(a, 0.3).ndim, 0)
 2755             assert_(w[0].category is RuntimeWarning)
 2756 
 2757         # axis0 zerod
 2758         b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 0)
 2759         b[2, 3] = np.nan
 2760         b[1, 2] = np.nan
 2761         with warnings.catch_warnings(record=True) as w:
 2762             warnings.filterwarnings('always', '', RuntimeWarning)
 2763             assert_equal(np.percentile(a, 0.3, 0), b)
 2764 
 2765         # axis0 not zerod
 2766         b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
 2767                           [0.3, 0.6], 0)
 2768         b[:, 2, 3] = np.nan
 2769         b[:, 1, 2] = np.nan
 2770         with warnings.catch_warnings(record=True) as w:
 2771             warnings.filterwarnings('always', '', RuntimeWarning)
 2772             assert_equal(np.percentile(a, [0.3, 0.6], 0), b)
 2773 
 2774         # axis1 zerod
 2775         b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, 1)
 2776         b[1, 3] = np.nan
 2777         b[1, 2] = np.nan
 2778         with warnings.catch_warnings(record=True) as w:
 2779             warnings.filterwarnings('always', '', RuntimeWarning)
 2780             assert_equal(np.percentile(a, 0.3, 1), b)
 2781         # axis1 not zerod
 2782         b = np.percentile(
 2783             np.arange(24, dtype=float).reshape(2, 3, 4), [0.3, 0.6], 1)
 2784         b[:, 1, 3] = np.nan
 2785         b[:, 1, 2] = np.nan
 2786         with warnings.catch_warnings(record=True) as w:
 2787             warnings.filterwarnings('always', '', RuntimeWarning)
 2788             assert_equal(np.percentile(a, [0.3, 0.6], 1), b)
 2789 
 2790         # axis02 zerod
 2791         b = np.percentile(
 2792             np.arange(24, dtype=float).reshape(2, 3, 4), 0.3, (0, 2))
 2793         b[1] = np.nan
 2794         b[2] = np.nan
 2795         with warnings.catch_warnings(record=True) as w:
 2796             warnings.filterwarnings('always', '', RuntimeWarning)
 2797             assert_equal(np.percentile(a, 0.3, (0, 2)), b)
 2798         # axis02 not zerod
 2799         b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
 2800                           [0.3, 0.6], (0, 2))
 2801         b[:, 1] = np.nan
 2802         b[:, 2] = np.nan
 2803         with warnings.catch_warnings(record=True) as w:
 2804             warnings.filterwarnings('always', '', RuntimeWarning)
 2805             assert_equal(np.percentile(a, [0.3, 0.6], (0, 2)), b)
 2806         # axis02 not zerod with nearest interpolation
 2807         b = np.percentile(np.arange(24, dtype=float).reshape(2, 3, 4),
 2808                           [0.3, 0.6], (0, 2), interpolation='nearest')
 2809         b[:, 1] = np.nan
 2810         b[:, 2] = np.nan
 2811         with warnings.catch_warnings(record=True) as w:
 2812             warnings.filterwarnings('always', '', RuntimeWarning)
 2813             assert_equal(np.percentile(
 2814                 a, [0.3, 0.6], (0, 2), interpolation='nearest'), b)
 2815 
 2816 
 2817 class TestQuantile(object):
 2818     # most of this is already tested by TestPercentile
 2819 
 2820     def test_basic(self):
 2821         x = np.arange(8) * 0.5
 2822         assert_equal(np.quantile(x, 0), 0.)
 2823         assert_equal(np.quantile(x, 1), 3.5)
 2824         assert_equal(np.quantile(x, 0.5), 1.75)
 2825 
 2826     def test_no_p_overwrite(self):
 2827         # this is worth retesting, because quantile does not make a copy
 2828         p0 = np.array([0, 0.75, 0.25, 0.5, 1.0])
 2829         p = p0.copy()
 2830         np.quantile(np.arange(100.), p, interpolation="midpoint")
 2831         assert_array_equal(p, p0)
 2832 
 2833         p0 = p0.tolist()
 2834         p = p.tolist()
 2835         np.quantile(np.arange(100.), p, interpolation="midpoint")
 2836         assert_array_equal(p, p0)
 2837 
 2838 
 2839 class TestMedian(object):
 2840 
 2841     def test_basic(self):
 2842         a0 = np.array(1)
 2843         a1 = np.arange(2)
 2844         a2 = np.arange(6).reshape(2, 3)
 2845         assert_equal(np.median(a0), 1)
 2846         assert_allclose(np.median(a1), 0.5)
 2847         assert_allclose(np.median(a2), 2.5)
 2848         assert_allclose(np.median(a2, axis=0), [1.5,  2.5,  3.5])
 2849         assert_equal(np.median(a2, axis=1), [1, 4])
 2850         assert_allclose(np.median(a2, axis=None), 2.5)
 2851 
 2852         a = np.array([0.0444502, 0.0463301, 0.141249, 0.0606775])
 2853         assert_almost_equal((a[1] + a[3]) / 2., np.median(a))
 2854         a = np.array([0.0463301, 0.0444502, 0.141249])
 2855         assert_equal(a[0], np.median(a))
 2856         a = np.array([0.0444502, 0.141249, 0.0463301])
 2857         assert_equal(a[-1], np.median(a))
 2858         # check array scalar result
 2859         assert_equal(np.median(a).ndim, 0)
 2860         a[1] = np.nan
 2861         with warnings.catch_warnings(record=True) as w:
 2862             warnings.filterwarnings('always', '', RuntimeWarning)
 2863             assert_equal(np.median(a).ndim, 0)
 2864             assert_(w[0].category is RuntimeWarning)
 2865 
 2866     def test_axis_keyword(self):
 2867         a3 = np.array([[2, 3],
 2868                        [0, 1],
 2869                        [6, 7],
 2870                        [4, 5]])
 2871         for a in [a3, np.random.randint(0, 100, size=(2, 3, 4))]:
 2872             orig = a.copy()
 2873             np.median(a, axis=None)
 2874             for ax in range(a.ndim):
 2875                 np.median(a, axis=ax)
 2876             assert_array_equal(a, orig)
 2877 
 2878         assert_allclose(np.median(a3, axis=0), [3,  4])
 2879         assert_allclose(np.median(a3.T, axis=1), [3,  4])
 2880         assert_allclose(np.median(a3), 3.5)
 2881         assert_allclose(np.median(a3, axis=None), 3.5)
 2882         assert_allclose(np.median(a3.T), 3.5)
 2883 
 2884     def test_overwrite_keyword(self):
 2885         a3 = np.array([[2, 3],
 2886                        [0, 1],
 2887                        [6, 7],
 2888                        [4, 5]])
 2889         a0 = np.array(1)
 2890         a1 = np.arange(2)
 2891         a2 = np.arange(6).reshape(2, 3)
 2892         assert_allclose(np.median(a0.copy(), overwrite_input=True), 1)
 2893         assert_allclose(np.median(a1.copy(), overwrite_input=True), 0.5)
 2894         assert_allclose(np.median(a2.copy(), overwrite_input=True), 2.5)
 2895         assert_allclose(np.median(a2.copy(), overwrite_input=True, axis=0),
 2896                         [1.5,  2.5,  3.5])
 2897         assert_allclose(
 2898             np.median(a2.copy(), overwrite_input=True, axis=1), [1, 4])
 2899         assert_allclose(
 2900             np.median(a2.copy(), overwrite_input=True, axis=None), 2.5)
 2901         assert_allclose(
 2902             np.median(a3.copy(), overwrite_input=True, axis=0), [3,  4])
 2903         assert_allclose(np.median(a3.T.copy(), overwrite_input=True, axis=1),
 2904                         [3,  4])
 2905 
 2906         a4 = np.arange(3 * 4 * 5, dtype=np.float32).reshape((3, 4, 5))
 2907         np.random.shuffle(a4.ravel())
 2908         assert_allclose(np.median(a4, axis=None),
 2909                         np.median(a4.copy(), axis=None, overwrite_input=True))
 2910         assert_allclose(np.median(a4, axis=0),
 2911                         np.median(a4.copy(), axis=0, overwrite_input=True))
 2912         assert_allclose(np.median(a4, axis=1),
 2913                         np.median(a4.copy(), axis=1, overwrite_input=True))
 2914         assert_allclose(np.median(a4, axis=2),
 2915                         np.median(a4.copy(), axis=2, overwrite_input=True))
 2916 
 2917     def test_array_like(self):
 2918         x = [1, 2, 3]
 2919         assert_almost_equal(np.median(x), 2)
 2920         x2 = [x]
 2921         assert_almost_equal(np.median(x2), 2)
 2922         assert_allclose(np.median(x2, axis=0), x)
 2923 
 2924     def test_subclass(self):
 2925         # gh-3846
 2926         class MySubClass(np.ndarray):
 2927 
 2928             def __new__(cls, input_array, info=None):
 2929                 obj = np.asarray(input_array).view(cls)
 2930                 obj.info = info
 2931                 return obj
 2932 
 2933             def mean(self, axis=None, dtype=None, out=None):
 2934                 return -7
 2935 
 2936         a = MySubClass([1, 2, 3])
 2937         assert_equal(np.median(a), -7)
 2938 
 2939     def test_out(self):
 2940         o = np.zeros((4,))
 2941         d = np.ones((3, 4))
 2942         assert_equal(np.median(d, 0, out=o), o)
 2943         o = np.zeros((3,))
 2944         assert_equal(np.median(d, 1, out=o), o)
 2945         o = np.zeros(())
 2946         assert_equal(np.median(d, out=o), o)
 2947 
 2948     def test_out_nan(self):
 2949         with warnings.catch_warnings(record=True):
 2950             warnings.filterwarnings('always', '', RuntimeWarning)
 2951             o = np.zeros((4,))
 2952             d = np.ones((3, 4))
 2953             d[2, 1] = np.nan
 2954             assert_equal(np.median(d, 0, out=o), o)
 2955             o = np.zeros((3,))
 2956             assert_equal(np.median(d, 1, out=o), o)
 2957             o = np.zeros(())
 2958             assert_equal(np.median(d, out=o), o)
 2959 
 2960     def test_nan_behavior(self):
 2961         a = np.arange(24, dtype=float)
 2962         a[2] = np.nan
 2963         with warnings.catch_warnings(record=True) as w:
 2964             warnings.filterwarnings('always', '', RuntimeWarning)
 2965             assert_equal(np.median(a), np.nan)
 2966             assert_equal(np.median(a, axis=0), np.nan)
 2967             assert_(w[0].category is RuntimeWarning)
 2968             assert_(w[1].category is RuntimeWarning)
 2969 
 2970         a = np.arange(24, dtype=float).reshape(2, 3, 4)
 2971         a[1, 2, 3] = np.nan
 2972         a[1, 1, 2] = np.nan
 2973 
 2974         # no axis
 2975         with warnings.catch_warnings(record=True) as w:
 2976             warnings.filterwarnings('always', '', RuntimeWarning)
 2977             assert_equal(np.median(a), np.nan)
 2978             assert_equal(np.median(a).ndim, 0)
 2979             assert_(w[0].category is RuntimeWarning)
 2980 
 2981         # axis0
 2982         b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), 0)
 2983         b[2, 3] = np.nan
 2984         b[1, 2] = np.nan
 2985         with warnings.catch_warnings(record=True) as w:
 2986             warnings.filterwarnings('always', '', RuntimeWarning)
 2987             assert_equal(np.median(a, 0), b)
 2988             assert_equal(len(w), 1)
 2989 
 2990         # axis1
 2991         b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), 1)
 2992         b[1, 3] = np.nan
 2993         b[1, 2] = np.nan
 2994         with warnings.catch_warnings(record=True) as w:
 2995             warnings.filterwarnings('always', '', RuntimeWarning)
 2996             assert_equal(np.median(a, 1), b)
 2997             assert_equal(len(w), 1)
 2998 
 2999         # axis02
 3000         b = np.median(np.arange(24, dtype=float).reshape(2, 3, 4), (0, 2))
 3001         b[1] = np.nan
 3002         b[2] = np.nan
 3003         with warnings.catch_warnings(record=True) as w:
 3004             warnings.filterwarnings('always', '', RuntimeWarning)
 3005             assert_equal(np.median(a, (0, 2)), b)
 3006             assert_equal(len(w), 1)
 3007 
 3008     def test_empty(self):
 3009         # empty arrays
 3010         a = np.array([], dtype=float)
 3011         with warnings.catch_warnings(record=True) as w:
 3012             warnings.filterwarnings('always', '', RuntimeWarning)
 3013             assert_equal(np.median(a), np.nan)
 3014             assert_(w[0].category is RuntimeWarning)
 3015 
 3016         # multiple dimensions
 3017         a = np.array([], dtype=float, ndmin=3)
 3018         # no axis
 3019         with warnings.catch_warnings(record=True) as w:
 3020             warnings.filterwarnings('always', '', RuntimeWarning)
 3021             assert_equal(np.median(a), np.nan)
 3022             assert_(w[0].category is RuntimeWarning)
 3023 
 3024         # axis 0 and 1
 3025         b = np.array([], dtype=float, ndmin=2)
 3026         assert_equal(np.median(a, axis=0), b)
 3027         assert_equal(np.median(a, axis=1), b)
 3028 
 3029         # axis 2
 3030         b = np.array(np.nan, dtype=float, ndmin=2)
 3031         with warnings.catch_warnings(record=True) as w:
 3032             warnings.filterwarnings('always', '', RuntimeWarning)
 3033             assert_equal(np.median(a, axis=2), b)
 3034             assert_(w[0].category is RuntimeWarning)
 3035 
 3036     def test_object(self):
 3037         o = np.arange(7.)
 3038         assert_(type(np.median(o.astype(object))), float)
 3039         o[2] = np.nan
 3040         assert_(type(np.median(o.astype(object))), float)
 3041 
 3042     def test_extended_axis(self):
 3043         o = np.random.normal(size=(71, 23))
 3044         x = np.dstack([o] * 10)
 3045         assert_equal(np.median(x, axis=(0, 1)), np.median(o))
 3046         x = np.moveaxis(x, -1, 0)
 3047         assert_equal(np.median(x, axis=(-2, -1)), np.median(o))
 3048         x = x.swapaxes(0, 1).copy()
 3049         assert_equal(np.median(x, axis=(0, -1)), np.median(o))
 3050 
 3051         assert_equal(np.median(x, axis=(0, 1, 2)), np.median(x, axis=None))
 3052         assert_equal(np.median(x, axis=(0, )), np.median(x, axis=0))
 3053         assert_equal(np.median(x, axis=(-1, )), np.median(x, axis=-1))
 3054 
 3055         d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))
 3056         np.random.shuffle(d.ravel())
 3057         assert_equal(np.median(d, axis=(0, 1, 2))[0],
 3058                      np.median(d[:,:,:, 0].flatten()))
 3059         assert_equal(np.median(d, axis=(0, 1, 3))[1],
 3060                      np.median(d[:,:, 1,:].flatten()))
 3061         assert_equal(np.median(d, axis=(3, 1, -4))[2],
 3062                      np.median(d[:,:, 2,:].flatten()))
 3063         assert_equal(np.median(d, axis=(3, 1, 2))[2],
 3064                      np.median(d[2,:,:,:].flatten()))
 3065         assert_equal(np.median(d, axis=(3, 2))[2, 1],
 3066                      np.median(d[2, 1,:,:].flatten()))
 3067         assert_equal(np.median(d, axis=(1, -2))[2, 1],
 3068                      np.median(d[2,:,:, 1].flatten()))
 3069         assert_equal(np.median(d, axis=(1, 3))[2, 2],
 3070                      np.median(d[2,:, 2,:].flatten()))
 3071 
 3072     def test_extended_axis_invalid(self):
 3073         d = np.ones((3, 5, 7, 11))
 3074         assert_raises(np.AxisError, np.median, d, axis=-5)
 3075         assert_raises(np.AxisError, np.median, d, axis=(0, -5))
 3076         assert_raises(np.AxisError, np.median, d, axis=4)
 3077         assert_raises(np.AxisError, np.median, d, axis=(0, 4))
 3078         assert_raises(ValueError, np.median, d, axis=(1, 1))
 3079 
 3080     def test_keepdims(self):
 3081         d = np.ones((3, 5, 7, 11))
 3082         assert_equal(np.median(d, axis=None, keepdims=True).shape,
 3083                      (1, 1, 1, 1))
 3084         assert_equal(np.median(d, axis=(0, 1), keepdims=True).shape,
 3085                      (1, 1, 7, 11))
 3086         assert_equal(np.median(d, axis=(0, 3), keepdims=True).shape,
 3087                      (1, 5, 7, 1))
 3088         assert_equal(np.median(d, axis=(1,), keepdims=True).shape,
 3089                      (3, 1, 7, 11))
 3090         assert_equal(np.median(d, axis=(0, 1, 2, 3), keepdims=True).shape,
 3091                      (1, 1, 1, 1))
 3092         assert_equal(np.median(d, axis=(0, 1, 3), keepdims=True).shape,
 3093                      (1, 1, 7, 1))
 3094 
 3095 
 3096 class TestAdd_newdoc_ufunc(object):
 3097 
 3098     def test_ufunc_arg(self):
 3099         assert_raises(TypeError, add_newdoc_ufunc, 2, "blah")
 3100         assert_raises(ValueError, add_newdoc_ufunc, np.add, "blah")
 3101 
 3102     def test_string_arg(self):
 3103         assert_raises(TypeError, add_newdoc_ufunc, np.add, 3)
 3104 
 3105 
 3106 class TestAdd_newdoc(object):
 3107 
 3108     @pytest.mark.skipif(sys.flags.optimize == 2, reason="Python running -OO")
 3109     def test_add_doc(self):
 3110         # test np.add_newdoc
 3111         tgt = "Current flat index into the array."
 3112         assert_equal(np.core.flatiter.index.__doc__[:len(tgt)], tgt)
 3113         assert_(len(np.core.ufunc.identity.__doc__) > 300)
 3114         assert_(len(np.lib.index_tricks.mgrid.__doc__) > 300)
 3115 
 3116 class TestSortComplex(object):
 3117 
 3118     @pytest.mark.parametrize("type_in, type_out", [
 3119         ('l', 'D'),
 3120         ('h', 'F'),
 3121         ('H', 'F'),
 3122         ('b', 'F'),
 3123         ('B', 'F'),
 3124         ('g', 'G'),
 3125         ])
 3126     def test_sort_real(self, type_in, type_out):
 3127         # sort_complex() type casting for real input types
 3128         a = np.array([5, 3, 6, 2, 1], dtype=type_in)
 3129         actual = np.sort_complex(a)
 3130         expected = np.sort(a).astype(type_out)
 3131         assert_equal(actual, expected)
 3132         assert_equal(actual.dtype, expected.dtype)
 3133 
 3134     def test_sort_complex(self):
 3135         # sort_complex() handling of complex input
 3136         a = np.array([2 + 3j, 1 - 2j, 1 - 3j, 2 + 1j], dtype='D')
 3137         expected = np.array([1 - 3j, 1 - 2j, 2 + 1j, 2 + 3j], dtype='D')
 3138         actual = np.sort_complex(a)
 3139         assert_equal(actual, expected)
 3140         assert_equal(actual.dtype, expected.dtype)