summaryrefslogtreecommitdiff
path: root/numpy/lib/tests
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/lib/tests')
-rw-r--r--numpy/lib/tests/test__datasource.py317
-rw-r--r--numpy/lib/tests/test_arraysetops.py156
-rw-r--r--numpy/lib/tests/test_arrayterator.py43
-rw-r--r--numpy/lib/tests/test_financial.py57
-rw-r--r--numpy/lib/tests/test_format.py554
-rw-r--r--numpy/lib/tests/test_function_base.py850
-rw-r--r--numpy/lib/tests/test_getlimits.py55
-rw-r--r--numpy/lib/tests/test_index_tricks.py66
-rw-r--r--numpy/lib/tests/test_io.py306
-rw-r--r--numpy/lib/tests/test_machar.py31
-rw-r--r--numpy/lib/tests/test_polynomial.py115
-rw-r--r--numpy/lib/tests/test_regression.py30
-rw-r--r--numpy/lib/tests/test_shape_base.py454
-rw-r--r--numpy/lib/tests/test_stride_tricks.py208
-rw-r--r--numpy/lib/tests/test_twodim_base.py197
-rw-r--r--numpy/lib/tests/test_type_check.py291
-rw-r--r--numpy/lib/tests/test_ufunclike.py67
17 files changed, 3797 insertions, 0 deletions
diff --git a/numpy/lib/tests/test__datasource.py b/numpy/lib/tests/test__datasource.py
new file mode 100644
index 000000000..90a137498
--- /dev/null
+++ b/numpy/lib/tests/test__datasource.py
@@ -0,0 +1,317 @@
+import os
+from tempfile import mkdtemp, mkstemp, NamedTemporaryFile
+from shutil import rmtree
+from urlparse import urlparse
+from urllib2 import URLError
+import urllib2
+
+from numpy.testing import *
+
+import numpy.lib._datasource as datasource
+
+def urlopen_stub(url, data=None):
+ '''Stub to replace urlopen for testing.'''
+ if url == valid_httpurl():
+ tmpfile = NamedTemporaryFile(prefix='urltmp_')
+ return tmpfile
+ else:
+ raise URLError('Name or service not known')
+
+old_urlopen = None
+def setup():
+ global old_urlopen
+ old_urlopen = urllib2.urlopen
+ urllib2.urlopen = urlopen_stub
+
+def teardown():
+ urllib2.urlopen = old_urlopen
+
+# A valid website for more robust testing
+http_path = 'http://www.google.com/'
+http_file = 'index.html'
+
+http_fakepath = 'http://fake.abc.web/site/'
+http_fakefile = 'fake.txt'
+
+malicious_files = ['/etc/shadow', '../../shadow',
+ '..\\system.dat', 'c:\\windows\\system.dat']
+
+magic_line = 'three is the magic number'
+
+
+# Utility functions used by many TestCases
+def valid_textfile(filedir):
+ # Generate and return a valid temporary file.
+ fd, path = mkstemp(suffix='.txt', prefix='dstmp_', dir=filedir, text=True)
+ os.close(fd)
+ return path
+
+def invalid_textfile(filedir):
+ # Generate and return an invalid filename.
+ fd, path = mkstemp(suffix='.txt', prefix='dstmp_', dir=filedir)
+ os.close(fd)
+ os.remove(path)
+ return path
+
+def valid_httpurl():
+ return http_path+http_file
+
+def invalid_httpurl():
+ return http_fakepath+http_fakefile
+
+def valid_baseurl():
+ return http_path
+
+def invalid_baseurl():
+ return http_fakepath
+
+def valid_httpfile():
+ return http_file
+
+def invalid_httpfile():
+ return http_fakefile
+
+class TestDataSourceOpen(TestCase):
+ def setUp(self):
+ self.tmpdir = mkdtemp()
+ self.ds = datasource.DataSource(self.tmpdir)
+
+ def tearDown(self):
+ rmtree(self.tmpdir)
+ del self.ds
+
+ def test_ValidHTTP(self):
+ assert self.ds.open(valid_httpurl())
+
+ def test_InvalidHTTP(self):
+ url = invalid_httpurl()
+ self.assertRaises(IOError, self.ds.open, url)
+ try:
+ self.ds.open(url)
+ except IOError, e:
+ # Regression test for bug fixed in r4342.
+ assert e.errno is None
+
+ def test_InvalidHTTPCacheURLError(self):
+ self.assertRaises(URLError, self.ds._cache, invalid_httpurl())
+
+ def test_ValidFile(self):
+ local_file = valid_textfile(self.tmpdir)
+ assert self.ds.open(local_file)
+
+ def test_InvalidFile(self):
+ invalid_file = invalid_textfile(self.tmpdir)
+ self.assertRaises(IOError, self.ds.open, invalid_file)
+
+ def test_ValidGzipFile(self):
+ try:
+ import gzip
+ except ImportError:
+ # We don't have the gzip capabilities to test.
+ import nose
+ raise nose.SkipTest
+ # Test datasource's internal file_opener for Gzip files.
+ filepath = os.path.join(self.tmpdir, 'foobar.txt.gz')
+ fp = gzip.open(filepath, 'w')
+ fp.write(magic_line)
+ fp.close()
+ fp = self.ds.open(filepath)
+ result = fp.readline()
+ fp.close()
+ self.assertEqual(magic_line, result)
+
+ def test_ValidBz2File(self):
+ try:
+ import bz2
+ except ImportError:
+ # We don't have the bz2 capabilities to test.
+ import nose
+ raise nose.SkipTest
+ # Test datasource's internal file_opener for BZip2 files.
+ filepath = os.path.join(self.tmpdir, 'foobar.txt.bz2')
+ fp = bz2.BZ2File(filepath, 'w')
+ fp.write(magic_line)
+ fp.close()
+ fp = self.ds.open(filepath)
+ result = fp.readline()
+ fp.close()
+ self.assertEqual(magic_line, result)
+
+
+class TestDataSourceExists(TestCase):
+ def setUp(self):
+ self.tmpdir = mkdtemp()
+ self.ds = datasource.DataSource(self.tmpdir)
+
+ def tearDown(self):
+ rmtree(self.tmpdir)
+ del self.ds
+
+ def test_ValidHTTP(self):
+ assert self.ds.exists(valid_httpurl())
+
+ def test_InvalidHTTP(self):
+ self.assertEqual(self.ds.exists(invalid_httpurl()), False)
+
+ def test_ValidFile(self):
+ # Test valid file in destpath
+ tmpfile = valid_textfile(self.tmpdir)
+ assert self.ds.exists(tmpfile)
+ # Test valid local file not in destpath
+ localdir = mkdtemp()
+ tmpfile = valid_textfile(localdir)
+ assert self.ds.exists(tmpfile)
+ rmtree(localdir)
+
+ def test_InvalidFile(self):
+ tmpfile = invalid_textfile(self.tmpdir)
+ self.assertEqual(self.ds.exists(tmpfile), False)
+
+
+class TestDataSourceAbspath(TestCase):
+ def setUp(self):
+ self.tmpdir = os.path.abspath(mkdtemp())
+ self.ds = datasource.DataSource(self.tmpdir)
+
+ def tearDown(self):
+ rmtree(self.tmpdir)
+ del self.ds
+
+ def test_ValidHTTP(self):
+ scheme, netloc, upath, pms, qry, frg = urlparse(valid_httpurl())
+ local_path = os.path.join(self.tmpdir, netloc,
+ upath.strip(os.sep).strip('/'))
+ self.assertEqual(local_path, self.ds.abspath(valid_httpurl()))
+
+ def test_ValidFile(self):
+ tmpfile = valid_textfile(self.tmpdir)
+ tmpfilename = os.path.split(tmpfile)[-1]
+ # Test with filename only
+ self.assertEqual(tmpfile, self.ds.abspath(os.path.split(tmpfile)[-1]))
+ # Test filename with complete path
+ self.assertEqual(tmpfile, self.ds.abspath(tmpfile))
+
+ def test_InvalidHTTP(self):
+ scheme, netloc, upath, pms, qry, frg = urlparse(invalid_httpurl())
+ invalidhttp = os.path.join(self.tmpdir, netloc,
+ upath.strip(os.sep).strip('/'))
+ self.assertNotEqual(invalidhttp, self.ds.abspath(valid_httpurl()))
+
+ def test_InvalidFile(self):
+ invalidfile = valid_textfile(self.tmpdir)
+ tmpfile = valid_textfile(self.tmpdir)
+ tmpfilename = os.path.split(tmpfile)[-1]
+ # Test with filename only
+ self.assertNotEqual(invalidfile, self.ds.abspath(tmpfilename))
+ # Test filename with complete path
+ self.assertNotEqual(invalidfile, self.ds.abspath(tmpfile))
+
+ def test_sandboxing(self):
+ tmpfile = valid_textfile(self.tmpdir)
+ tmpfilename = os.path.split(tmpfile)[-1]
+
+ tmp_path = lambda x: os.path.abspath(self.ds.abspath(x))
+
+ assert tmp_path(valid_httpurl()).startswith(self.tmpdir)
+ assert tmp_path(invalid_httpurl()).startswith(self.tmpdir)
+ assert tmp_path(tmpfile).startswith(self.tmpdir)
+ assert tmp_path(tmpfilename).startswith(self.tmpdir)
+ for fn in malicious_files:
+ assert tmp_path(http_path+fn).startswith(self.tmpdir)
+ assert tmp_path(fn).startswith(self.tmpdir)
+
+ def test_windows_os_sep(self):
+ orig_os_sep = os.sep
+ try:
+ os.sep = '\\'
+ self.test_ValidHTTP()
+ self.test_ValidFile()
+ self.test_InvalidHTTP()
+ self.test_InvalidFile()
+ self.test_sandboxing()
+ finally:
+ os.sep = orig_os_sep
+
+
+class TestRepositoryAbspath(TestCase):
+ def setUp(self):
+ self.tmpdir = os.path.abspath(mkdtemp())
+ self.repos = datasource.Repository(valid_baseurl(), self.tmpdir)
+
+ def tearDown(self):
+ rmtree(self.tmpdir)
+ del self.repos
+
+ def test_ValidHTTP(self):
+ scheme, netloc, upath, pms, qry, frg = urlparse(valid_httpurl())
+ local_path = os.path.join(self.repos._destpath, netloc, \
+ upath.strip(os.sep).strip('/'))
+ filepath = self.repos.abspath(valid_httpfile())
+ self.assertEqual(local_path, filepath)
+
+ def test_sandboxing(self):
+ tmp_path = lambda x: os.path.abspath(self.repos.abspath(x))
+ assert tmp_path(valid_httpfile()).startswith(self.tmpdir)
+ for fn in malicious_files:
+ assert tmp_path(http_path+fn).startswith(self.tmpdir)
+ assert tmp_path(fn).startswith(self.tmpdir)
+
+ def test_windows_os_sep(self):
+ orig_os_sep = os.sep
+ try:
+ os.sep = '\\'
+ self.test_ValidHTTP()
+ self.test_sandboxing()
+ finally:
+ os.sep = orig_os_sep
+
+
+class TestRepositoryExists(TestCase):
+ def setUp(self):
+ self.tmpdir = mkdtemp()
+ self.repos = datasource.Repository(valid_baseurl(), self.tmpdir)
+
+ def tearDown(self):
+ rmtree(self.tmpdir)
+ del self.repos
+
+ def test_ValidFile(self):
+ # Create local temp file
+ tmpfile = valid_textfile(self.tmpdir)
+ assert self.repos.exists(tmpfile)
+
+ def test_InvalidFile(self):
+ tmpfile = invalid_textfile(self.tmpdir)
+ self.assertEqual(self.repos.exists(tmpfile), False)
+
+ def test_RemoveHTTPFile(self):
+ assert self.repos.exists(valid_httpurl())
+
+ def test_CachedHTTPFile(self):
+ localfile = valid_httpurl()
+ # Create a locally cached temp file with an URL based
+ # directory structure. This is similar to what Repository.open
+ # would do.
+ scheme, netloc, upath, pms, qry, frg = urlparse(localfile)
+ local_path = os.path.join(self.repos._destpath, netloc)
+ os.mkdir(local_path, 0700)
+ tmpfile = valid_textfile(local_path)
+ assert self.repos.exists(tmpfile)
+
+class TestOpenFunc(TestCase):
+ def setUp(self):
+ self.tmpdir = mkdtemp()
+
+ def tearDown(self):
+ rmtree(self.tmpdir)
+
+ def test_DataSourceOpen(self):
+ local_file = valid_textfile(self.tmpdir)
+ # Test case where destpath is passed in
+ assert datasource.open(local_file, destpath=self.tmpdir)
+ # Test case where default destpath is used
+ assert datasource.open(local_file)
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py
new file mode 100644
index 000000000..c40cf9d20
--- /dev/null
+++ b/numpy/lib/tests/test_arraysetops.py
@@ -0,0 +1,156 @@
+""" Test functions for 1D array set operations.
+
+"""
+
+from numpy.testing import *
+import numpy as np
+from numpy.lib.arraysetops import *
+
+import warnings
+
+class TestAso(TestCase):
+ def test_unique1d( self ):
+ a = np.array( [5, 7, 1, 2, 1, 5, 7] )
+
+ ec = np.array( [1, 2, 5, 7] )
+ c = unique1d( a )
+ assert_array_equal( c, ec )
+
+ warnings.simplefilter('ignore', Warning)
+ unique, indices = unique1d( a, return_index=True )
+ warnings.resetwarnings()
+
+ ed = np.array( [2, 3, 0, 1] )
+ assert_array_equal(unique, ec)
+ assert_array_equal(indices, ed)
+
+ assert_array_equal([], unique1d([]))
+
+ def test_intersect1d( self ):
+ a = np.array( [5, 7, 1, 2] )
+ b = np.array( [2, 4, 3, 1, 5] )
+
+ ec = np.array( [1, 2, 5] )
+ c = intersect1d( a, b )
+ assert_array_equal( c, ec )
+
+ assert_array_equal([], intersect1d([],[]))
+
+ def test_intersect1d_nu( self ):
+ a = np.array( [5, 5, 7, 1, 2] )
+ b = np.array( [2, 1, 4, 3, 3, 1, 5] )
+
+ ec = np.array( [1, 2, 5] )
+ c = intersect1d_nu( a, b )
+ assert_array_equal( c, ec )
+
+ assert_array_equal([], intersect1d_nu([],[]))
+
+ def test_setxor1d( self ):
+ a = np.array( [5, 7, 1, 2] )
+ b = np.array( [2, 4, 3, 1, 5] )
+
+ ec = np.array( [3, 4, 7] )
+ c = setxor1d( a, b )
+ assert_array_equal( c, ec )
+
+ a = np.array( [1, 2, 3] )
+ b = np.array( [6, 5, 4] )
+
+ ec = np.array( [1, 2, 3, 4, 5, 6] )
+ c = setxor1d( a, b )
+ assert_array_equal( c, ec )
+
+ a = np.array( [1, 8, 2, 3] )
+ b = np.array( [6, 5, 4, 8] )
+
+ ec = np.array( [1, 2, 3, 4, 5, 6] )
+ c = setxor1d( a, b )
+ assert_array_equal( c, ec )
+
+ assert_array_equal([], setxor1d([],[]))
+
+ def test_ediff1d(self):
+ zero_elem = np.array([])
+ one_elem = np.array([1])
+ two_elem = np.array([1,2])
+
+ assert_array_equal([],ediff1d(zero_elem))
+ assert_array_equal([0],ediff1d(zero_elem,to_begin=0))
+ assert_array_equal([0],ediff1d(zero_elem,to_end=0))
+ assert_array_equal([-1,0],ediff1d(zero_elem,to_begin=-1,to_end=0))
+ assert_array_equal([],ediff1d(one_elem))
+ assert_array_equal([1],ediff1d(two_elem))
+
+ def test_setmember1d( self ):
+ a = np.array( [5, 7, 1, 2] )
+ b = np.array( [2, 4, 3, 1, 5] )
+
+ ec = np.array( [True, False, True, True] )
+ c = setmember1d( a, b )
+ assert_array_equal( c, ec )
+
+ a[0] = 8
+ ec = np.array( [False, False, True, True] )
+ c = setmember1d( a, b )
+ assert_array_equal( c, ec )
+
+ a[0], a[3] = 4, 8
+ ec = np.array( [True, False, True, False] )
+ c = setmember1d( a, b )
+ assert_array_equal( c, ec )
+
+ assert_array_equal([], setmember1d([],[]))
+
+ def test_union1d( self ):
+ a = np.array( [5, 4, 7, 1, 2] )
+ b = np.array( [2, 4, 3, 3, 2, 1, 5] )
+
+ ec = np.array( [1, 2, 3, 4, 5, 7] )
+ c = union1d( a, b )
+ assert_array_equal( c, ec )
+
+ assert_array_equal([], union1d([],[]))
+
+ def test_setdiff1d( self ):
+ a = np.array( [6, 5, 4, 7, 1, 2] )
+ b = np.array( [2, 4, 3, 3, 2, 1, 5] )
+
+ ec = np.array( [6, 7] )
+ c = setdiff1d( a, b )
+ assert_array_equal( c, ec )
+
+ a = np.arange( 21 )
+ b = np.arange( 19 )
+ ec = np.array( [19, 20] )
+ c = setdiff1d( a, b )
+ assert_array_equal( c, ec )
+
+ assert_array_equal([], setdiff1d([],[]))
+
+ def test_setdiff1d_char_array(self):
+ a = np.array(['a','b','c'])
+ b = np.array(['a','b','s'])
+ assert_array_equal(setdiff1d(a,b),np.array(['c']))
+
+ def test_manyways( self ):
+ nItem = 100
+ a = np.fix( nItem / 10 * np.random.random( nItem ) )
+ b = np.fix( nItem / 10 * np.random.random( nItem ) )
+
+ c1 = intersect1d_nu( a, b )
+ c2 = unique1d( intersect1d( a, b ) )
+ assert_array_equal( c1, c2 )
+
+ a = np.array( [5, 7, 1, 2, 8] )
+ b = np.array( [9, 8, 2, 4, 3, 1, 5] )
+
+ c1 = setxor1d( a, b )
+ aux1 = intersect1d( a, b )
+ aux2 = union1d( a, b )
+ c2 = setdiff1d( aux2, aux1 )
+ assert_array_equal( c1, c2 )
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_arrayterator.py b/numpy/lib/tests/test_arrayterator.py
new file mode 100644
index 000000000..421569651
--- /dev/null
+++ b/numpy/lib/tests/test_arrayterator.py
@@ -0,0 +1,43 @@
+from operator import mul
+
+import numpy as np
+from numpy.random import randint
+from numpy.lib import Arrayterator
+
+def test():
+ np.random.seed(np.arange(10))
+
+ # Create a random array
+ ndims = randint(5)+1
+ shape = tuple(randint(10)+1 for dim in range(ndims))
+ els = reduce(mul, shape)
+ a = np.arange(els)
+ a.shape = shape
+
+ buf_size = randint(2*els)
+ b = Arrayterator(a, buf_size)
+
+ # Check that each block has at most ``buf_size`` elements
+ for block in b:
+ assert len(block.flat) <= (buf_size or els)
+
+ # Check that all elements are iterated correctly
+ assert list(b.flat) == list(a.flat)
+
+ # Slice arrayterator
+ start = [randint(dim) for dim in shape]
+ stop = [randint(dim)+1 for dim in shape]
+ step = [randint(dim)+1 for dim in shape]
+ slice_ = tuple(slice(*t) for t in zip(start, stop, step))
+ c = b[slice_]
+ d = a[slice_]
+
+ # Check that each block has at most ``buf_size`` elements
+ for block in c:
+ assert len(block.flat) <= (buf_size or els)
+
+ # Check that the arrayterator is sliced correctly
+ assert np.all(c.__array__() == d)
+
+ # Check that all elements are iterated correctly
+ assert list(c.flat) == list(d.flat)
diff --git a/numpy/lib/tests/test_financial.py b/numpy/lib/tests/test_financial.py
new file mode 100644
index 000000000..1ac14b561
--- /dev/null
+++ b/numpy/lib/tests/test_financial.py
@@ -0,0 +1,57 @@
+from numpy.testing import *
+import numpy as np
+
+class TestFinancial(TestCase):
+ def test_rate(self):
+ assert_almost_equal(np.rate(10,0,-3500,10000),
+ 0.1107, 4)
+
+ def test_irr(self):
+ v = [-150000, 15000, 25000, 35000, 45000, 60000]
+ assert_almost_equal(np.irr(v),
+ 0.0524, 2)
+
+ def test_pv(self):
+ assert_almost_equal(np.pv(0.07,20,12000,0),
+ -127128.17, 2)
+
+ def test_fv(self):
+ assert_almost_equal(np.fv(0.075, 20, -2000,0,0),
+ 86609.36, 2)
+
+ def test_pmt(self):
+ assert_almost_equal(np.pmt(0.08/12,5*12,15000),
+ -304.146, 3)
+
+ def test_nper(self):
+ assert_almost_equal(np.nper(0.075,-2000,0,100000.),
+ 21.54, 2)
+
+ def test_nper(self):
+ assert_almost_equal(np.nper(0.0,-2000,0,100000.),
+ 50.0, 1)
+
+ def test_npv(self):
+ assert_almost_equal(np.npv(0.05,[-15000,1500,2500,3500,4500,6000]),
+ 117.04, 2)
+
+ def test_mirr(self):
+ v1 = [-4500,-800,800,800,600,600,800,800,700,3000]
+ assert_almost_equal(np.mirr(v1,0.08,0.055),
+ 0.0665, 4)
+
+ v2 = [-120000,39000,30000,21000,37000,46000]
+ assert_almost_equal(np.mirr(v2,0.10,0.12),
+ 0.1344, 4)
+
+
+def test_unimplemented():
+ # np.round(np.ppmt(0.1/12,1,60,55000),2) == 710.25
+ assert_raises(NotImplementedError, np.ppmt, 0.1/12, 1, 60, 55000)
+
+ # np.round(np.ipmt(0.1/12,1,24,2000),2) == 16.67
+ assert_raises(NotImplementedError, np.ipmt, 0.1/12, 1, 24, 2000)
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py
new file mode 100644
index 000000000..35558400f
--- /dev/null
+++ b/numpy/lib/tests/test_format.py
@@ -0,0 +1,554 @@
+r''' Test the .npy file format.
+
+Set up:
+
+ >>> from cStringIO import StringIO
+ >>> from numpy.lib import format
+ >>>
+ >>> scalars = [
+ ... np.uint8,
+ ... np.int8,
+ ... np.uint16,
+ ... np.int16,
+ ... np.uint32,
+ ... np.int32,
+ ... np.uint64,
+ ... np.int64,
+ ... np.float32,
+ ... np.float64,
+ ... np.complex64,
+ ... np.complex128,
+ ... object,
+ ... ]
+ >>>
+ >>> basic_arrays = []
+ >>>
+ >>> for scalar in scalars:
+ ... for endian in '<>':
+ ... dtype = np.dtype(scalar).newbyteorder(endian)
+ ... basic = np.arange(15).astype(dtype)
+ ... basic_arrays.extend([
+ ... np.array([], dtype=dtype),
+ ... np.array(10, dtype=dtype),
+ ... basic,
+ ... basic.reshape((3,5)),
+ ... basic.reshape((3,5)).T,
+ ... basic.reshape((3,5))[::-1,::2],
+ ... ])
+ ...
+ >>>
+ >>> Pdescr = [
+ ... ('x', 'i4', (2,)),
+ ... ('y', 'f8', (2, 2)),
+ ... ('z', 'u1')]
+ >>>
+ >>>
+ >>> PbufferT = [
+ ... ([3,2], [[6.,4.],[6.,4.]], 8),
+ ... ([4,3], [[7.,5.],[7.,5.]], 9),
+ ... ]
+ >>>
+ >>>
+ >>> Ndescr = [
+ ... ('x', 'i4', (2,)),
+ ... ('Info', [
+ ... ('value', 'c16'),
+ ... ('y2', 'f8'),
+ ... ('Info2', [
+ ... ('name', 'S2'),
+ ... ('value', 'c16', (2,)),
+ ... ('y3', 'f8', (2,)),
+ ... ('z3', 'u4', (2,))]),
+ ... ('name', 'S2'),
+ ... ('z2', 'b1')]),
+ ... ('color', 'S2'),
+ ... ('info', [
+ ... ('Name', 'U8'),
+ ... ('Value', 'c16')]),
+ ... ('y', 'f8', (2, 2)),
+ ... ('z', 'u1')]
+ >>>
+ >>>
+ >>> NbufferT = [
+ ... ([3,2], (6j, 6., ('nn', [6j,4j], [6.,4.], [1,2]), 'NN', True), 'cc', ('NN', 6j), [[6.,4.],[6.,4.]], 8),
+ ... ([4,3], (7j, 7., ('oo', [7j,5j], [7.,5.], [2,1]), 'OO', False), 'dd', ('OO', 7j), [[7.,5.],[7.,5.]], 9),
+ ... ]
+ >>>
+ >>>
+ >>> record_arrays = [
+ ... np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('<')),
+ ... np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('<')),
+ ... np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('>')),
+ ... np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('>')),
+ ... ]
+
+Test the magic string writing.
+
+ >>> format.magic(1, 0)
+ '\x93NUMPY\x01\x00'
+ >>> format.magic(0, 0)
+ '\x93NUMPY\x00\x00'
+ >>> format.magic(255, 255)
+ '\x93NUMPY\xff\xff'
+ >>> format.magic(2, 5)
+ '\x93NUMPY\x02\x05'
+
+Test the magic string reading.
+
+ >>> format.read_magic(StringIO(format.magic(1, 0)))
+ (1, 0)
+ >>> format.read_magic(StringIO(format.magic(0, 0)))
+ (0, 0)
+ >>> format.read_magic(StringIO(format.magic(255, 255)))
+ (255, 255)
+ >>> format.read_magic(StringIO(format.magic(2, 5)))
+ (2, 5)
+
+Test the header writing.
+
+ >>> for arr in basic_arrays + record_arrays:
+ ... f = StringIO()
+ ... format.write_array_header_1_0(f, arr)
+ ... print repr(f.getvalue())
+ ...
+ "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '|u1', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '|u1', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '<u2', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '<u2', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '<u2', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '<u2', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '<u2', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '<u2', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '>u2', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '>u2', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '>u2', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '>u2', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '>u2', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '>u2', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '<i2', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '<i2', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '<i2', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '<i2', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '<i2', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '<i2', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '>i2', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '>i2', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '>i2', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '>i2', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '>i2', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '>i2', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '<u4', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '<u4', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '<u4', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '<u4', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '<u4', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '<u4', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '>u4', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '>u4', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '<i4', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '<i4', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '<i4', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '<i4', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '<i4', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '<i4', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '>i4', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '>i4', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '>i4', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '>i4', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '>i4', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '>i4', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '<u8', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '<u8', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '<u8', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '<u8', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '<u8', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '<u8', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '>u8', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '>u8', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '>u8', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '>u8', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '>u8', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '>u8', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '<i8', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '<i8', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '<i8', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '<i8', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '<i8', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '<i8', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '>i8', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '>i8', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '>i8', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '>i8', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '>i8', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '>i8', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '<f4', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '<f4', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '<f4', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '<f4', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '<f4', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '<f4', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '>f4', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '>f4', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '>f4', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '>f4', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '>f4', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '>f4', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '<f8', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '<f8', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '<f8', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '<f8', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '<f8', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '<f8', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '>f8', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '>f8', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '>f8', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '>f8', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '>f8', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '>f8', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '<c8', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '<c8', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '<c8', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '<c8', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '<c8', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '<c8', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '>c8', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '>c8', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '>c8', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '>c8', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '>c8', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '>c8', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '<c16', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '<c16', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '<c16', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '<c16', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '<c16', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '<c16', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '>c16', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '>c16', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '>c16', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '>c16', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '>c16', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '>c16', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': False, 'shape': (0,)} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': False, 'shape': ()} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': False, 'shape': (15,)} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': False, 'shape': (3, 5)} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': True, 'shape': (5, 3)} \n"
+ "F\x00{'descr': '|O4', 'fortran_order': False, 'shape': (3, 3)} \n"
+ "v\x00{'descr': [('x', '<i4', (2,)), ('y', '<f8', (2, 2)), ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n"
+ "\x16\x02{'descr': [('x', '<i4', (2,)),\n ('Info',\n [('value', '<c16'),\n ('y2', '<f8'),\n ('Info2',\n [('name', '|S2'),\n ('value', '<c16', (2,)),\n ('y3', '<f8', (2,)),\n ('z3', '<u4', (2,))]),\n ('name', '|S2'),\n ('z2', '|b1')]),\n ('color', '|S2'),\n ('info', [('Name', '<U8'), ('Value', '<c16')]),\n ('y', '<f8', (2, 2)),\n ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n"
+ "v\x00{'descr': [('x', '>i4', (2,)), ('y', '>f8', (2, 2)), ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n"
+ "\x16\x02{'descr': [('x', '>i4', (2,)),\n ('Info',\n [('value', '>c16'),\n ('y2', '>f8'),\n ('Info2',\n [('name', '|S2'),\n ('value', '>c16', (2,)),\n ('y3', '>f8', (2,)),\n ('z3', '>u4', (2,))]),\n ('name', '|S2'),\n ('z2', '|b1')]),\n ('color', '|S2'),\n ('info', [('Name', '>U8'), ('Value', '>c16')]),\n ('y', '>f8', (2, 2)),\n ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n"
+'''
+
+
+import sys
+from cStringIO import StringIO
+import os
+import shutil
+import tempfile
+
+import numpy as np
+from numpy.testing import *
+
+from numpy.lib import format
+
+
+tempdir = None
+
+# Module-level setup.
+def setup_module():
+ global tempdir
+ tempdir = tempfile.mkdtemp()
+
+def teardown_module():
+ global tempdir
+ if tempdir is not None and os.path.isdir(tempdir):
+ shutil.rmtree(tempdir)
+ tempdir = None
+
+
+# Generate some basic arrays to test with.
+scalars = [
+ np.uint8,
+ np.int8,
+ np.uint16,
+ np.int16,
+ np.uint32,
+ np.int32,
+ np.uint64,
+ np.int64,
+ np.float32,
+ np.float64,
+ np.complex64,
+ np.complex128,
+ object,
+]
+basic_arrays = []
+for scalar in scalars:
+ for endian in '<>':
+ dtype = np.dtype(scalar).newbyteorder(endian)
+ basic = np.arange(15).astype(dtype)
+ basic_arrays.extend([
+ # Empty
+ np.array([], dtype=dtype),
+ # Rank-0
+ np.array(10, dtype=dtype),
+ # 1-D
+ basic,
+ # 2-D C-contiguous
+ basic.reshape((3,5)),
+ # 2-D F-contiguous
+ basic.reshape((3,5)).T,
+ # 2-D non-contiguous
+ basic.reshape((3,5))[::-1,::2],
+ ])
+
+# More complicated record arrays.
+# This is the structure of the table used for plain objects:
+#
+# +-+-+-+
+# |x|y|z|
+# +-+-+-+
+
+# Structure of a plain array description:
+Pdescr = [
+ ('x', 'i4', (2,)),
+ ('y', 'f8', (2, 2)),
+ ('z', 'u1')]
+
+# A plain list of tuples with values for testing:
+PbufferT = [
+ # x y z
+ ([3,2], [[6.,4.],[6.,4.]], 8),
+ ([4,3], [[7.,5.],[7.,5.]], 9),
+ ]
+
+
+# This is the structure of the table used for nested objects (DON'T PANIC!):
+#
+# +-+---------------------------------+-----+----------+-+-+
+# |x|Info |color|info |y|z|
+# | +-----+--+----------------+----+--+ +----+-----+ | |
+# | |value|y2|Info2 |name|z2| |Name|Value| | |
+# | | | +----+-----+--+--+ | | | | | | |
+# | | | |name|value|y3|z3| | | | | | | |
+# +-+-----+--+----+-----+--+--+----+--+-----+----+-----+-+-+
+#
+
+# The corresponding nested array description:
+Ndescr = [
+ ('x', 'i4', (2,)),
+ ('Info', [
+ ('value', 'c16'),
+ ('y2', 'f8'),
+ ('Info2', [
+ ('name', 'S2'),
+ ('value', 'c16', (2,)),
+ ('y3', 'f8', (2,)),
+ ('z3', 'u4', (2,))]),
+ ('name', 'S2'),
+ ('z2', 'b1')]),
+ ('color', 'S2'),
+ ('info', [
+ ('Name', 'U8'),
+ ('Value', 'c16')]),
+ ('y', 'f8', (2, 2)),
+ ('z', 'u1')]
+
+NbufferT = [
+ # x Info color info y z
+ # value y2 Info2 name z2 Name Value
+ # name value y3 z3
+ ([3,2], (6j, 6., ('nn', [6j,4j], [6.,4.], [1,2]), 'NN', True), 'cc', ('NN', 6j), [[6.,4.],[6.,4.]], 8),
+ ([4,3], (7j, 7., ('oo', [7j,5j], [7.,5.], [2,1]), 'OO', False), 'dd', ('OO', 7j), [[7.,5.],[7.,5.]], 9),
+ ]
+
+record_arrays = [
+ np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('<')),
+ np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('<')),
+ np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('>')),
+ np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('>')),
+]
+
+def roundtrip(arr):
+ f = StringIO()
+ format.write_array(f, arr)
+ f2 = StringIO(f.getvalue())
+ arr2 = format.read_array(f2)
+ return arr2
+
+def assert_equal(o1, o2):
+ assert o1 == o2
+
+
+def test_roundtrip():
+ for arr in basic_arrays + record_arrays:
+ arr2 = roundtrip(arr)
+ yield assert_array_equal, arr, arr2
+
+def test_memmap_roundtrip():
+ # XXX: test crashes nose on windows. Fix this
+ if not (sys.platform == 'win32' or sys.platform == 'cygwin'):
+ for arr in basic_arrays + record_arrays:
+ if arr.dtype.hasobject:
+ # Skip these since they can't be mmap'ed.
+ continue
+ # Write it out normally and through mmap.
+ nfn = os.path.join(tempdir, 'normal.npy')
+ mfn = os.path.join(tempdir, 'memmap.npy')
+ fp = open(nfn, 'wb')
+ try:
+ format.write_array(fp, arr)
+ finally:
+ fp.close()
+
+ fortran_order = (arr.flags.f_contiguous and not arr.flags.c_contiguous)
+ ma = format.open_memmap(mfn, mode='w+', dtype=arr.dtype,
+ shape=arr.shape, fortran_order=fortran_order)
+ ma[...] = arr
+ del ma
+
+ # Check that both of these files' contents are the same.
+ fp = open(nfn, 'rb')
+ normal_bytes = fp.read()
+ fp.close()
+ fp = open(mfn, 'rb')
+ memmap_bytes = fp.read()
+ fp.close()
+ yield assert_equal, normal_bytes, memmap_bytes
+
+ # Check that reading the file using memmap works.
+ ma = format.open_memmap(nfn, mode='r')
+ #yield assert_array_equal, ma, arr
+ #del ma
+
+
+def test_write_version_1_0():
+ f = StringIO()
+ arr = np.arange(1)
+ # These should pass.
+ format.write_array(f, arr, version=(1, 0))
+ format.write_array(f, arr)
+
+ # These should all fail.
+ bad_versions = [
+ (1, 1),
+ (0, 0),
+ (0, 1),
+ (2, 0),
+ (2, 2),
+ (255, 255),
+ ]
+ for version in bad_versions:
+ try:
+ format.write_array(f, arr, version=version)
+ except ValueError:
+ pass
+ else:
+ raise AssertionError("we should have raised a ValueError for the bad version %r" % (version,))
+
+
+bad_version_magic = [
+ '\x93NUMPY\x01\x01',
+ '\x93NUMPY\x00\x00',
+ '\x93NUMPY\x00\x01',
+ '\x93NUMPY\x02\x00',
+ '\x93NUMPY\x02\x02',
+ '\x93NUMPY\xff\xff',
+]
+malformed_magic = [
+ '\x92NUMPY\x01\x00',
+ '\x00NUMPY\x01\x00',
+ '\x93numpy\x01\x00',
+ '\x93MATLB\x01\x00',
+ '\x93NUMPY\x01',
+ '\x93NUMPY',
+ '',
+]
+
+def test_read_magic_bad_magic():
+ for magic in malformed_magic:
+ f = StringIO(magic)
+ yield raises(ValueError)(format.read_magic), f
+
+def test_read_version_1_0_bad_magic():
+ for magic in bad_version_magic + malformed_magic:
+ f = StringIO(magic)
+ yield raises(ValueError)(format.read_array), f
+
+def test_bad_magic_args():
+ assert_raises(ValueError, format.magic, -1, 1)
+ assert_raises(ValueError, format.magic, 256, 1)
+ assert_raises(ValueError, format.magic, 1, -1)
+ assert_raises(ValueError, format.magic, 1, 256)
+
+def test_large_header():
+ s = StringIO()
+ d = {'a':1,'b':2}
+ format.write_array_header_1_0(s,d)
+
+ s = StringIO()
+ d = {'a':1,'b':2,'c':'x'*256*256}
+ assert_raises(ValueError, format.write_array_header_1_0, s, d)
+
+def test_bad_header():
+ # header of length less than 2 should fail
+ s = StringIO()
+ assert_raises(ValueError, format.read_array_header_1_0, s)
+ s = StringIO('1')
+ assert_raises(ValueError, format.read_array_header_1_0, s)
+
+ # header shorter than indicated size should fail
+ s = StringIO('\x01\x00')
+ assert_raises(ValueError, format.read_array_header_1_0, s)
+
+ # headers without the exact keys required should fail
+ d = {"shape":(1,2),
+ "descr":"x"}
+ s = StringIO()
+ format.write_array_header_1_0(s,d)
+ assert_raises(ValueError, format.read_array_header_1_0, s)
+
+ d = {"shape":(1,2),
+ "fortran_order":False,
+ "descr":"x",
+ "extrakey":-1}
+ s = StringIO()
+ format.write_array_header_1_0(s,d)
+ assert_raises(ValueError, format.read_array_header_1_0, s)
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
new file mode 100644
index 000000000..ca8104b53
--- /dev/null
+++ b/numpy/lib/tests/test_function_base.py
@@ -0,0 +1,850 @@
+import warnings
+
+from numpy.testing import *
+import numpy.lib
+from numpy.lib import *
+from numpy.core import *
+
+class TestAny(TestCase):
+ def test_basic(self):
+ y1 = [0,0,1,0]
+ y2 = [0,0,0,0]
+ y3 = [1,0,1,0]
+ assert(any(y1))
+ assert(any(y3))
+ assert(not any(y2))
+
+ def test_nd(self):
+ y1 = [[0,0,0],[0,1,0],[1,1,0]]
+ assert(any(y1))
+ assert_array_equal(sometrue(y1,axis=0),[1,1,0])
+ assert_array_equal(sometrue(y1,axis=1),[0,1,1])
+
+class TestAll(TestCase):
+ def test_basic(self):
+ y1 = [0,1,1,0]
+ y2 = [0,0,0,0]
+ y3 = [1,1,1,1]
+ assert(not all(y1))
+ assert(all(y3))
+ assert(not all(y2))
+ assert(all(~array(y2)))
+
+ def test_nd(self):
+ y1 = [[0,0,1],[0,1,1],[1,1,1]]
+ assert(not all(y1))
+ assert_array_equal(alltrue(y1,axis=0),[0,0,1])
+ assert_array_equal(alltrue(y1,axis=1),[0,0,1])
+
+class TestAverage(TestCase):
+ def test_basic(self):
+ y1 = array([1,2,3])
+ assert(average(y1,axis=0) == 2.)
+ y2 = array([1.,2.,3.])
+ assert(average(y2,axis=0) == 2.)
+ y3 = [0.,0.,0.]
+ assert(average(y3,axis=0) == 0.)
+
+ y4 = ones((4,4))
+ y4[0,1] = 0
+ y4[1,0] = 2
+ assert_almost_equal(y4.mean(0), average(y4, 0))
+ assert_almost_equal(y4.mean(1), average(y4, 1))
+
+ y5 = rand(5,5)
+ assert_almost_equal(y5.mean(0), average(y5, 0))
+ assert_almost_equal(y5.mean(1), average(y5, 1))
+
+ y6 = matrix(rand(5,5))
+ assert_array_equal(y6.mean(0), average(y6,0))
+
+ def test_weights(self):
+ y = arange(10)
+ w = arange(10)
+ assert_almost_equal(average(y, weights=w), (arange(10)**2).sum()*1./arange(10).sum())
+
+ y1 = array([[1,2,3],[4,5,6]])
+ w0 = [1,2]
+ actual = average(y1,weights=w0,axis=0)
+ desired = array([3.,4.,5.])
+ assert_almost_equal(actual, desired)
+
+
+ w1 = [0,0,1]
+ desired = array([3., 6.])
+ assert_almost_equal(average(y1, weights=w1, axis=1), desired)
+
+ # This should raise an error. Can we test for that ?
+ # assert_equal(average(y1, weights=w1), 9./2.)
+
+
+ # 2D Case
+ w2 = [[0,0,1],[0,0,2]]
+ desired = array([3., 6.])
+ assert_array_equal(average(y1, weights=w2, axis=1), desired)
+
+ assert_equal(average(y1, weights=w2), 5.)
+
+
+ def test_returned(self):
+ y = array([[1,2,3],[4,5,6]])
+
+ # No weights
+ avg, scl = average(y, returned=True)
+ assert_equal(scl, 6.)
+
+ avg, scl = average(y, 0, returned=True)
+ assert_array_equal(scl, array([2.,2.,2.]))
+
+ avg, scl = average(y, 1, returned=True)
+ assert_array_equal(scl, array([3.,3.]))
+
+ # With weights
+ w0 = [1,2]
+ avg, scl = average(y, weights=w0, axis=0, returned=True)
+ assert_array_equal(scl, array([3., 3., 3.]))
+
+ w1 = [1,2,3]
+ avg, scl = average(y, weights=w1, axis=1, returned=True)
+ assert_array_equal(scl, array([6., 6.]))
+
+ w2 = [[0,0,1],[1,2,3]]
+ avg, scl = average(y, weights=w2, axis=1, returned=True)
+ assert_array_equal(scl, array([1.,6.]))
+
+
+class TestSelect(TestCase):
+ def _select(self,cond,values,default=0):
+ output = []
+ for m in range(len(cond)):
+ output += [V[m] for V,C in zip(values,cond) if C[m]] or [default]
+ return output
+
+ def test_basic(self):
+ choices = [array([1,2,3]),
+ array([4,5,6]),
+ array([7,8,9])]
+ conditions = [array([0,0,0]),
+ array([0,1,0]),
+ array([0,0,1])]
+ assert_array_equal(select(conditions,choices,default=15),
+ self._select(conditions,choices,default=15))
+
+ assert_equal(len(choices),3)
+ assert_equal(len(conditions),3)
+
+class TestLogspace(TestCase):
+ def test_basic(self):
+ y = logspace(0,6)
+ assert(len(y)==50)
+ y = logspace(0,6,num=100)
+ assert(y[-1] == 10**6)
+ y = logspace(0,6,endpoint=0)
+ assert(y[-1] < 10**6)
+ y = logspace(0,6,num=7)
+ assert_array_equal(y,[1,10,100,1e3,1e4,1e5,1e6])
+
+class TestLinspace(TestCase):
+ def test_basic(self):
+ y = linspace(0,10)
+ assert(len(y)==50)
+ y = linspace(2,10,num=100)
+ assert(y[-1] == 10)
+ y = linspace(2,10,endpoint=0)
+ assert(y[-1] < 10)
+ y,st = linspace(2,10,retstep=1)
+ assert_almost_equal(st,8/49.0)
+ assert_array_almost_equal(y,mgrid[2:10:50j],13)
+
+ def test_corner(self):
+ y = list(linspace(0,1,1))
+ assert y == [0.0], y
+ y = list(linspace(0,1,2.5))
+ assert y == [0.0, 1.0]
+
+ def test_type(self):
+ t1 = linspace(0,1,0).dtype
+ t2 = linspace(0,1,1).dtype
+ t3 = linspace(0,1,2).dtype
+ assert_equal(t1, t2)
+ assert_equal(t2, t3)
+
+class TestInsert(TestCase):
+ def test_basic(self):
+ a = [1,2,3]
+ assert_equal(insert(a,0,1), [1,1,2,3])
+ assert_equal(insert(a,3,1), [1,2,3,1])
+ assert_equal(insert(a,[1,1,1],[1,2,3]), [1,1,2,3,2,3])
+
+class TestAmax(TestCase):
+ def test_basic(self):
+ a = [3,4,5,10,-3,-5,6.0]
+ assert_equal(amax(a),10.0)
+ b = [[3,6.0, 9.0],
+ [4,10.0,5.0],
+ [8,3.0,2.0]]
+ assert_equal(amax(b,axis=0),[8.0,10.0,9.0])
+ assert_equal(amax(b,axis=1),[9.0,10.0,8.0])
+
+class TestAmin(TestCase):
+ def test_basic(self):
+ a = [3,4,5,10,-3,-5,6.0]
+ assert_equal(amin(a),-5.0)
+ b = [[3,6.0, 9.0],
+ [4,10.0,5.0],
+ [8,3.0,2.0]]
+ assert_equal(amin(b,axis=0),[3.0,3.0,2.0])
+ assert_equal(amin(b,axis=1),[3.0,4.0,2.0])
+
+class TestPtp(TestCase):
+ def test_basic(self):
+ a = [3,4,5,10,-3,-5,6.0]
+ assert_equal(ptp(a,axis=0),15.0)
+ b = [[3,6.0, 9.0],
+ [4,10.0,5.0],
+ [8,3.0,2.0]]
+ assert_equal(ptp(b,axis=0),[5.0,7.0,7.0])
+ assert_equal(ptp(b,axis=-1),[6.0,6.0,6.0])
+
+class TestCumsum(TestCase):
+ def test_basic(self):
+ ba = [1,2,10,11,6,5,4]
+ ba2 = [[1,2,3,4],[5,6,7,9],[10,3,4,5]]
+ for ctype in [int8,uint8,int16,uint16,int32,uint32,
+ float32,float64,complex64,complex128]:
+ a = array(ba,ctype)
+ a2 = array(ba2,ctype)
+ assert_array_equal(cumsum(a,axis=0), array([1,3,13,24,30,35,39],ctype))
+ assert_array_equal(cumsum(a2,axis=0), array([[1,2,3,4],[6,8,10,13],
+ [16,11,14,18]],ctype))
+ assert_array_equal(cumsum(a2,axis=1),
+ array([[1,3,6,10],
+ [5,11,18,27],
+ [10,13,17,22]],ctype))
+
+class TestProd(TestCase):
+ def test_basic(self):
+ ba = [1,2,10,11,6,5,4]
+ ba2 = [[1,2,3,4],[5,6,7,9],[10,3,4,5]]
+ for ctype in [int16,uint16,int32,uint32,
+ float32,float64,complex64,complex128]:
+ a = array(ba,ctype)
+ a2 = array(ba2,ctype)
+ if ctype in ['1', 'b']:
+ self.failUnlessRaises(ArithmeticError, prod, a)
+ self.failUnlessRaises(ArithmeticError, prod, a2, 1)
+ self.failUnlessRaises(ArithmeticError, prod, a)
+ else:
+ assert_equal(prod(a,axis=0),26400)
+ assert_array_equal(prod(a2,axis=0),
+ array([50,36,84,180],ctype))
+ assert_array_equal(prod(a2,axis=-1),array([24, 1890, 600],ctype))
+
+class TestCumprod(TestCase):
+ def test_basic(self):
+ ba = [1,2,10,11,6,5,4]
+ ba2 = [[1,2,3,4],[5,6,7,9],[10,3,4,5]]
+ for ctype in [int16,uint16,int32,uint32,
+ float32,float64,complex64,complex128]:
+ a = array(ba,ctype)
+ a2 = array(ba2,ctype)
+ if ctype in ['1', 'b']:
+ self.failUnlessRaises(ArithmeticError, cumprod, a)
+ self.failUnlessRaises(ArithmeticError, cumprod, a2, 1)
+ self.failUnlessRaises(ArithmeticError, cumprod, a)
+ else:
+ assert_array_equal(cumprod(a,axis=-1),
+ array([1, 2, 20, 220,
+ 1320, 6600, 26400],ctype))
+ assert_array_equal(cumprod(a2,axis=0),
+ array([[ 1, 2, 3, 4],
+ [ 5, 12, 21, 36],
+ [50, 36, 84, 180]],ctype))
+ assert_array_equal(cumprod(a2,axis=-1),
+ array([[ 1, 2, 6, 24],
+ [ 5, 30, 210, 1890],
+ [10, 30, 120, 600]],ctype))
+
+class TestDiff(TestCase):
+ def test_basic(self):
+ x = [1,4,6,7,12]
+ out = array([3,2,1,5])
+ out2 = array([-1,-1,4])
+ out3 = array([0,5])
+ assert_array_equal(diff(x),out)
+ assert_array_equal(diff(x,n=2),out2)
+ assert_array_equal(diff(x,n=3),out3)
+
+ def test_nd(self):
+ x = 20*rand(10,20,30)
+ out1 = x[:,:,1:] - x[:,:,:-1]
+ out2 = out1[:,:,1:] - out1[:,:,:-1]
+ out3 = x[1:,:,:] - x[:-1,:,:]
+ out4 = out3[1:,:,:] - out3[:-1,:,:]
+ assert_array_equal(diff(x),out1)
+ assert_array_equal(diff(x,n=2),out2)
+ assert_array_equal(diff(x,axis=0),out3)
+ assert_array_equal(diff(x,n=2,axis=0),out4)
+
+class TestGradient(TestCase):
+ def test_basic(self):
+ x = array([[1,1],[3,4]])
+ dx = [array([[2.,3.],[2.,3.]]),
+ array([[0.,0.],[1.,1.]])]
+ assert_array_equal(gradient(x), dx)
+
+ def test_badargs(self):
+ # for 2D array, gradient can take 0,1, or 2 extra args
+ x = array([[1,1],[3,4]])
+ assert_raises(SyntaxError, gradient, x, array([1.,1.]),
+ array([1.,1.]), array([1.,1.]))
+
+class TestAngle(TestCase):
+ def test_basic(self):
+ x = [1+3j,sqrt(2)/2.0+1j*sqrt(2)/2,1,1j,-1,-1j,1-3j,-1+3j]
+ y = angle(x)
+ yo = [arctan(3.0/1.0),arctan(1.0),0,pi/2,pi,-pi/2.0,
+ -arctan(3.0/1.0),pi-arctan(3.0/1.0)]
+ z = angle(x,deg=1)
+ zo = array(yo)*180/pi
+ assert_array_almost_equal(y,yo,11)
+ assert_array_almost_equal(z,zo,11)
+
+class TestTrimZeros(TestCase):
+ """ only testing for integer splits.
+ """
+ def test_basic(self):
+ a= array([0,0,1,2,3,4,0])
+ res = trim_zeros(a)
+ assert_array_equal(res,array([1,2,3,4]))
+ def test_leading_skip(self):
+ a= array([0,0,1,0,2,3,4,0])
+ res = trim_zeros(a)
+ assert_array_equal(res,array([1,0,2,3,4]))
+ def test_trailing_skip(self):
+ a= array([0,0,1,0,2,3,0,4,0])
+ res = trim_zeros(a)
+ assert_array_equal(res,array([1,0,2,3,0,4]))
+
+
+class TestExtins(TestCase):
+ def test_basic(self):
+ a = array([1,3,2,1,2,3,3])
+ b = extract(a>1,a)
+ assert_array_equal(b,[3,2,2,3,3])
+ def test_place(self):
+ a = array([1,4,3,2,5,8,7])
+ place(a,[0,1,0,1,0,1,0],[2,4,6])
+ assert_array_equal(a,[1,2,3,4,5,6,7])
+ def test_both(self):
+ a = rand(10)
+ mask = a > 0.5
+ ac = a.copy()
+ c = extract(mask, a)
+ place(a,mask,0)
+ place(a,mask,c)
+ assert_array_equal(a,ac)
+
+class TestVectorize(TestCase):
+ def test_simple(self):
+ def addsubtract(a,b):
+ if a > b:
+ return a - b
+ else:
+ return a + b
+ f = vectorize(addsubtract)
+ r = f([0,3,6,9],[1,3,5,7])
+ assert_array_equal(r,[1,6,1,2])
+ def test_scalar(self):
+ def addsubtract(a,b):
+ if a > b:
+ return a - b
+ else:
+ return a + b
+ f = vectorize(addsubtract)
+ r = f([0,3,6,9],5)
+ assert_array_equal(r,[5,8,1,4])
+ def test_large(self):
+ x = linspace(-3,2,10000)
+ f = vectorize(lambda x: x)
+ y = f(x)
+ assert_array_equal(y, x)
+
+class TestDigitize(TestCase):
+ def test_forward(self):
+ x = arange(-6,5)
+ bins = arange(-5,5)
+ assert_array_equal(digitize(x,bins),arange(11))
+
+ def test_reverse(self):
+ x = arange(5,-6,-1)
+ bins = arange(5,-5,-1)
+ assert_array_equal(digitize(x,bins),arange(11))
+
+ def test_random(self):
+ x = rand(10)
+ bin = linspace(x.min(), x.max(), 10)
+ assert all(digitize(x,bin) != 0)
+
+class TestUnwrap(TestCase):
+ def test_simple(self):
+ #check that unwrap removes jumps greather that 2*pi
+ assert_array_equal(unwrap([1,1+2*pi]),[1,1])
+ #check that unwrap maintans continuity
+ assert(all(diff(unwrap(rand(10)*100))<pi))
+
+
+class TestFilterwindows(TestCase):
+ def test_hanning(self):
+ #check symmetry
+ w=hanning(10)
+ assert_array_almost_equal(w,flipud(w),7)
+ #check known value
+ assert_almost_equal(sum(w,axis=0),4.500,4)
+
+ def test_hamming(self):
+ #check symmetry
+ w=hamming(10)
+ assert_array_almost_equal(w,flipud(w),7)
+ #check known value
+ assert_almost_equal(sum(w,axis=0),4.9400,4)
+
+ def test_bartlett(self):
+ #check symmetry
+ w=bartlett(10)
+ assert_array_almost_equal(w,flipud(w),7)
+ #check known value
+ assert_almost_equal(sum(w,axis=0),4.4444,4)
+
+ def test_blackman(self):
+ #check symmetry
+ w=blackman(10)
+ assert_array_almost_equal(w,flipud(w),7)
+ #check known value
+ assert_almost_equal(sum(w,axis=0),3.7800,4)
+
+
+class TestTrapz(TestCase):
+ def test_simple(self):
+ r=trapz(exp(-1.0/2*(arange(-10,10,.1))**2)/sqrt(2*pi),dx=0.1)
+ #check integral of normal equals 1
+ assert_almost_equal(sum(r,axis=0),1,7)
+
+class TestSinc(TestCase):
+ def test_simple(self):
+ assert(sinc(0)==1)
+ w=sinc(linspace(-1,1,100))
+ #check symmetry
+ assert_array_almost_equal(w,flipud(w),7)
+
+class TestHistogram(TestCase):
+ def setUp(self):
+ warnings.simplefilter('ignore', DeprecationWarning)
+
+ def tearDown(self):
+ warnings.resetwarnings()
+
+ def test_simple_old(self):
+ n=100
+ v=rand(n)
+ (a,b)=histogram(v, new=False)
+ #check if the sum of the bins equals the number of samples
+ assert_equal(sum(a,axis=0), n)
+ #check that the bin counts are evenly spaced when the data is from a
+ # linear function
+ (a,b)=histogram(linspace(0,10,100), new=False)
+ assert_array_equal(a, 10)
+
+ def test_simple(self):
+ n=100
+ v=rand(n)
+ (a,b)=histogram(v)
+ #check if the sum of the bins equals the number of samples
+ assert_equal(sum(a,axis=0), n)
+ #check that the bin counts are evenly spaced when the data is from a
+ # linear function
+ (a,b)=histogram(linspace(0,10,100))
+ assert_array_equal(a, 10)
+
+ def test_one_bin(self):
+ # Ticket 632
+ hist,edges = histogram([1,2,3,4],[1,2])
+ assert_array_equal(hist,[2, ])
+ assert_array_equal(edges,[1,2])
+
+ def test_normed(self):
+ # Check that the integral of the density equals 1.
+ n = 100
+ v = rand(n)
+ a,b = histogram(v, normed=True)
+ area = sum(a*diff(b))
+ assert_almost_equal(area, 1)
+
+ # Check with non constant bin width
+ v = rand(n)*10
+ bins = [0,1,5, 9, 10]
+ a,b = histogram(v, bins, normed=True)
+ area = sum(a*diff(b))
+ assert_almost_equal(area, 1)
+
+
+ def test_outliers(self):
+ # Check that outliers are not tallied
+ a = arange(10)+.5
+
+ # Lower outliers
+ h,b = histogram(a, range=[0,9])
+ assert_equal(h.sum(),9)
+
+ # Upper outliers
+ h,b = histogram(a, range=[1,10])
+ assert_equal(h.sum(),9)
+
+ # Normalization
+ h,b = histogram(a, range=[1,9], normed=True)
+ assert_equal((h*diff(b)).sum(),1)
+
+ # Weights
+ w = arange(10)+.5
+ h,b = histogram(a, range=[1,9], weights=w, normed=True)
+ assert_equal((h*diff(b)).sum(),1)
+
+ h,b = histogram(a, bins=8, range=[1,9], weights=w)
+ assert_equal(h, w[1:-1])
+
+
+ def test_type(self):
+ # Check the type of the returned histogram
+ a = arange(10)+.5
+ h,b = histogram(a)
+ assert(issubdtype(h.dtype, int))
+
+ h,b = histogram(a, normed=True)
+ assert(issubdtype(h.dtype, float))
+
+ h,b = histogram(a, weights=ones(10, int))
+ assert(issubdtype(h.dtype, int))
+
+ h,b = histogram(a, weights=ones(10, float))
+ assert(issubdtype(h.dtype, float))
+
+
+ def test_weights(self):
+ v = rand(100)
+ w = ones(100)*5
+ a,b = histogram(v)
+ na,nb = histogram(v, normed=True)
+ wa,wb = histogram(v, weights=w)
+ nwa,nwb = histogram(v, weights=w, normed=True)
+ assert_array_almost_equal(a*5, wa)
+ assert_array_almost_equal(na, nwa)
+
+ # Check weights are properly applied.
+ v = linspace(0,10,10)
+ w = concatenate((zeros(5), ones(5)))
+ wa,wb = histogram(v, bins=arange(11),weights=w)
+ assert_array_almost_equal(wa, w)
+
+ # Check with integer weights
+ wa, wb = histogram([1,2,2,4], bins=4, weights=[4,3,2,1])
+ assert_array_equal(wa, [4,5,0,1])
+ wa, wb = histogram([1,2,2,4], bins=4, weights=[4,3,2,1], normed=True)
+ assert_array_equal(wa, array([4,5,0,1])/10./3.*4)
+
+class TestHistogramdd(TestCase):
+ def test_simple(self):
+ x = array([[-.5, .5, 1.5], [-.5, 1.5, 2.5], [-.5, 2.5, .5], \
+ [.5, .5, 1.5], [.5, 1.5, 2.5], [.5, 2.5, 2.5]])
+ H, edges = histogramdd(x, (2,3,3), range = [[-1,1], [0,3], [0,3]])
+ answer = asarray([[[0,1,0], [0,0,1], [1,0,0]], [[0,1,0], [0,0,1],
+ [0,0,1]]])
+ assert_array_equal(H,answer)
+ # Check normalization
+ ed = [[-2,0,2], [0,1,2,3], [0,1,2,3]]
+ H, edges = histogramdd(x, bins = ed, normed = True)
+ assert(all(H == answer/12.))
+ # Check that H has the correct shape.
+ H, edges = histogramdd(x, (2,3,4), range = [[-1,1], [0,3], [0,4]],
+ normed=True)
+ answer = asarray([[[0,1,0,0], [0,0,1,0], [1,0,0,0]], [[0,1,0,0],
+ [0,0,1,0], [0,0,1,0]]])
+ assert_array_almost_equal(H, answer/6., 4)
+ # Check that a sequence of arrays is accepted and H has the correct
+ # shape.
+ z = [squeeze(y) for y in split(x,3,axis=1)]
+ H, edges = histogramdd(z, bins=(4,3,2),range=[[-2,2], [0,3], [0,2]])
+ answer = asarray([[[0,0],[0,0],[0,0]],
+ [[0,1], [0,0], [1,0]],
+ [[0,1], [0,0],[0,0]],
+ [[0,0],[0,0],[0,0]]])
+ assert_array_equal(H, answer)
+
+ Z = zeros((5,5,5))
+ Z[range(5), range(5), range(5)] = 1.
+ H,edges = histogramdd([arange(5), arange(5), arange(5)], 5)
+ assert_array_equal(H, Z)
+
+ def test_shape_3d(self):
+ # All possible permutations for bins of different lengths in 3D.
+ bins = ((5, 4, 6), (6, 4, 5), (5, 6, 4), (4, 6, 5), (6, 5, 4),
+ (4, 5, 6))
+ r = rand(10,3)
+ for b in bins:
+ H, edges = histogramdd(r, b)
+ assert(H.shape == b)
+
+ def test_shape_4d(self):
+ # All possible permutations for bins of different lengths in 4D.
+ bins = ((7, 4, 5, 6), (4, 5, 7, 6), (5, 6, 4, 7), (7, 6, 5, 4),
+ (5, 7, 6, 4), (4, 6, 7, 5), (6, 5, 7, 4), (7, 5, 4, 6),
+ (7, 4, 6, 5), (6, 4, 7, 5), (6, 7, 5, 4), (4, 6, 5, 7),
+ (4, 7, 5, 6), (5, 4, 6, 7), (5, 7, 4, 6), (6, 7, 4, 5),
+ (6, 5, 4, 7), (4, 7, 6, 5), (4, 5, 6, 7), (7, 6, 4, 5),
+ (5, 4, 7, 6), (5, 6, 7, 4), (6, 4, 5, 7), (7, 5, 6, 4))
+
+ r = rand(10,4)
+ for b in bins:
+ H, edges = histogramdd(r, b)
+ assert(H.shape == b)
+
+ def test_weights(self):
+ v = rand(100,2)
+ hist, edges = histogramdd(v)
+ n_hist, edges = histogramdd(v, normed=True)
+ w_hist, edges = histogramdd(v, weights=ones(100))
+ assert_array_equal(w_hist, hist)
+ w_hist, edges = histogramdd(v, weights=ones(100)*2, normed=True)
+ assert_array_equal(w_hist, n_hist)
+ w_hist, edges = histogramdd(v, weights=ones(100, int)*2)
+ assert_array_equal(w_hist, 2*hist)
+
+ def test_identical_samples(self):
+ x = zeros((10,2),int)
+ hist, edges = histogramdd(x, bins=2)
+ assert_array_equal(edges[0],array([-0.5, 0. , 0.5]))
+
+class TestUnique(TestCase):
+ def test_simple(self):
+ x = array([4,3,2,1,1,2,3,4, 0])
+ assert(all(unique(x) == [0,1,2,3,4]))
+ assert(unique(array([1,1,1,1,1])) == array([1]))
+ x = ['widget', 'ham', 'foo', 'bar', 'foo', 'ham']
+ assert(all(unique(x) == ['bar', 'foo', 'ham', 'widget']))
+ x = array([5+6j, 1+1j, 1+10j, 10, 5+6j])
+ assert(all(unique(x) == [1+1j, 1+10j, 5+6j, 10]))
+
+
+class TestCheckFinite(TestCase):
+ def test_simple(self):
+ a = [1,2,3]
+ b = [1,2,inf]
+ c = [1,2,nan]
+ numpy.lib.asarray_chkfinite(a)
+ assert_raises(ValueError, numpy.lib.asarray_chkfinite, b)
+ assert_raises(ValueError, numpy.lib.asarray_chkfinite, c)
+
+class TestNaNFuncts(TestCase):
+ def setUp(self):
+ self.A = array([[[ nan, 0.01319214, 0.01620964],
+ [ 0.11704017, nan, 0.75157887],
+ [ 0.28333658, 0.1630199 , nan ]],
+ [[ 0.59541557, nan, 0.37910852],
+ [ nan, 0.87964135, nan ],
+ [ 0.70543747, nan, 0.34306596]],
+ [[ 0.72687499, 0.91084584, nan ],
+ [ 0.84386844, 0.38944762, 0.23913896],
+ [ nan, 0.37068164, 0.33850425]]])
+
+ def test_nansum(self):
+ assert_almost_equal(nansum(self.A), 8.0664079100000006)
+ assert_almost_equal(nansum(self.A,0),
+ array([[ 1.32229056, 0.92403798, 0.39531816],
+ [ 0.96090861, 1.26908897, 0.99071783],
+ [ 0.98877405, 0.53370154, 0.68157021]]))
+ assert_almost_equal(nansum(self.A,1),
+ array([[ 0.40037675, 0.17621204, 0.76778851],
+ [ 1.30085304, 0.87964135, 0.72217448],
+ [ 1.57074343, 1.6709751 , 0.57764321]]))
+ assert_almost_equal(nansum(self.A,2),
+ array([[ 0.02940178, 0.86861904, 0.44635648],
+ [ 0.97452409, 0.87964135, 1.04850343],
+ [ 1.63772083, 1.47245502, 0.70918589]]))
+
+ def test_nanmin(self):
+ assert_almost_equal(nanmin(self.A), 0.01319214)
+ assert_almost_equal(nanmin(self.A,0),
+ array([[ 0.59541557, 0.01319214, 0.01620964],
+ [ 0.11704017, 0.38944762, 0.23913896],
+ [ 0.28333658, 0.1630199 , 0.33850425]]))
+ assert_almost_equal(nanmin(self.A,1),
+ array([[ 0.11704017, 0.01319214, 0.01620964],
+ [ 0.59541557, 0.87964135, 0.34306596],
+ [ 0.72687499, 0.37068164, 0.23913896]]))
+ assert_almost_equal(nanmin(self.A,2),
+ array([[ 0.01319214, 0.11704017, 0.1630199 ],
+ [ 0.37910852, 0.87964135, 0.34306596],
+ [ 0.72687499, 0.23913896, 0.33850425]]))
+ assert nanmin([nan, nan]) is nan
+
+ def test_nanargmin(self):
+ assert_almost_equal(nanargmin(self.A), 1)
+ assert_almost_equal(nanargmin(self.A,0),
+ array([[1, 0, 0],
+ [0, 2, 2],
+ [0, 0, 2]]))
+ assert_almost_equal(nanargmin(self.A,1),
+ array([[1, 0, 0],
+ [0, 1, 2],
+ [0, 2, 1]]))
+ assert_almost_equal(nanargmin(self.A,2),
+ array([[1, 0, 1],
+ [2, 1, 2],
+ [0, 2, 2]]))
+
+ def test_nanmax(self):
+ assert_almost_equal(nanmax(self.A), 0.91084584000000002)
+ assert_almost_equal(nanmax(self.A,0),
+ array([[ 0.72687499, 0.91084584, 0.37910852],
+ [ 0.84386844, 0.87964135, 0.75157887],
+ [ 0.70543747, 0.37068164, 0.34306596]]))
+ assert_almost_equal(nanmax(self.A,1),
+ array([[ 0.28333658, 0.1630199 , 0.75157887],
+ [ 0.70543747, 0.87964135, 0.37910852],
+ [ 0.84386844, 0.91084584, 0.33850425]]))
+ assert_almost_equal(nanmax(self.A,2),
+ array([[ 0.01620964, 0.75157887, 0.28333658],
+ [ 0.59541557, 0.87964135, 0.70543747],
+ [ 0.91084584, 0.84386844, 0.37068164]]))
+
+
+class TestCorrCoef(TestCase):
+ def test_simple(self):
+ A = array([[ 0.15391142, 0.18045767, 0.14197213],
+ [ 0.70461506, 0.96474128, 0.27906989],
+ [ 0.9297531 , 0.32296769, 0.19267156]])
+ B = array([[ 0.10377691, 0.5417086 , 0.49807457],
+ [ 0.82872117, 0.77801674, 0.39226705],
+ [ 0.9314666 , 0.66800209, 0.03538394]])
+ assert_almost_equal(corrcoef(A),
+ array([[ 1. , 0.9379533 , -0.04931983],
+ [ 0.9379533 , 1. , 0.30007991],
+ [-0.04931983, 0.30007991, 1. ]]))
+ assert_almost_equal(corrcoef(A,B),
+ array([[ 1. , 0.9379533 , -0.04931983,
+ 0.30151751, 0.66318558, 0.51532523],
+ [ 0.9379533 , 1. , 0.30007991,
+ -0.04781421, 0.88157256, 0.78052386],
+ [-0.04931983, 0.30007991, 1. ,
+ -0.96717111, 0.71483595, 0.83053601],
+ [ 0.30151751, -0.04781421, -0.96717111,
+ 1. , -0.51366032, -0.66173113],
+ [ 0.66318558, 0.88157256, 0.71483595,
+ -0.51366032, 1. , 0.98317823],
+ [ 0.51532523, 0.78052386, 0.83053601,
+ -0.66173113, 0.98317823, 1. ]]))
+
+
+
+class Test_i0(TestCase):
+ def test_simple(self):
+ assert_almost_equal(i0(0.5), array(1.0634833707413234))
+ A = array([ 0.49842636, 0.6969809 , 0.22011976, 0.0155549])
+ assert_almost_equal(i0(A),
+ array([ 1.06307822, 1.12518299, 1.01214991, 1.00006049]))
+ B = array([[ 0.827002 , 0.99959078],
+ [ 0.89694769, 0.39298162],
+ [ 0.37954418, 0.05206293],
+ [ 0.36465447, 0.72446427],
+ [ 0.48164949, 0.50324519]])
+ assert_almost_equal(i0(B),
+ array([[ 1.17843223, 1.26583466],
+ [ 1.21147086, 1.0389829 ],
+ [ 1.03633899, 1.00067775],
+ [ 1.03352052, 1.13557954],
+ [ 1.0588429 , 1.06432317]]))
+
+class TestKaiser(TestCase):
+ def test_simple(self):
+ assert_almost_equal(kaiser(0,1.0), array([]))
+ assert isnan(kaiser(1,1.0))
+ assert_almost_equal(kaiser(2,1.0), array([ 0.78984831, 0.78984831]))
+ assert_almost_equal(kaiser(5,1.0),
+ array([ 0.78984831, 0.94503323, 1. ,
+ 0.94503323, 0.78984831]))
+ assert_almost_equal(kaiser(5,1.56789),
+ array([ 0.58285404, 0.88409679, 1. ,
+ 0.88409679, 0.58285404]))
+
+class TestMsort(TestCase):
+ def test_simple(self):
+ A = array([[ 0.44567325, 0.79115165, 0.5490053 ],
+ [ 0.36844147, 0.37325583, 0.96098397],
+ [ 0.64864341, 0.52929049, 0.39172155]])
+ assert_almost_equal(msort(A),
+ array([[ 0.36844147, 0.37325583, 0.39172155],
+ [ 0.44567325, 0.52929049, 0.5490053 ],
+ [ 0.64864341, 0.79115165, 0.96098397]]))
+
+class TestMeshgrid(TestCase):
+ def test_simple(self):
+ [X, Y] = meshgrid([1,2,3], [4,5,6,7])
+ assert all(X == array([[1, 2, 3],
+ [1, 2, 3],
+ [1, 2, 3],
+ [1, 2, 3]]))
+ assert all(Y == array([[4, 4, 4],
+ [5, 5, 5],
+ [6, 6, 6],
+ [7, 7, 7]]))
+
+
+class TestPiecewise(TestCase):
+ def test_simple(self):
+ # Condition is single bool list
+ x = piecewise([0, 0], [True, False], [1])
+ assert_array_equal(x, [1, 0])
+
+ # List of conditions: single bool list
+ x = piecewise([0, 0], [[True, False]], [1])
+ assert_array_equal(x, [1, 0])
+
+ # Conditions is single bool array
+ x = piecewise([0, 0], array([True, False]), [1])
+ assert_array_equal(x, [1, 0])
+
+ # Condition is single int array
+ x = piecewise([0, 0], array([1, 0]), [1])
+ assert_array_equal(x, [1, 0])
+
+ # List of conditions: int array
+ x = piecewise([0, 0], [array([1, 0])], [1])
+ assert_array_equal(x, [1, 0])
+
+
+ x = piecewise([0, 0], [[False, True]], [lambda x: -1])
+ assert_array_equal(x, [0, -1])
+
+ x = piecewise([1, 2], [[True, False], [False, True]], [3, 4])
+ assert_array_equal(x, [3, 4])
+
+ def test_default(self):
+ # No value specified for x[1], should be 0
+ x = piecewise([1, 2], [True, False], [2])
+ assert_array_equal(x, [2, 0])
+
+ # Should set x[1] to 3
+ x = piecewise([1, 2], [True, False], [2, 3])
+ assert_array_equal(x, [2, 3])
+
+ def test_0d(self):
+ x = array(3)
+ y = piecewise(x, x>3, [4, 0])
+ assert y.ndim == 0
+ assert y == 0
+
+def compare_results(res,desired):
+ for i in range(len(desired)):
+ assert_array_equal(res[i],desired[i])
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_getlimits.py b/numpy/lib/tests/test_getlimits.py
new file mode 100644
index 000000000..3fe939b32
--- /dev/null
+++ b/numpy/lib/tests/test_getlimits.py
@@ -0,0 +1,55 @@
+""" Test functions for limits module.
+"""
+
+from numpy.testing import *
+import numpy.lib
+reload(numpy.lib)
+from numpy.lib.getlimits import finfo, iinfo
+from numpy import single,double,longdouble
+import numpy as np
+
+##################################################
+
+class TestPythonFloat(TestCase):
+ def test_singleton(self):
+ ftype = finfo(float)
+ ftype2 = finfo(float)
+ assert_equal(id(ftype),id(ftype2))
+
+class TestSingle(TestCase):
+ def test_singleton(self):
+ ftype = finfo(single)
+ ftype2 = finfo(single)
+ assert_equal(id(ftype),id(ftype2))
+
+class TestDouble(TestCase):
+ def test_singleton(self):
+ ftype = finfo(double)
+ ftype2 = finfo(double)
+ assert_equal(id(ftype),id(ftype2))
+
+class TestLongdouble(TestCase):
+ def test_singleton(self,level=2):
+ ftype = finfo(longdouble)
+ ftype2 = finfo(longdouble)
+ assert_equal(id(ftype),id(ftype2))
+
+class TestIinfo(TestCase):
+ def test_basic(self):
+ dts = zip(['i1', 'i2', 'i4', 'i8',
+ 'u1', 'u2', 'u4', 'u8'],
+ [np.int8, np.int16, np.int32, np.int64,
+ np.uint8, np.uint16, np.uint32, np.uint64])
+ for dt1, dt2 in dts:
+ assert_equal(iinfo(dt1).min, iinfo(dt2).min)
+ assert_equal(iinfo(dt1).max, iinfo(dt2).max)
+ self.assertRaises(ValueError, iinfo, 'f4')
+
+ def test_unsigned_max(self):
+ types = np.sctypes['uint']
+ for T in types:
+ assert_equal(iinfo(T).max, T(-1))
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py
new file mode 100644
index 000000000..47529502d
--- /dev/null
+++ b/numpy/lib/tests/test_index_tricks.py
@@ -0,0 +1,66 @@
+from numpy.testing import *
+from numpy import array, ones, r_, mgrid, unravel_index
+
+class TestUnravelIndex(TestCase):
+ def test_basic(self):
+ assert unravel_index(2,(2,2)) == (1,0)
+ assert unravel_index(254,(17,94)) == (2, 66)
+ assert_raises(ValueError, unravel_index, 4,(2,2))
+
+
+class TestGrid(TestCase):
+ def test_basic(self):
+ a = mgrid[-1:1:10j]
+ b = mgrid[-1:1:0.1]
+ assert(a.shape == (10,))
+ assert(b.shape == (20,))
+ assert(a[0] == -1)
+ assert_almost_equal(a[-1],1)
+ assert(b[0] == -1)
+ assert_almost_equal(b[1]-b[0],0.1,11)
+ assert_almost_equal(b[-1],b[0]+19*0.1,11)
+ assert_almost_equal(a[1]-a[0],2.0/9.0,11)
+
+ def test_nd(self):
+ c = mgrid[-1:1:10j,-2:2:10j]
+ d = mgrid[-1:1:0.1,-2:2:0.2]
+ assert(c.shape == (2,10,10))
+ assert(d.shape == (2,20,20))
+ assert_array_equal(c[0][0,:],-ones(10,'d'))
+ assert_array_equal(c[1][:,0],-2*ones(10,'d'))
+ assert_array_almost_equal(c[0][-1,:],ones(10,'d'),11)
+ assert_array_almost_equal(c[1][:,-1],2*ones(10,'d'),11)
+ assert_array_almost_equal(d[0,1,:]-d[0,0,:], 0.1*ones(20,'d'),11)
+ assert_array_almost_equal(d[1,:,1]-d[1,:,0], 0.2*ones(20,'d'),11)
+
+
+class TestConcatenator(TestCase):
+ def test_1d(self):
+ assert_array_equal(r_[1,2,3,4,5,6],array([1,2,3,4,5,6]))
+ b = ones(5)
+ c = r_[b,0,0,b]
+ assert_array_equal(c,[1,1,1,1,1,0,0,1,1,1,1,1])
+
+ def test_mixed_type(self):
+ g = r_[10.1, 1:10]
+ assert(g.dtype == 'f8')
+
+ def test_more_mixed_type(self):
+ g = r_[-10.1, array([1]), array([2,3,4]), 10.0]
+ assert(g.dtype == 'f8')
+
+ def test_2d(self):
+ b = rand(5,5)
+ c = rand(5,5)
+ d = r_['1',b,c] # append columns
+ assert(d.shape == (5,10))
+ assert_array_equal(d[:,:5],b)
+ assert_array_equal(d[:,5:],c)
+ d = r_[b,c]
+ assert(d.shape == (10,5))
+ assert_array_equal(d[:5,:],b)
+ assert_array_equal(d[5:,:],c)
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py
new file mode 100644
index 000000000..e78fd0579
--- /dev/null
+++ b/numpy/lib/tests/test_io.py
@@ -0,0 +1,306 @@
+from numpy.testing import *
+import numpy as np
+import StringIO
+
+
+class RoundtripTest:
+ def test_array(self):
+ a = np.array( [[1,2],[3,4]], float)
+ self.do(a)
+
+ a = np.array( [[1,2],[3,4]], int)
+ self.do(a)
+
+ a = np.array( [[1+5j,2+6j],[3+7j,4+8j]], dtype=np.csingle)
+ self.do(a)
+
+ a = np.array( [[1+5j,2+6j],[3+7j,4+8j]], dtype=np.cdouble)
+ self.do(a)
+
+ def test_1D(self):
+ a = np.array([1,2,3,4], int)
+ self.do(a)
+
+ def test_record(self):
+ a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
+ self.do(a)
+
+class TestSaveLoad(RoundtripTest, TestCase):
+ def do(self, a):
+ c = StringIO.StringIO()
+ np.save(c, a)
+ c.seek(0)
+ a_reloaded = np.load(c)
+ assert_equal(a, a_reloaded)
+
+
+class TestSavezLoad(RoundtripTest, TestCase):
+ def do(self, *arrays):
+ c = StringIO.StringIO()
+ np.savez(c, *arrays)
+ c.seek(0)
+ l = np.load(c)
+ for n, a in enumerate(arrays):
+ assert_equal(a, l['arr_%d' % n])
+
+ def test_multiple_arrays(self):
+ a = np.array( [[1,2],[3,4]], float)
+ b = np.array( [[1+2j,2+7j],[3-6j,4+12j]], complex)
+ self.do(a,b)
+
+ def test_named_arrays(self):
+ a = np.array( [[1,2],[3,4]], float)
+ b = np.array( [[1+2j,2+7j],[3-6j,4+12j]], complex)
+ c = StringIO.StringIO()
+ np.savez(c, file_a=a, file_b=b)
+ c.seek(0)
+ l = np.load(c)
+ assert_equal(a, l['file_a'])
+ assert_equal(b, l['file_b'])
+
+
+class TestSaveTxt(TestCase):
+ def test_array(self):
+ a =np.array( [[1,2],[3,4]], float)
+ c = StringIO.StringIO()
+ np.savetxt(c, a)
+ c.seek(0)
+ assert(c.readlines() ==
+ ['1.000000000000000000e+00 2.000000000000000000e+00\n',
+ '3.000000000000000000e+00 4.000000000000000000e+00\n'])
+
+ a =np.array( [[1,2],[3,4]], int)
+ c = StringIO.StringIO()
+ np.savetxt(c, a, fmt='%d')
+ c.seek(0)
+ assert_equal(c.readlines(), ['1 2\n', '3 4\n'])
+
+ def test_1D(self):
+ a = np.array([1,2,3,4], int)
+ c = StringIO.StringIO()
+ np.savetxt(c, a, fmt='%d')
+ c.seek(0)
+ lines = c.readlines()
+ assert_equal(lines, ['1\n', '2\n', '3\n', '4\n'])
+
+ def test_record(self):
+ a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
+ c = StringIO.StringIO()
+ np.savetxt(c, a, fmt='%d')
+ c.seek(0)
+ assert_equal(c.readlines(), ['1 2\n', '3 4\n'])
+
+ def test_delimiter(self):
+ a = np.array([[1., 2.], [3., 4.]])
+ c = StringIO.StringIO()
+ np.savetxt(c, a, delimiter=',', fmt='%d')
+ c.seek(0)
+ assert_equal(c.readlines(), ['1,2\n', '3,4\n'])
+
+ def test_format(self):
+ a = np.array([(1, 2), (3, 4)])
+ c = StringIO.StringIO()
+ # Sequence of formats
+ np.savetxt(c, a, fmt=['%02d', '%3.1f'])
+ c.seek(0)
+ assert_equal(c.readlines(), ['01 2.0\n', '03 4.0\n'])
+
+ # A single multiformat string
+ c = StringIO.StringIO()
+ np.savetxt(c, a, fmt='%02d : %3.1f')
+ c.seek(0)
+ lines = c.readlines()
+ assert_equal(lines, ['01 : 2.0\n', '03 : 4.0\n'])
+
+ # Specify delimiter, should be overiden
+ c = StringIO.StringIO()
+ np.savetxt(c, a, fmt='%02d : %3.1f', delimiter=',')
+ c.seek(0)
+ lines = c.readlines()
+ assert_equal(lines, ['01 : 2.0\n', '03 : 4.0\n'])
+
+
+class TestLoadTxt(TestCase):
+ def test_record(self):
+ c = StringIO.StringIO()
+ c.write('1 2\n3 4')
+ c.seek(0)
+ x = np.loadtxt(c, dtype=[('x', np.int32), ('y', np.int32)])
+ a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
+ assert_array_equal(x, a)
+
+ d = StringIO.StringIO()
+ d.write('M 64.0 75.0\nF 25.0 60.0')
+ d.seek(0)
+ mydescriptor = {'names': ('gender','age','weight'),
+ 'formats': ('S1',
+ 'i4', 'f4')}
+ b = np.array([('M', 64.0, 75.0),
+ ('F', 25.0, 60.0)], dtype=mydescriptor)
+ y = np.loadtxt(d, dtype=mydescriptor)
+ assert_array_equal(y, b)
+
+ def test_array(self):
+ c = StringIO.StringIO()
+ c.write('1 2\n3 4')
+
+ c.seek(0)
+ x = np.loadtxt(c, dtype=int)
+ a = np.array([[1,2],[3,4]], int)
+ assert_array_equal(x, a)
+
+ c.seek(0)
+ x = np.loadtxt(c, dtype=float)
+ a = np.array([[1,2],[3,4]], float)
+ assert_array_equal(x, a)
+
+ def test_1D(self):
+ c = StringIO.StringIO()
+ c.write('1\n2\n3\n4\n')
+ c.seek(0)
+ x = np.loadtxt(c, dtype=int)
+ a = np.array([1,2,3,4], int)
+ assert_array_equal(x, a)
+
+ c = StringIO.StringIO()
+ c.write('1,2,3,4\n')
+ c.seek(0)
+ x = np.loadtxt(c, dtype=int, delimiter=',')
+ a = np.array([1,2,3,4], int)
+ assert_array_equal(x, a)
+
+ def test_missing(self):
+ c = StringIO.StringIO()
+ c.write('1,2,3,,5\n')
+ c.seek(0)
+ x = np.loadtxt(c, dtype=int, delimiter=',', \
+ converters={3:lambda s: int(s or -999)})
+ a = np.array([1,2,3,-999,5], int)
+ assert_array_equal(x, a)
+
+ def test_converters_with_usecols(self):
+ c = StringIO.StringIO()
+ c.write('1,2,3,,5\n6,7,8,9,10\n')
+ c.seek(0)
+ x = np.loadtxt(c, dtype=int, delimiter=',', \
+ converters={3:lambda s: int(s or -999)}, \
+ usecols=(1, 3, ))
+ a = np.array([[2, -999],[7, 9]], int)
+ assert_array_equal(x, a)
+
+ def test_comments(self):
+ c = StringIO.StringIO()
+ c.write('# comment\n1,2,3,5\n')
+ c.seek(0)
+ x = np.loadtxt(c, dtype=int, delimiter=',', \
+ comments='#')
+ a = np.array([1,2,3,5], int)
+ assert_array_equal(x, a)
+
+ def test_skiprows(self):
+ c = StringIO.StringIO()
+ c.write('comment\n1,2,3,5\n')
+ c.seek(0)
+ x = np.loadtxt(c, dtype=int, delimiter=',', \
+ skiprows=1)
+ a = np.array([1,2,3,5], int)
+ assert_array_equal(x, a)
+
+ c = StringIO.StringIO()
+ c.write('# comment\n1,2,3,5\n')
+ c.seek(0)
+ x = np.loadtxt(c, dtype=int, delimiter=',', \
+ skiprows=1)
+ a = np.array([1,2,3,5], int)
+ assert_array_equal(x, a)
+
+ def test_usecols(self):
+ a =np.array( [[1,2],[3,4]], float)
+ c = StringIO.StringIO()
+ np.savetxt(c, a)
+ c.seek(0)
+ x = np.loadtxt(c, dtype=float, usecols=(1,))
+ assert_array_equal(x, a[:,1])
+
+ a =np.array( [[1,2,3],[3,4,5]], float)
+ c = StringIO.StringIO()
+ np.savetxt(c, a)
+ c.seek(0)
+ x = np.loadtxt(c, dtype=float, usecols=(1,2))
+ assert_array_equal(x, a[:,1:])
+
+ # Testing with arrays instead of tuples.
+ c.seek(0)
+ x = np.loadtxt(c, dtype=float, usecols=np.array([1,2]))
+ assert_array_equal(x, a[:,1:])
+
+ # Checking with dtypes defined converters.
+ data = '''JOE 70.1 25.3
+ BOB 60.5 27.9
+ '''
+ c = StringIO.StringIO(data)
+ names = ['stid', 'temp']
+ dtypes = ['S4', 'f8']
+ arr = np.loadtxt(c, usecols=(0,2),dtype=zip(names,dtypes))
+ assert_equal(arr['stid'], ["JOE", "BOB"])
+ assert_equal(arr['temp'], [25.3, 27.9])
+
+ def test_fancy_dtype(self):
+ c = StringIO.StringIO()
+ c.write('1,2,3.0\n4,5,6.0\n')
+ c.seek(0)
+ dt = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
+ x = np.loadtxt(c, dtype=dt, delimiter=',')
+ a = np.array([(1,(2,3.0)),(4,(5,6.0))], dt)
+ assert_array_equal(x, a)
+
+ def test_empty_file(self):
+ c = StringIO.StringIO()
+ assert_raises(IOError, np.loadtxt, c)
+
+ def test_unused_converter(self):
+ c = StringIO.StringIO()
+ c.writelines(['1 21\n', '3 42\n'])
+ c.seek(0)
+ data = np.loadtxt(c, usecols=(1,), converters={0: lambda s: int(s, 16)})
+ assert_array_equal(data, [21, 42])
+
+ c.seek(0)
+ data = np.loadtxt(c, usecols=(1,), converters={1: lambda s: int(s, 16)})
+ assert_array_equal(data, [33, 66])
+
+class Testfromregex(TestCase):
+ def test_record(self):
+ c = StringIO.StringIO()
+ c.write('1.312 foo\n1.534 bar\n4.444 qux')
+ c.seek(0)
+
+ dt = [('num', np.float64), ('val', 'S3')]
+ x = np.fromregex(c, r"([0-9.]+)\s+(...)", dt)
+ a = np.array([(1.312, 'foo'), (1.534, 'bar'), (4.444, 'qux')], dtype=dt)
+ assert_array_equal(x, a)
+
+ def test_record_2(self):
+ return # pass this test until #736 is resolved
+ c = StringIO.StringIO()
+ c.write('1312 foo\n1534 bar\n4444 qux')
+ c.seek(0)
+
+ dt = [('num', np.int32), ('val', 'S3')]
+ x = np.fromregex(c, r"(\d+)\s+(...)", dt)
+ a = np.array([(1312, 'foo'), (1534, 'bar'), (4444, 'qux')], dtype=dt)
+ assert_array_equal(x, a)
+
+ def test_record_3(self):
+ c = StringIO.StringIO()
+ c.write('1312 foo\n1534 bar\n4444 qux')
+ c.seek(0)
+
+ dt = [('num', np.float64)]
+ x = np.fromregex(c, r"(\d+)\s+...", dt)
+ a = np.array([(1312,), (1534,), (4444,)], dtype=dt)
+ assert_array_equal(x, a)
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_machar.py b/numpy/lib/tests/test_machar.py
new file mode 100644
index 000000000..64abf7236
--- /dev/null
+++ b/numpy/lib/tests/test_machar.py
@@ -0,0 +1,31 @@
+from numpy.testing import *
+
+from numpy.lib.machar import MachAr
+import numpy.core.numerictypes as ntypes
+from numpy import seterr, array
+
+class TestMachAr(TestCase):
+ def _run_machar_highprec(self):
+ # Instanciate MachAr instance with high enough precision to cause
+ # underflow
+ try:
+ hiprec = ntypes.float96
+ machar = MachAr(lambda v:array([v], hiprec))
+ except AttributeError:
+ "Skipping test: no nyptes.float96 available on this platform."
+
+ def test_underlow(self):
+ """Regression testing for #759: instanciating MachAr for dtype =
+ np.float96 raises spurious warning."""
+ serrstate = seterr(all='raise')
+ try:
+ try:
+ self._run_machar_highprec()
+ except FloatingPointError, e:
+ self.fail("Caught %s exception, should not have been raised." % e)
+ finally:
+ seterr(**serrstate)
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py
new file mode 100644
index 000000000..96dd084b2
--- /dev/null
+++ b/numpy/lib/tests/test_polynomial.py
@@ -0,0 +1,115 @@
+"""
+>>> import numpy.core as nx
+>>> from numpy.lib.polynomial import poly1d, polydiv
+
+>>> p = poly1d([1.,2,3])
+>>> p
+poly1d([ 1., 2., 3.])
+>>> print p
+ 2
+1 x + 2 x + 3
+>>> q = poly1d([3.,2,1])
+>>> q
+poly1d([ 3., 2., 1.])
+>>> print q
+ 2
+3 x + 2 x + 1
+
+>>> p(0)
+3.0
+>>> p(5)
+38.0
+>>> q(0)
+1.0
+>>> q(5)
+86.0
+
+>>> p * q
+poly1d([ 3., 8., 14., 8., 3.])
+>>> p / q
+(poly1d([ 0.33333333]), poly1d([ 1.33333333, 2.66666667]))
+>>> p + q
+poly1d([ 4., 4., 4.])
+>>> p - q
+poly1d([-2., 0., 2.])
+>>> p ** 4
+poly1d([ 1., 8., 36., 104., 214., 312., 324., 216., 81.])
+
+>>> p(q)
+poly1d([ 9., 12., 16., 8., 6.])
+>>> q(p)
+poly1d([ 3., 12., 32., 40., 34.])
+
+>>> nx.asarray(p)
+array([ 1., 2., 3.])
+>>> len(p)
+2
+
+>>> p[0], p[1], p[2], p[3]
+(3.0, 2.0, 1.0, 0)
+
+>>> p.integ()
+poly1d([ 0.33333333, 1. , 3. , 0. ])
+>>> p.integ(1)
+poly1d([ 0.33333333, 1. , 3. , 0. ])
+>>> p.integ(5)
+poly1d([ 0.00039683, 0.00277778, 0.025 , 0. , 0. ,
+ 0. , 0. , 0. ])
+>>> p.deriv()
+poly1d([ 2., 2.])
+>>> p.deriv(2)
+poly1d([ 2.])
+
+>>> q = poly1d([1.,2,3], variable='y')
+>>> print q
+ 2
+1 y + 2 y + 3
+>>> q = poly1d([1.,2,3], variable='lambda')
+>>> print q
+ 2
+1 lambda + 2 lambda + 3
+
+>>> polydiv(poly1d([1,0,-1]), poly1d([1,1]))
+(poly1d([ 1., -1.]), poly1d([ 0.]))
+"""
+
+from numpy.testing import *
+import numpy as np
+
+class TestDocs(TestCase):
+ def test_doctests(self):
+ return rundocs()
+
+ def test_roots(self):
+ assert_array_equal(np.roots([1,0,0]), [0,0])
+
+ def test_str_leading_zeros(self):
+ p = np.poly1d([4,3,2,1])
+ p[3] = 0
+ assert_equal(str(p),
+ " 2\n"
+ "3 x + 2 x + 1")
+
+ p = np.poly1d([1,2])
+ p[0] = 0
+ p[1] = 0
+ assert_equal(str(p), " \n0")
+
+ def test_polyfit(self) :
+ c = np.array([3., 2., 1.])
+ x = np.linspace(0,2,5)
+ y = np.polyval(c,x)
+ # check 1D case
+ assert_almost_equal(c, np.polyfit(x,y,2))
+ # check 2D (n,1) case
+ y = y[:,np.newaxis]
+ c = c[:,np.newaxis]
+ assert_almost_equal(c, np.polyfit(x,y,2))
+ # check 2D (n,2) case
+ yy = np.concatenate((y,y), axis=1)
+ cc = np.concatenate((c,c), axis=1)
+ assert_almost_equal(cc, np.polyfit(x,yy,2))
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_regression.py b/numpy/lib/tests/test_regression.py
new file mode 100644
index 000000000..189b2e481
--- /dev/null
+++ b/numpy/lib/tests/test_regression.py
@@ -0,0 +1,30 @@
+from numpy.testing import *
+import numpy as np
+
+rlevel = 1
+
+class TestRegression(TestCase):
+ def test_polyfit_build(self,level=rlevel):
+ """Ticket #628"""
+ ref = [-1.06123820e-06, 5.70886914e-04, -1.13822012e-01,
+ 9.95368241e+00, -3.14526520e+02]
+ x = [90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103,
+ 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115,
+ 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 129,
+ 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
+ 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157,
+ 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169,
+ 170, 171, 172, 173, 174, 175, 176]
+ y = [9.0, 3.0, 7.0, 4.0, 4.0, 8.0, 6.0, 11.0, 9.0, 8.0, 11.0, 5.0,
+ 6.0, 5.0, 9.0, 8.0, 6.0, 10.0, 6.0, 10.0, 7.0, 6.0, 6.0, 6.0,
+ 13.0, 4.0, 9.0, 11.0, 4.0, 5.0, 8.0, 5.0, 7.0, 7.0, 6.0, 12.0,
+ 7.0, 7.0, 9.0, 4.0, 12.0, 6.0, 6.0, 4.0, 3.0, 9.0, 8.0, 8.0,
+ 6.0, 7.0, 9.0, 10.0, 6.0, 8.0, 4.0, 7.0, 7.0, 10.0, 8.0, 8.0,
+ 6.0, 3.0, 8.0, 4.0, 5.0, 7.0, 8.0, 6.0, 6.0, 4.0, 12.0, 9.0,
+ 8.0, 8.0, 8.0, 6.0, 7.0, 4.0, 4.0, 5.0, 7.0]
+ tested = np.polyfit(x, y, 4)
+ assert_array_almost_equal(ref, tested)
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_shape_base.py b/numpy/lib/tests/test_shape_base.py
new file mode 100644
index 000000000..59c48dba0
--- /dev/null
+++ b/numpy/lib/tests/test_shape_base.py
@@ -0,0 +1,454 @@
+from numpy.testing import *
+from numpy.lib import *
+from numpy.core import *
+
+class TestApplyAlongAxis(TestCase):
+ def test_simple(self):
+ a = ones((20,10),'d')
+ assert_array_equal(apply_along_axis(len,0,a),len(a)*ones(shape(a)[1]))
+
+ def test_simple101(self,level=11):
+ a = ones((10,101),'d')
+ assert_array_equal(apply_along_axis(len,0,a),len(a)*ones(shape(a)[1]))
+
+ def test_3d(self):
+ a = arange(27).reshape((3,3,3))
+ assert_array_equal(apply_along_axis(sum,0,a),
+ [[27,30,33],[36,39,42],[45,48,51]])
+
+
+class TestApplyOverAxes(TestCase):
+ def test_simple(self):
+ a = arange(24).reshape(2,3,4)
+ aoa_a = apply_over_axes(sum, a, [0,2])
+ assert_array_equal(aoa_a, array([[[60],[92],[124]]]))
+
+
+class TestArraySplit(TestCase):
+ def test_integer_0_split(self):
+ a = arange(10)
+ try:
+ res = array_split(a,0)
+ assert(0) # it should have thrown a value error
+ except ValueError:
+ pass
+
+ def test_integer_split(self):
+ a = arange(10)
+ res = array_split(a,1)
+ desired = [arange(10)]
+ compare_results(res,desired)
+
+ res = array_split(a,2)
+ desired = [arange(5),arange(5,10)]
+ compare_results(res,desired)
+
+ res = array_split(a,3)
+ desired = [arange(4),arange(4,7),arange(7,10)]
+ compare_results(res,desired)
+
+ res = array_split(a,4)
+ desired = [arange(3),arange(3,6),arange(6,8),arange(8,10)]
+ compare_results(res,desired)
+
+ res = array_split(a,5)
+ desired = [arange(2),arange(2,4),arange(4,6),arange(6,8),arange(8,10)]
+ compare_results(res,desired)
+
+ res = array_split(a,6)
+ desired = [arange(2),arange(2,4),arange(4,6),arange(6,8),arange(8,9),
+ arange(9,10)]
+ compare_results(res,desired)
+
+ res = array_split(a,7)
+ desired = [arange(2),arange(2,4),arange(4,6),arange(6,7),arange(7,8),
+ arange(8,9), arange(9,10)]
+ compare_results(res,desired)
+
+ res = array_split(a,8)
+ desired = [arange(2),arange(2,4),arange(4,5),arange(5,6),arange(6,7),
+ arange(7,8), arange(8,9), arange(9,10)]
+ compare_results(res,desired)
+
+ res = array_split(a,9)
+ desired = [arange(2),arange(2,3),arange(3,4),arange(4,5),arange(5,6),
+ arange(6,7), arange(7,8), arange(8,9), arange(9,10)]
+ compare_results(res,desired)
+
+ res = array_split(a,10)
+ desired = [arange(1),arange(1,2),arange(2,3),arange(3,4),
+ arange(4,5),arange(5,6), arange(6,7), arange(7,8),
+ arange(8,9), arange(9,10)]
+ compare_results(res,desired)
+
+ res = array_split(a,11)
+ desired = [arange(1),arange(1,2),arange(2,3),arange(3,4),
+ arange(4,5),arange(5,6), arange(6,7), arange(7,8),
+ arange(8,9), arange(9,10),array([])]
+ compare_results(res,desired)
+
+ def test_integer_split_2D_rows(self):
+ a = array([arange(10),arange(10)])
+ res = array_split(a,3,axis=0)
+ desired = [array([arange(10)]),array([arange(10)]),array([])]
+ compare_results(res,desired)
+
+ def test_integer_split_2D_cols(self):
+ a = array([arange(10),arange(10)])
+ res = array_split(a,3,axis=-1)
+ desired = [array([arange(4),arange(4)]),
+ array([arange(4,7),arange(4,7)]),
+ array([arange(7,10),arange(7,10)])]
+ compare_results(res,desired)
+
+ def test_integer_split_2D_default(self):
+ """ This will fail if we change default axis
+ """
+ a = array([arange(10),arange(10)])
+ res = array_split(a,3)
+ desired = [array([arange(10)]),array([arange(10)]),array([])]
+ compare_results(res,desired)
+ #perhaps should check higher dimensions
+
+ def test_index_split_simple(self):
+ a = arange(10)
+ indices = [1,5,7]
+ res = array_split(a,indices,axis=-1)
+ desired = [arange(0,1),arange(1,5),arange(5,7),arange(7,10)]
+ compare_results(res,desired)
+
+ def test_index_split_low_bound(self):
+ a = arange(10)
+ indices = [0,5,7]
+ res = array_split(a,indices,axis=-1)
+ desired = [array([]),arange(0,5),arange(5,7),arange(7,10)]
+ compare_results(res,desired)
+
+ def test_index_split_high_bound(self):
+ a = arange(10)
+ indices = [0,5,7,10,12]
+ res = array_split(a,indices,axis=-1)
+ desired = [array([]),arange(0,5),arange(5,7),arange(7,10),
+ array([]),array([])]
+ compare_results(res,desired)
+
+
+class TestSplit(TestCase):
+ """* This function is essentially the same as array_split,
+ except that it test if splitting will result in an
+ equal split. Only test for this case.
+ *"""
+ def test_equal_split(self):
+ a = arange(10)
+ res = split(a,2)
+ desired = [arange(5),arange(5,10)]
+ compare_results(res,desired)
+
+ def test_unequal_split(self):
+ a = arange(10)
+ try:
+ res = split(a,3)
+ assert(0) # should raise an error
+ except ValueError:
+ pass
+
+
+class TestAtleast1d(TestCase):
+ def test_0D_array(self):
+ a = array(1); b = array(2);
+ res=map(atleast_1d,[a,b])
+ desired = [array([1]),array([2])]
+ assert_array_equal(res,desired)
+
+ def test_1D_array(self):
+ a = array([1,2]); b = array([2,3]);
+ res=map(atleast_1d,[a,b])
+ desired = [array([1,2]),array([2,3])]
+ assert_array_equal(res,desired)
+
+ def test_2D_array(self):
+ a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
+ res=map(atleast_1d,[a,b])
+ desired = [a,b]
+ assert_array_equal(res,desired)
+
+ def test_3D_array(self):
+ a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
+ a = array([a,a]);b = array([b,b]);
+ res=map(atleast_1d,[a,b])
+ desired = [a,b]
+ assert_array_equal(res,desired)
+
+ def test_r1array(self):
+ """ Test to make sure equivalent Travis O's r1array function
+ """
+ assert(atleast_1d(3).shape == (1,))
+ assert(atleast_1d(3j).shape == (1,))
+ assert(atleast_1d(3L).shape == (1,))
+ assert(atleast_1d(3.0).shape == (1,))
+ assert(atleast_1d([[2,3],[4,5]]).shape == (2,2))
+
+class TestAtleast2d(TestCase):
+ def test_0D_array(self):
+ a = array(1); b = array(2);
+ res=map(atleast_2d,[a,b])
+ desired = [array([[1]]),array([[2]])]
+ assert_array_equal(res,desired)
+
+ def test_1D_array(self):
+ a = array([1,2]); b = array([2,3]);
+ res=map(atleast_2d,[a,b])
+ desired = [array([[1,2]]),array([[2,3]])]
+ assert_array_equal(res,desired)
+
+ def test_2D_array(self):
+ a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
+ res=map(atleast_2d,[a,b])
+ desired = [a,b]
+ assert_array_equal(res,desired)
+
+ def test_3D_array(self):
+ a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
+ a = array([a,a]);b = array([b,b]);
+ res=map(atleast_2d,[a,b])
+ desired = [a,b]
+ assert_array_equal(res,desired)
+
+ def test_r2array(self):
+ """ Test to make sure equivalent Travis O's r2array function
+ """
+ assert(atleast_2d(3).shape == (1,1))
+ assert(atleast_2d([3j,1]).shape == (1,2))
+ assert(atleast_2d([[[3,1],[4,5]],[[3,5],[1,2]]]).shape == (2,2,2))
+
+
+class TestAtleast3d(TestCase):
+ def test_0D_array(self):
+ a = array(1); b = array(2);
+ res=map(atleast_3d,[a,b])
+ desired = [array([[[1]]]),array([[[2]]])]
+ assert_array_equal(res,desired)
+
+ def test_1D_array(self):
+ a = array([1,2]); b = array([2,3]);
+ res=map(atleast_3d,[a,b])
+ desired = [array([[[1],[2]]]),array([[[2],[3]]])]
+ assert_array_equal(res,desired)
+
+ def test_2D_array(self):
+ a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
+ res=map(atleast_3d,[a,b])
+ desired = [a[:,:,newaxis],b[:,:,newaxis]]
+ assert_array_equal(res,desired)
+
+ def test_3D_array(self):
+ a = array([[1,2],[1,2]]); b = array([[2,3],[2,3]]);
+ a = array([a,a]);b = array([b,b]);
+ res=map(atleast_3d,[a,b])
+ desired = [a,b]
+ assert_array_equal(res,desired)
+
+class TestHstack(TestCase):
+ def test_0D_array(self):
+ a = array(1); b = array(2);
+ res=hstack([a,b])
+ desired = array([1,2])
+ assert_array_equal(res,desired)
+
+ def test_1D_array(self):
+ a = array([1]); b = array([2]);
+ res=hstack([a,b])
+ desired = array([1,2])
+ assert_array_equal(res,desired)
+
+ def test_2D_array(self):
+ a = array([[1],[2]]); b = array([[1],[2]]);
+ res=hstack([a,b])
+ desired = array([[1,1],[2,2]])
+ assert_array_equal(res,desired)
+
+class TestVstack(TestCase):
+ def test_0D_array(self):
+ a = array(1); b = array(2);
+ res=vstack([a,b])
+ desired = array([[1],[2]])
+ assert_array_equal(res,desired)
+
+ def test_1D_array(self):
+ a = array([1]); b = array([2]);
+ res=vstack([a,b])
+ desired = array([[1],[2]])
+ assert_array_equal(res,desired)
+
+ def test_2D_array(self):
+ a = array([[1],[2]]); b = array([[1],[2]]);
+ res=vstack([a,b])
+ desired = array([[1],[2],[1],[2]])
+ assert_array_equal(res,desired)
+
+ def test_2D_array2(self):
+ a = array([1,2]); b = array([1,2]);
+ res=vstack([a,b])
+ desired = array([[1,2],[1,2]])
+ assert_array_equal(res,desired)
+
+class TestDstack(TestCase):
+ def test_0D_array(self):
+ a = array(1); b = array(2);
+ res=dstack([a,b])
+ desired = array([[[1,2]]])
+ assert_array_equal(res,desired)
+
+ def test_1D_array(self):
+ a = array([1]); b = array([2]);
+ res=dstack([a,b])
+ desired = array([[[1,2]]])
+ assert_array_equal(res,desired)
+
+ def test_2D_array(self):
+ a = array([[1],[2]]); b = array([[1],[2]]);
+ res=dstack([a,b])
+ desired = array([[[1,1]],[[2,2,]]])
+ assert_array_equal(res,desired)
+
+ def test_2D_array2(self):
+ a = array([1,2]); b = array([1,2]);
+ res=dstack([a,b])
+ desired = array([[[1,1],[2,2]]])
+ assert_array_equal(res,desired)
+
+""" array_split has more comprehensive test of splitting.
+ only do simple test on hsplit, vsplit, and dsplit
+"""
+class TestHsplit(TestCase):
+ """ only testing for integer splits.
+ """
+ def test_0D_array(self):
+ a= array(1)
+ try:
+ hsplit(a,2)
+ assert(0)
+ except ValueError:
+ pass
+
+ def test_1D_array(self):
+ a= array([1,2,3,4])
+ res = hsplit(a,2)
+ desired = [array([1,2]),array([3,4])]
+ compare_results(res,desired)
+
+ def test_2D_array(self):
+ a= array([[1,2,3,4],
+ [1,2,3,4]])
+ res = hsplit(a,2)
+ desired = [array([[1,2],[1,2]]),array([[3,4],[3,4]])]
+ compare_results(res,desired)
+
+
+class TestVsplit(TestCase):
+ """ only testing for integer splits.
+ """
+ def test_1D_array(self):
+ a= array([1,2,3,4])
+ try:
+ vsplit(a,2)
+ assert(0)
+ except ValueError:
+ pass
+
+ def test_2D_array(self):
+ a= array([[1,2,3,4],
+ [1,2,3,4]])
+ res = vsplit(a,2)
+ desired = [array([[1,2,3,4]]),array([[1,2,3,4]])]
+ compare_results(res,desired)
+
+
+class TestDsplit(TestCase):
+ """ only testing for integer splits.
+ """
+ def test_2D_array(self):
+ a= array([[1,2,3,4],
+ [1,2,3,4]])
+ try:
+ dsplit(a,2)
+ assert(0)
+ except ValueError:
+ pass
+
+ def test_3D_array(self):
+ a= array([[[1,2,3,4],
+ [1,2,3,4]],
+ [[1,2,3,4],
+ [1,2,3,4]]])
+ res = dsplit(a,2)
+ desired = [array([[[1,2],[1,2]],[[1,2],[1,2]]]),
+ array([[[3,4],[3,4]],[[3,4],[3,4]]])]
+ compare_results(res,desired)
+
+
+class TestSqueeze(TestCase):
+ def test_basic(self):
+ a = rand(20,10,10,1,1)
+ b = rand(20,1,10,1,20)
+ c = rand(1,1,20,10)
+ assert_array_equal(squeeze(a),reshape(a,(20,10,10)))
+ assert_array_equal(squeeze(b),reshape(b,(20,10,20)))
+ assert_array_equal(squeeze(c),reshape(c,(20,10)))
+
+
+class TestKron(TestCase):
+ def test_return_type(self):
+ a = ones([2,2])
+ m = asmatrix(a)
+ assert_equal(type(kron(a,a)), ndarray)
+ assert_equal(type(kron(m,m)), matrix)
+ assert_equal(type(kron(a,m)), matrix)
+ assert_equal(type(kron(m,a)), matrix)
+ class myarray(ndarray):
+ __array_priority__ = 0.0
+ ma = myarray(a.shape, a.dtype, a.data)
+ assert_equal(type(kron(a,a)), ndarray)
+ assert_equal(type(kron(ma,ma)), myarray)
+ assert_equal(type(kron(a,ma)), ndarray)
+ assert_equal(type(kron(ma,a)), myarray)
+
+
+class TestTile(TestCase):
+ def test_basic(self):
+ a = array([0,1,2])
+ b = [[1,2],[3,4]]
+ assert_equal(tile(a,2), [0,1,2,0,1,2])
+ assert_equal(tile(a,(2,2)), [[0,1,2,0,1,2],[0,1,2,0,1,2]])
+ assert_equal(tile(a,(1,2)), [[0,1,2,0,1,2]])
+ assert_equal(tile(b, 2), [[1,2,1,2],[3,4,3,4]])
+ assert_equal(tile(b,(2,1)),[[1,2],[3,4],[1,2],[3,4]])
+ assert_equal(tile(b,(2,2)),[[1,2,1,2],[3,4,3,4],
+ [1,2,1,2],[3,4,3,4]])
+
+ def test_empty(self):
+ a = array([[[]]])
+ d = tile(a,(3,2,5)).shape
+ assert_equal(d,(3,2,0))
+
+ def test_kroncompare(self):
+ import numpy.random as nr
+ reps=[(2,),(1,2),(2,1),(2,2),(2,3,2),(3,2)]
+ shape=[(3,),(2,3),(3,4,3),(3,2,3),(4,3,2,4),(2,2)]
+ for s in shape:
+ b = nr.randint(0,10,size=s)
+ for r in reps:
+ a = ones(r, b.dtype)
+ large = tile(b, r)
+ klarge = kron(a, b)
+ assert_equal(large, klarge)
+
+
+# Utility
+def compare_results(res,desired):
+ for i in range(len(desired)):
+ assert_array_equal(res[i],desired[i])
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_stride_tricks.py b/numpy/lib/tests/test_stride_tricks.py
new file mode 100644
index 000000000..8f0ac52b8
--- /dev/null
+++ b/numpy/lib/tests/test_stride_tricks.py
@@ -0,0 +1,208 @@
+import numpy as np
+from numpy.testing import *
+from numpy.lib.stride_tricks import broadcast_arrays
+
+
+def assert_shapes_correct(input_shapes, expected_shape):
+ """ Broadcast a list of arrays with the given input shapes and check the
+ common output shape.
+ """
+ inarrays = [np.zeros(s) for s in input_shapes]
+ outarrays = broadcast_arrays(*inarrays)
+ outshapes = [a.shape for a in outarrays]
+ expected = [expected_shape] * len(inarrays)
+ assert outshapes == expected
+
+def assert_incompatible_shapes_raise(input_shapes):
+ """ Broadcast a list of arrays with the given (incompatible) input shapes
+ and check that they raise a ValueError.
+ """
+ inarrays = [np.zeros(s) for s in input_shapes]
+ assert_raises(ValueError, broadcast_arrays, *inarrays)
+
+def assert_same_as_ufunc(shape0, shape1, transposed=False, flipped=False):
+ """ Broadcast two shapes against each other and check that the data layout
+ is the same as if a ufunc did the broadcasting.
+ """
+ x0 = np.zeros(shape0, dtype=int)
+ # Note that multiply.reduce's identity element is 1.0, so when shape1==(),
+ # this gives the desired n==1.
+ n = int(np.multiply.reduce(shape1))
+ x1 = np.arange(n).reshape(shape1)
+ if transposed:
+ x0 = x0.T
+ x1 = x1.T
+ if flipped:
+ x0 = x0[::-1]
+ x1 = x1[::-1]
+ # Use the add ufunc to do the broadcasting. Since we're adding 0s to x1, the
+ # result should be exactly the same as the broadcasted view of x1.
+ y = x0 + x1
+ b0, b1 = broadcast_arrays(x0, x1)
+ assert_array_equal(y, b1)
+
+
+def test_same():
+ x = np.arange(10)
+ y = np.arange(10)
+ bx, by = broadcast_arrays(x, y)
+ assert_array_equal(x, bx)
+ assert_array_equal(y, by)
+
+def test_one_off():
+ x = np.array([[1,2,3]])
+ y = np.array([[1],[2],[3]])
+ bx, by = broadcast_arrays(x, y)
+ bx0 = np.array([[1,2,3],[1,2,3],[1,2,3]])
+ by0 = bx0.T
+ assert_array_equal(bx0, bx)
+ assert_array_equal(by0, by)
+
+def test_same_input_shapes():
+ """ Check that the final shape is just the input shape.
+ """
+ data = [
+ (),
+ (1,),
+ (3,),
+ (0,1),
+ (0,3),
+ (1,0),
+ (3,0),
+ (1,3),
+ (3,1),
+ (3,3),
+ ]
+ for shape in data:
+ input_shapes = [shape]
+ # Single input.
+ yield assert_shapes_correct, input_shapes, shape
+ # Double input.
+ input_shapes2 = [shape, shape]
+ yield assert_shapes_correct, input_shapes2, shape
+ # Triple input.
+ input_shapes3 = [shape, shape, shape]
+ yield assert_shapes_correct, input_shapes3, shape
+
+def test_two_compatible_by_ones_input_shapes():
+ """ Check that two different input shapes (of the same length but some have
+ 1s) broadcast to the correct shape.
+ """
+ data = [
+ [[(1,), (3,)], (3,)],
+ [[(1,3), (3,3)], (3,3)],
+ [[(3,1), (3,3)], (3,3)],
+ [[(1,3), (3,1)], (3,3)],
+ [[(1,1), (3,3)], (3,3)],
+ [[(1,1), (1,3)], (1,3)],
+ [[(1,1), (3,1)], (3,1)],
+ [[(1,0), (0,0)], (0,0)],
+ [[(0,1), (0,0)], (0,0)],
+ [[(1,0), (0,1)], (0,0)],
+ [[(1,1), (0,0)], (0,0)],
+ [[(1,1), (1,0)], (1,0)],
+ [[(1,1), (0,1)], (0,1)],
+ ]
+ for input_shapes, expected_shape in data:
+ yield assert_shapes_correct, input_shapes, expected_shape
+ # Reverse the input shapes since broadcasting should be symmetric.
+ yield assert_shapes_correct, input_shapes[::-1], expected_shape
+
+def test_two_compatible_by_prepending_ones_input_shapes():
+ """ Check that two different input shapes (of different lengths) broadcast
+ to the correct shape.
+ """
+ data = [
+ [[(), (3,)], (3,)],
+ [[(3,), (3,3)], (3,3)],
+ [[(3,), (3,1)], (3,3)],
+ [[(1,), (3,3)], (3,3)],
+ [[(), (3,3)], (3,3)],
+ [[(1,1), (3,)], (1,3)],
+ [[(1,), (3,1)], (3,1)],
+ [[(1,), (1,3)], (1,3)],
+ [[(), (1,3)], (1,3)],
+ [[(), (3,1)], (3,1)],
+ [[(), (0,)], (0,)],
+ [[(0,), (0,0)], (0,0)],
+ [[(0,), (0,1)], (0,0)],
+ [[(1,), (0,0)], (0,0)],
+ [[(), (0,0)], (0,0)],
+ [[(1,1), (0,)], (1,0)],
+ [[(1,), (0,1)], (0,1)],
+ [[(1,), (1,0)], (1,0)],
+ [[(), (1,0)], (1,0)],
+ [[(), (0,1)], (0,1)],
+ ]
+ for input_shapes, expected_shape in data:
+ yield assert_shapes_correct, input_shapes, expected_shape
+ # Reverse the input shapes since broadcasting should be symmetric.
+ yield assert_shapes_correct, input_shapes[::-1], expected_shape
+
+def test_incompatible_shapes_raise_valueerror():
+ """ Check that a ValueError is raised for incompatible shapes.
+ """
+ data = [
+ [(3,), (4,)],
+ [(2,3), (2,)],
+ [(3,), (3,), (4,)],
+ [(1,3,4), (2,3,3)],
+ ]
+ for input_shapes in data:
+ yield assert_incompatible_shapes_raise, input_shapes
+ # Reverse the input shapes since broadcasting should be symmetric.
+ yield assert_incompatible_shapes_raise, input_shapes[::-1]
+
+def test_same_as_ufunc():
+ """ Check that the data layout is the same as if a ufunc did the operation.
+ """
+ data = [
+ [[(1,), (3,)], (3,)],
+ [[(1,3), (3,3)], (3,3)],
+ [[(3,1), (3,3)], (3,3)],
+ [[(1,3), (3,1)], (3,3)],
+ [[(1,1), (3,3)], (3,3)],
+ [[(1,1), (1,3)], (1,3)],
+ [[(1,1), (3,1)], (3,1)],
+ [[(1,0), (0,0)], (0,0)],
+ [[(0,1), (0,0)], (0,0)],
+ [[(1,0), (0,1)], (0,0)],
+ [[(1,1), (0,0)], (0,0)],
+ [[(1,1), (1,0)], (1,0)],
+ [[(1,1), (0,1)], (0,1)],
+ [[(), (3,)], (3,)],
+ [[(3,), (3,3)], (3,3)],
+ [[(3,), (3,1)], (3,3)],
+ [[(1,), (3,3)], (3,3)],
+ [[(), (3,3)], (3,3)],
+ [[(1,1), (3,)], (1,3)],
+ [[(1,), (3,1)], (3,1)],
+ [[(1,), (1,3)], (1,3)],
+ [[(), (1,3)], (1,3)],
+ [[(), (3,1)], (3,1)],
+ [[(), (0,)], (0,)],
+ [[(0,), (0,0)], (0,0)],
+ [[(0,), (0,1)], (0,0)],
+ [[(1,), (0,0)], (0,0)],
+ [[(), (0,0)], (0,0)],
+ [[(1,1), (0,)], (1,0)],
+ [[(1,), (0,1)], (0,1)],
+ [[(1,), (1,0)], (1,0)],
+ [[(), (1,0)], (1,0)],
+ [[(), (0,1)], (0,1)],
+ ]
+ for input_shapes, expected_shape in data:
+ yield assert_same_as_ufunc, input_shapes[0], input_shapes[1]
+ # Reverse the input shapes since broadcasting should be symmetric.
+ yield assert_same_as_ufunc, input_shapes[1], input_shapes[0]
+ # Try them transposed, too.
+ yield assert_same_as_ufunc, input_shapes[0], input_shapes[1], True
+ # ... and flipped for non-rank-0 inputs in order to test negative
+ # strides.
+ if () not in input_shapes:
+ yield assert_same_as_ufunc, input_shapes[0], input_shapes[1], False, True
+ yield assert_same_as_ufunc, input_shapes[0], input_shapes[1], True, True
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_twodim_base.py b/numpy/lib/tests/test_twodim_base.py
new file mode 100644
index 000000000..32c4ca58e
--- /dev/null
+++ b/numpy/lib/tests/test_twodim_base.py
@@ -0,0 +1,197 @@
+""" Test functions for matrix module
+
+"""
+
+from numpy.testing import *
+from numpy import arange, rot90, add, fliplr, flipud, zeros, ones, eye, \
+ array, diag, histogram2d, tri
+import numpy as np
+
+def get_mat(n):
+ data = arange(n)
+ data = add.outer(data,data)
+ return data
+
+class TestEye(TestCase):
+ def test_basic(self):
+ assert_equal(eye(4),array([[1,0,0,0],
+ [0,1,0,0],
+ [0,0,1,0],
+ [0,0,0,1]]))
+ assert_equal(eye(4,dtype='f'),array([[1,0,0,0],
+ [0,1,0,0],
+ [0,0,1,0],
+ [0,0,0,1]],'f'))
+ assert_equal(eye(3) == 1, eye(3,dtype=bool))
+
+ def test_diag(self):
+ assert_equal(eye(4,k=1),array([[0,1,0,0],
+ [0,0,1,0],
+ [0,0,0,1],
+ [0,0,0,0]]))
+ assert_equal(eye(4,k=-1),array([[0,0,0,0],
+ [1,0,0,0],
+ [0,1,0,0],
+ [0,0,1,0]]))
+ def test_2d(self):
+ assert_equal(eye(4,3),array([[1,0,0],
+ [0,1,0],
+ [0,0,1],
+ [0,0,0]]))
+ assert_equal(eye(3,4),array([[1,0,0,0],
+ [0,1,0,0],
+ [0,0,1,0]]))
+ def test_diag2d(self):
+ assert_equal(eye(3,4,k=2),array([[0,0,1,0],
+ [0,0,0,1],
+ [0,0,0,0]]))
+ assert_equal(eye(4,3,k=-2),array([[0,0,0],
+ [0,0,0],
+ [1,0,0],
+ [0,1,0]]))
+
+class TestDiag(TestCase):
+ def test_vector(self):
+ vals = (100*arange(5)).astype('l')
+ b = zeros((5,5))
+ for k in range(5):
+ b[k,k] = vals[k]
+ assert_equal(diag(vals),b)
+ b = zeros((7,7))
+ c = b.copy()
+ for k in range(5):
+ b[k,k+2] = vals[k]
+ c[k+2,k] = vals[k]
+ assert_equal(diag(vals,k=2), b)
+ assert_equal(diag(vals,k=-2), c)
+
+ def test_matrix(self):
+ vals = (100*get_mat(5)+1).astype('l')
+ b = zeros((5,))
+ for k in range(5):
+ b[k] = vals[k,k]
+ assert_equal(diag(vals),b)
+ b = b*0
+ for k in range(3):
+ b[k] = vals[k,k+2]
+ assert_equal(diag(vals,2),b[:3])
+ for k in range(3):
+ b[k] = vals[k+2,k]
+ assert_equal(diag(vals,-2),b[:3])
+
+class TestFliplr(TestCase):
+ def test_basic(self):
+ self.failUnlessRaises(ValueError, fliplr, ones(4))
+ a = get_mat(4)
+ b = a[:,::-1]
+ assert_equal(fliplr(a),b)
+ a = [[0,1,2],
+ [3,4,5]]
+ b = [[2,1,0],
+ [5,4,3]]
+ assert_equal(fliplr(a),b)
+
+class TestFlipud(TestCase):
+ def test_basic(self):
+ a = get_mat(4)
+ b = a[::-1,:]
+ assert_equal(flipud(a),b)
+ a = [[0,1,2],
+ [3,4,5]]
+ b = [[3,4,5],
+ [0,1,2]]
+ assert_equal(flipud(a),b)
+
+class TestRot90(TestCase):
+ def test_basic(self):
+ self.failUnlessRaises(ValueError, rot90, ones(4))
+
+ a = [[0,1,2],
+ [3,4,5]]
+ b1 = [[2,5],
+ [1,4],
+ [0,3]]
+ b2 = [[5,4,3],
+ [2,1,0]]
+ b3 = [[3,0],
+ [4,1],
+ [5,2]]
+ b4 = [[0,1,2],
+ [3,4,5]]
+
+ for k in range(-3,13,4):
+ assert_equal(rot90(a,k=k),b1)
+ for k in range(-2,13,4):
+ assert_equal(rot90(a,k=k),b2)
+ for k in range(-1,13,4):
+ assert_equal(rot90(a,k=k),b3)
+ for k in range(0,13,4):
+ assert_equal(rot90(a,k=k),b4)
+
+ def test_axes(self):
+ a = ones((50,40,3))
+ assert_equal(rot90(a).shape,(40,50,3))
+
+class TestHistogram2d(TestCase):
+ def test_simple(self):
+ x = array([ 0.41702200, 0.72032449, 0.00011437481, 0.302332573, 0.146755891])
+ y = array([ 0.09233859, 0.18626021, 0.34556073, 0.39676747, 0.53881673])
+ xedges = np.linspace(0,1,10)
+ yedges = np.linspace(0,1,10)
+ H = histogram2d(x, y, (xedges, yedges))[0]
+ answer = array([[0, 0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+ assert_array_equal(H.T, answer)
+ H = histogram2d(x, y, xedges)[0]
+ assert_array_equal(H.T, answer)
+ H,xedges,yedges = histogram2d(range(10),range(10))
+ assert_array_equal(H, eye(10,10))
+ assert_array_equal(xedges, np.linspace(0,9,11))
+ assert_array_equal(yedges, np.linspace(0,9,11))
+
+ def test_asym(self):
+ x = array([1, 1, 2, 3, 4, 4, 4, 5])
+ y = array([1, 3, 2, 0, 1, 2, 3, 4])
+ H, xed, yed = histogram2d(x,y, (6, 5), range = [[0,6],[0,5]], normed=True)
+ answer = array([[0.,0,0,0,0],
+ [0,1,0,1,0],
+ [0,0,1,0,0],
+ [1,0,0,0,0],
+ [0,1,1,1,0],
+ [0,0,0,0,1]])
+ assert_array_almost_equal(H, answer/8., 3)
+ assert_array_equal(xed, np.linspace(0,6,7))
+ assert_array_equal(yed, np.linspace(0,5,6))
+ def test_norm(self):
+ x = array([1,2,3,1,2,3,1,2,3])
+ y = array([1,1,1,2,2,2,3,3,3])
+ H, xed, yed = histogram2d(x,y,[[1,2,3,5], [1,2,3,5]], normed=True)
+ answer=array([[1,1,.5],
+ [1,1,.5],
+ [.5,.5,.25]])/9.
+ assert_array_almost_equal(H, answer, 3)
+
+ def test_all_outliers(self):
+ r = rand(100)+1.
+ H, xed, yed = histogram2d(r, r, (4, 5), range=([0,1], [0,1]))
+ assert_array_equal(H, 0)
+
+
+class TestTri(TestCase):
+ def test_dtype(self):
+ out = array([[1,0,0],
+ [1,1,0],
+ [1,1,1]])
+ assert_array_equal(tri(3),out)
+ assert_array_equal(tri(3,dtype=bool),out.astype(bool))
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_type_check.py b/numpy/lib/tests/test_type_check.py
new file mode 100644
index 000000000..82107d86c
--- /dev/null
+++ b/numpy/lib/tests/test_type_check.py
@@ -0,0 +1,291 @@
+from numpy.testing import *
+from numpy.lib import *
+from numpy.core import *
+
+def assert_all(x):
+ assert(all(x)), x
+
+
+class TestCommonType(TestCase):
+ def test_basic(self):
+ ai32 = array([[1,2],[3,4]], dtype=int32)
+ af32 = array([[1,2],[3,4]], dtype=float32)
+ af64 = array([[1,2],[3,4]], dtype=float64)
+ acs = array([[1+5j,2+6j],[3+7j,4+8j]], dtype=csingle)
+ acd = array([[1+5j,2+6j],[3+7j,4+8j]], dtype=cdouble)
+ assert common_type(af32) == float32
+ assert common_type(af64) == float64
+ assert common_type(acs) == csingle
+ assert common_type(acd) == cdouble
+
+
+
+class TestMintypecode(TestCase):
+
+ def test_default_1(self):
+ for itype in '1bcsuwil':
+ assert_equal(mintypecode(itype),'d')
+ assert_equal(mintypecode('f'),'f')
+ assert_equal(mintypecode('d'),'d')
+ assert_equal(mintypecode('F'),'F')
+ assert_equal(mintypecode('D'),'D')
+
+ def test_default_2(self):
+ for itype in '1bcsuwil':
+ assert_equal(mintypecode(itype+'f'),'f')
+ assert_equal(mintypecode(itype+'d'),'d')
+ assert_equal(mintypecode(itype+'F'),'F')
+ assert_equal(mintypecode(itype+'D'),'D')
+ assert_equal(mintypecode('ff'),'f')
+ assert_equal(mintypecode('fd'),'d')
+ assert_equal(mintypecode('fF'),'F')
+ assert_equal(mintypecode('fD'),'D')
+ assert_equal(mintypecode('df'),'d')
+ assert_equal(mintypecode('dd'),'d')
+ #assert_equal(mintypecode('dF',savespace=1),'F')
+ assert_equal(mintypecode('dF'),'D')
+ assert_equal(mintypecode('dD'),'D')
+ assert_equal(mintypecode('Ff'),'F')
+ #assert_equal(mintypecode('Fd',savespace=1),'F')
+ assert_equal(mintypecode('Fd'),'D')
+ assert_equal(mintypecode('FF'),'F')
+ assert_equal(mintypecode('FD'),'D')
+ assert_equal(mintypecode('Df'),'D')
+ assert_equal(mintypecode('Dd'),'D')
+ assert_equal(mintypecode('DF'),'D')
+ assert_equal(mintypecode('DD'),'D')
+
+ def test_default_3(self):
+ assert_equal(mintypecode('fdF'),'D')
+ #assert_equal(mintypecode('fdF',savespace=1),'F')
+ assert_equal(mintypecode('fdD'),'D')
+ assert_equal(mintypecode('fFD'),'D')
+ assert_equal(mintypecode('dFD'),'D')
+
+ assert_equal(mintypecode('ifd'),'d')
+ assert_equal(mintypecode('ifF'),'F')
+ assert_equal(mintypecode('ifD'),'D')
+ assert_equal(mintypecode('idF'),'D')
+ #assert_equal(mintypecode('idF',savespace=1),'F')
+ assert_equal(mintypecode('idD'),'D')
+
+class TestIsscalar(TestCase):
+ def test_basic(self):
+ assert(isscalar(3))
+ assert(not isscalar([3]))
+ assert(not isscalar((3,)))
+ assert(isscalar(3j))
+ assert(isscalar(10L))
+ assert(isscalar(4.0))
+
+class TestReal(TestCase):
+ def test_real(self):
+ y = rand(10,)
+ assert_array_equal(y,real(y))
+
+ def test_cmplx(self):
+ y = rand(10,)+1j*rand(10,)
+ assert_array_equal(y.real,real(y))
+
+class TestImag(TestCase):
+ def test_real(self):
+ y = rand(10,)
+ assert_array_equal(0,imag(y))
+
+ def test_cmplx(self):
+ y = rand(10,)+1j*rand(10,)
+ assert_array_equal(y.imag,imag(y))
+
+class TestIscomplex(TestCase):
+ def test_fail(self):
+ z = array([-1,0,1])
+ res = iscomplex(z)
+ assert(not sometrue(res,axis=0))
+ def test_pass(self):
+ z = array([-1j,1,0])
+ res = iscomplex(z)
+ assert_array_equal(res,[1,0,0])
+
+class TestIsreal(TestCase):
+ def test_pass(self):
+ z = array([-1,0,1j])
+ res = isreal(z)
+ assert_array_equal(res,[1,1,0])
+ def test_fail(self):
+ z = array([-1j,1,0])
+ res = isreal(z)
+ assert_array_equal(res,[0,1,1])
+
+class TestIscomplexobj(TestCase):
+ def test_basic(self):
+ z = array([-1,0,1])
+ assert(not iscomplexobj(z))
+ z = array([-1j,0,-1])
+ assert(iscomplexobj(z))
+
+class TestIsrealobj(TestCase):
+ def test_basic(self):
+ z = array([-1,0,1])
+ assert(isrealobj(z))
+ z = array([-1j,0,-1])
+ assert(not isrealobj(z))
+
+class TestIsnan(TestCase):
+ def test_goodvalues(self):
+ z = array((-1.,0.,1.))
+ res = isnan(z) == 0
+ assert_all(alltrue(res,axis=0))
+ def test_posinf(self):
+ olderr = seterr(divide='ignore')
+ assert_all(isnan(array((1.,))/0.) == 0)
+ seterr(**olderr)
+ def test_neginf(self):
+ olderr = seterr(divide='ignore')
+ assert_all(isnan(array((-1.,))/0.) == 0)
+ seterr(**olderr)
+ def test_ind(self):
+ olderr = seterr(divide='ignore', invalid='ignore')
+ assert_all(isnan(array((0.,))/0.) == 1)
+ seterr(**olderr)
+ #def test_qnan(self): log(-1) return pi*j now
+ # assert_all(isnan(log(-1.)) == 1)
+ def test_integer(self):
+ assert_all(isnan(1) == 0)
+ def test_complex(self):
+ assert_all(isnan(1+1j) == 0)
+ def test_complex1(self):
+ olderr = seterr(divide='ignore', invalid='ignore')
+ assert_all(isnan(array(0+0j)/0.) == 1)
+ seterr(**olderr)
+
+class TestIsfinite(TestCase):
+ def test_goodvalues(self):
+ z = array((-1.,0.,1.))
+ res = isfinite(z) == 1
+ assert_all(alltrue(res,axis=0))
+ def test_posinf(self):
+ olderr = seterr(divide='ignore')
+ assert_all(isfinite(array((1.,))/0.) == 0)
+ seterr(**olderr)
+ def test_neginf(self):
+ olderr = seterr(divide='ignore')
+ assert_all(isfinite(array((-1.,))/0.) == 0)
+ seterr(**olderr)
+ def test_ind(self):
+ olderr = seterr(divide='ignore', invalid='ignore')
+ assert_all(isfinite(array((0.,))/0.) == 0)
+ seterr(**olderr)
+ #def test_qnan(self):
+ # assert_all(isfinite(log(-1.)) == 0)
+ def test_integer(self):
+ assert_all(isfinite(1) == 1)
+ def test_complex(self):
+ assert_all(isfinite(1+1j) == 1)
+ def test_complex1(self):
+ olderr = seterr(divide='ignore', invalid='ignore')
+ assert_all(isfinite(array(1+1j)/0.) == 0)
+ seterr(**olderr)
+
+class TestIsinf(TestCase):
+ def test_goodvalues(self):
+ z = array((-1.,0.,1.))
+ res = isinf(z) == 0
+ assert_all(alltrue(res,axis=0))
+ def test_posinf(self):
+ olderr = seterr(divide='ignore')
+ assert_all(isinf(array((1.,))/0.) == 1)
+ seterr(**olderr)
+ def test_posinf_scalar(self):
+ olderr = seterr(divide='ignore')
+ assert_all(isinf(array(1.,)/0.) == 1)
+ seterr(**olderr)
+ def test_neginf(self):
+ olderr = seterr(divide='ignore')
+ assert_all(isinf(array((-1.,))/0.) == 1)
+ seterr(**olderr)
+ def test_neginf_scalar(self):
+ olderr = seterr(divide='ignore')
+ assert_all(isinf(array(-1.)/0.) == 1)
+ seterr(**olderr)
+ def test_ind(self):
+ olderr = seterr(divide='ignore', invalid='ignore')
+ assert_all(isinf(array((0.,))/0.) == 0)
+ seterr(**olderr)
+ #def test_qnan(self):
+ # assert_all(isinf(log(-1.)) == 0)
+ # assert_all(isnan(log(-1.)) == 1)
+
+class TestIsposinf(TestCase):
+ def test_generic(self):
+ olderr = seterr(divide='ignore', invalid='ignore')
+ vals = isposinf(array((-1.,0,1))/0.)
+ seterr(**olderr)
+ assert(vals[0] == 0)
+ assert(vals[1] == 0)
+ assert(vals[2] == 1)
+
+class TestIsneginf(TestCase):
+ def test_generic(self):
+ olderr = seterr(divide='ignore', invalid='ignore')
+ vals = isneginf(array((-1.,0,1))/0.)
+ seterr(**olderr)
+ assert(vals[0] == 1)
+ assert(vals[1] == 0)
+ assert(vals[2] == 0)
+
+class TestNanToNum(TestCase):
+ def test_generic(self):
+ olderr = seterr(divide='ignore', invalid='ignore')
+ vals = nan_to_num(array((-1.,0,1))/0.)
+ seterr(**olderr)
+ assert_all(vals[0] < -1e10) and assert_all(isfinite(vals[0]))
+ assert(vals[1] == 0)
+ assert_all(vals[2] > 1e10) and assert_all(isfinite(vals[2]))
+ def test_integer(self):
+ vals = nan_to_num(1)
+ assert_all(vals == 1)
+ def test_complex_good(self):
+ vals = nan_to_num(1+1j)
+ assert_all(vals == 1+1j)
+ def test_complex_bad(self):
+ v = 1+1j
+ olderr = seterr(divide='ignore', invalid='ignore')
+ v += array(0+1.j)/0.
+ seterr(**olderr)
+ vals = nan_to_num(v)
+ # !! This is actually (unexpectedly) zero
+ assert_all(isfinite(vals))
+ def test_complex_bad2(self):
+ v = 1+1j
+ olderr = seterr(divide='ignore', invalid='ignore')
+ v += array(-1+1.j)/0.
+ seterr(**olderr)
+ vals = nan_to_num(v)
+ assert_all(isfinite(vals))
+ #assert_all(vals.imag > 1e10) and assert_all(isfinite(vals))
+ # !! This is actually (unexpectedly) positive
+ # !! inf. Comment out for now, and see if it
+ # !! changes
+ #assert_all(vals.real < -1e10) and assert_all(isfinite(vals))
+
+
+class TestRealIfClose(TestCase):
+ def test_basic(self):
+ a = rand(10)
+ b = real_if_close(a+1e-15j)
+ assert_all(isrealobj(b))
+ assert_array_equal(a,b)
+ b = real_if_close(a+1e-7j)
+ assert_all(iscomplexobj(b))
+ b = real_if_close(a+1e-7j,tol=1e-6)
+ assert_all(isrealobj(b))
+
+class TestArrayConversion(TestCase):
+ def test_asfarray(self):
+ a = asfarray(array([1,2,3]))
+ assert_equal(a.__class__,ndarray)
+ assert issubdtype(a.dtype,float)
+
+
+if __name__ == "__main__":
+ run_module_suite()
diff --git a/numpy/lib/tests/test_ufunclike.py b/numpy/lib/tests/test_ufunclike.py
new file mode 100644
index 000000000..63e6a75de
--- /dev/null
+++ b/numpy/lib/tests/test_ufunclike.py
@@ -0,0 +1,67 @@
+"""
+>>> import numpy.core as nx
+>>> import numpy.lib.ufunclike as U
+
+Test fix:
+>>> a = nx.array([[1.0, 1.1, 1.5, 1.8], [-1.0, -1.1, -1.5, -1.8]])
+>>> U.fix(a)
+array([[ 1., 1., 1., 1.],
+ [-1., -1., -1., -1.]])
+>>> y = nx.zeros(a.shape, float)
+>>> U.fix(a, y)
+array([[ 1., 1., 1., 1.],
+ [-1., -1., -1., -1.]])
+>>> y
+array([[ 1., 1., 1., 1.],
+ [-1., -1., -1., -1.]])
+
+Test isposinf, isneginf, sign
+>>> a = nx.array([nx.Inf, -nx.Inf, nx.NaN, 0.0, 3.0, -3.0])
+>>> U.isposinf(a)
+array([ True, False, False, False, False, False], dtype=bool)
+>>> U.isneginf(a)
+array([False, True, False, False, False, False], dtype=bool)
+>>> olderr = nx.seterr(invalid='ignore')
+>>> nx.sign(a)
+array([ 1., -1., 0., 0., 1., -1.])
+>>> olderr = nx.seterr(**olderr)
+
+Same thing with an output array:
+>>> y = nx.zeros(a.shape, bool)
+>>> U.isposinf(a, y)
+array([ True, False, False, False, False, False], dtype=bool)
+>>> y
+array([ True, False, False, False, False, False], dtype=bool)
+>>> U.isneginf(a, y)
+array([False, True, False, False, False, False], dtype=bool)
+>>> y
+array([False, True, False, False, False, False], dtype=bool)
+>>> olderr = nx.seterr(invalid='ignore')
+>>> nx.sign(a, y)
+array([ True, True, False, False, True, True], dtype=bool)
+>>> olderr = nx.seterr(**olderr)
+>>> y
+array([ True, True, False, False, True, True], dtype=bool)
+
+Now log2:
+>>> a = nx.array([4.5, 2.3, 6.5])
+>>> U.log2(a)
+array([ 2.169925 , 1.20163386, 2.70043972])
+>>> 2**_
+array([ 4.5, 2.3, 6.5])
+>>> y = nx.zeros(a.shape, float)
+>>> U.log2(a, y)
+array([ 2.169925 , 1.20163386, 2.70043972])
+>>> y
+array([ 2.169925 , 1.20163386, 2.70043972])
+
+"""
+
+from numpy.testing import *
+
+def test():
+ return rundocs()
+
+
+if __name__ == "__main__":
+ run_module_suite()