From numpy-svn at scipy.org Mon Sep 1 08:10:35 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 1 Sep 2008 07:10:35 -0500 (CDT) Subject: [Numpy-svn] r5735 - / Message-ID: <20080901121035.B99E539C15C@scipy.org> Author: cdavid Date: 2008-09-01 07:10:31 -0500 (Mon, 01 Sep 2008) New Revision: 5735 Removed: cleaned_math_config/ Log: Grr, again create a branch at the root of repository. From numpy-svn at scipy.org Mon Sep 1 08:14:55 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 1 Sep 2008 07:14:55 -0500 (CDT) Subject: [Numpy-svn] r5736 - branches Message-ID: <20080901121455.E2BB939C2B4@scipy.org> Author: cdavid Date: 2008-09-01 07:14:42 -0500 (Mon, 01 Sep 2008) New Revision: 5736 Added: branches/clean_math_config/ Log: Start branch to clean math configuration for easier maintenance of new platforms. Copied: branches/clean_math_config (from rev 5735, trunk) From numpy-svn at scipy.org Mon Sep 1 08:16:34 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 1 Sep 2008 07:16:34 -0500 (CDT) Subject: [Numpy-svn] r5737 - trunk Message-ID: <20080901121634.F24FD39C15C@scipy.org> Author: cdavid Date: 2008-09-01 07:16:31 -0500 (Mon, 01 Sep 2008) New Revision: 5737 Modified: trunk/ Log: Initialized merge tracking via "svnmerge" with revisions "1-5736" from http://svn.scipy.org/svn/numpy/branches/clean_math_config Property changes on: trunk ___________________________________________________________________ Name: svnmerge-integrated - /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-2871 + /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/clean_math_config:1-5736 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-2871 From numpy-svn at scipy.org Mon Sep 1 08:18:55 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 1 Sep 2008 07:18:55 -0500 (CDT) Subject: [Numpy-svn] r5738 - branches/clean_math_config Message-ID: <20080901121855.D023639C15C@scipy.org> Author: cdavid Date: 2008-09-01 07:18:52 -0500 (Mon, 01 Sep 2008) New Revision: 5738 Modified: branches/clean_math_config/ Log: Initialized merge tracking via "svnmerge" with revisions "1-5737" from http://svn.scipy.org/svn/numpy/trunk Property changes on: branches/clean_math_config ___________________________________________________________________ Name: svnmerge-integrated - /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-2871 + /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5737 From numpy-svn at scipy.org Mon Sep 1 08:50:50 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 1 Sep 2008 07:50:50 -0500 (CDT) Subject: [Numpy-svn] r5739 - trunk/numpy/lib/tests Message-ID: <20080901125050.37CF539C15C@scipy.org> Author: cdavid Date: 2008-09-01 07:50:46 -0500 (Mon, 01 Sep 2008) New Revision: 5739 Modified: trunk/numpy/lib/tests/test_format.py Log: Disable memmap test which crashes nose tests on cygwin. Modified: trunk/numpy/lib/tests/test_format.py =================================================================== --- trunk/numpy/lib/tests/test_format.py 2008-09-01 12:18:52 UTC (rev 5738) +++ trunk/numpy/lib/tests/test_format.py 2008-09-01 12:50:46 UTC (rev 5739) @@ -421,7 +421,7 @@ def test_memmap_roundtrip(): # XXX: test crashes nose on windows. Fix this - if not sys.platform == 'win32': + 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. From numpy-svn at scipy.org Mon Sep 1 09:07:39 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 1 Sep 2008 08:07:39 -0500 (CDT) Subject: [Numpy-svn] r5740 - trunk/numpy/core/src Message-ID: <20080901130739.A771B39C15C@scipy.org> Author: cdavid Date: 2008-09-01 08:07:30 -0500 (Mon, 01 Sep 2008) New Revision: 5740 Modified: trunk/numpy/core/src/scalartypes.inc.src Log: Fix unused variable warning in object_arrtype_new. Modified: trunk/numpy/core/src/scalartypes.inc.src =================================================================== --- trunk/numpy/core/src/scalartypes.inc.src 2008-09-01 12:50:46 UTC (rev 5739) +++ trunk/numpy/core/src/scalartypes.inc.src 2008-09-01 13:07:30 UTC (rev 5740) @@ -1899,8 +1899,10 @@ PyObject *robj; PyObject *arr; PyArray_Descr *typecode = NULL; +#if !(@default@ == 2) int itemsize; void *dest, *src; +#endif /* allow base-class (if any) to do conversion */ /* If successful, this will jump to finish: */ From numpy-svn at scipy.org Tue Sep 2 02:59:51 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 2 Sep 2008 01:59:51 -0500 (CDT) Subject: [Numpy-svn] r5741 - trunk/numpy/core/tests Message-ID: <20080902065951.BD9C439C036@scipy.org> Author: cdavid Date: 2008-09-02 01:59:43 -0500 (Tue, 02 Sep 2008) New Revision: 5741 Modified: trunk/numpy/core/tests/test_regression.py Log: Fix regression test #771 on 64 bits architecture. The test assumed an item was 4 bytes. Use itemsize instead of harcoding 4 bytes per item. Modified: trunk/numpy/core/tests/test_regression.py =================================================================== --- trunk/numpy/core/tests/test_regression.py 2008-09-01 13:07:30 UTC (rev 5740) +++ trunk/numpy/core/tests/test_regression.py 2008-09-02 06:59:43 UTC (rev 5741) @@ -847,7 +847,7 @@ """Ticket #771: strides are not set correctly when reshaping 0-sized arrays""" b = np.indices((0,3,4)).T.reshape(-1,3) - assert_equal(b.strides, (12, 4)) + assert_equal(b.strides, (3 * b.itemsize, b.itemsize)) def test_object_array_refcounting(self, level=rlevel): """Ticket #633""" From numpy-svn at scipy.org Tue Sep 2 16:13:20 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 2 Sep 2008 15:13:20 -0500 (CDT) Subject: [Numpy-svn] r5742 - trunk/doc Message-ID: <20080902201320.0CCD239C10E@scipy.org> Author: jarrod.millman Date: 2008-09-02 15:13:17 -0500 (Tue, 02 Sep 2008) New Revision: 5742 Added: trunk/doc/TESTS.txt Modified: trunk/doc/DISTUTILS.txt Log: pulling out testing docs from distutils docs Modified: trunk/doc/DISTUTILS.txt =================================================================== --- trunk/doc/DISTUTILS.txt 2008-09-02 06:59:43 UTC (rev 5741) +++ trunk/doc/DISTUTILS.txt 2008-09-02 20:13:17 UTC (rev 5742) @@ -453,58 +453,6 @@ from numpy.testing import NumpyTest test = NumpyTest().test -The ``tests/`` directory -'''''''''''''''''''''''' - -Ideally, every Python code, extension module, or subpackage in Scipy -package directory should have the corresponding ``test_.py`` -file in ``tests/`` directory. This file should define classes -derived from the ``numpy.testing.TestCase`` class (or from -``unittest.TestCase``) and have names starting with ``test``. The methods -of these classes whose names contain ``test`` or start with ``bench`` are -automatically picked up by the test machinery. - -A minimal example of a ``test_yyy.py`` file that implements tests for -a NumPy package module ``numpy.xxx.yyy`` containing a function -``zzz()``, is shown below:: - - import sys - from numpy.testing import * - - # import xxx symbols - from numpy.xxx.yyy import zzz - - - class test_zzz(TestCase): - def test_simple(self, level=1): - assert zzz()=='Hello from zzz' - #... - - if __name__ == "__main__": - run_module_tests(file) - -Note that all classes that are inherited from ``TestCase`` class, are -automatically picked up by the test runner. - -``numpy.testing`` module provides also the following convenience -functions:: - - assert_equal(actual,desired,err_msg='',verbose=1) - assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=1) - assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=1) - assert_array_equal(x,y,err_msg='') - assert_array_almost_equal(x,y,decimal=6,err_msg='') - rand(*shape) # returns random array with a given shape - -To run all test scripts of the module ``xxx``, execute in Python: - - >>> import numpy - >>> numpy.xxx.test() - -To run only tests for ``xxx.yyy`` module, execute: - - >>> NumpyTest('xxx.yyy').test(level=1,verbosity=1) - Extra features in NumPy Distutils ''''''''''''''''''''''''''''''''' Added: trunk/doc/TESTS.txt =================================================================== --- trunk/doc/TESTS.txt 2008-09-02 06:59:43 UTC (rev 5741) +++ trunk/doc/TESTS.txt 2008-09-02 20:13:17 UTC (rev 5742) @@ -0,0 +1,52 @@ +The ``tests/`` directory +'''''''''''''''''''''''' + +Ideally, every Python code, extension module, or subpackage in Scipy +package directory should have the corresponding ``test_.py`` +file in ``tests/`` directory. This file should define classes +derived from the ``numpy.testing.TestCase`` class (or from +``unittest.TestCase``) and have names starting with ``test``. The methods +of these classes whose names contain ``test`` or start with ``bench`` are +automatically picked up by the test machinery. + +A minimal example of a ``test_yyy.py`` file that implements tests for +a NumPy package module ``numpy.xxx.yyy`` containing a function +``zzz()``, is shown below:: + + import sys + from numpy.testing import * + + # import xxx symbols + from numpy.xxx.yyy import zzz + + + class test_zzz(TestCase): + def test_simple(self, level=1): + assert zzz()=='Hello from zzz' + #... + + if __name__ == "__main__": + run_module_tests(file) + +Note that all classes that are inherited from ``TestCase`` class, are +automatically picked up by the test runner. + +``numpy.testing`` module provides also the following convenience +functions:: + + assert_equal(actual,desired,err_msg='',verbose=1) + assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=1) + assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=1) + assert_array_equal(x,y,err_msg='') + assert_array_almost_equal(x,y,decimal=6,err_msg='') + rand(*shape) # returns random array with a given shape + +To run all test scripts of the module ``xxx``, execute in Python: + + >>> import numpy + >>> numpy.xxx.test() + +To run only tests for ``xxx.yyy`` module, execute: + + >>> NumpyTest('xxx.yyy').test(level=1,verbosity=1) + From numpy-svn at scipy.org Tue Sep 2 16:32:52 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 2 Sep 2008 15:32:52 -0500 (CDT) Subject: [Numpy-svn] r5743 - in trunk: doc/numpybook doc/numpybook/comparison doc/numpybook/comparison/ctypes doc/numpybook/comparison/pyrex doc/numpybook/comparison/weave numpy/core numpy/core/code_generators numpy/distutils/command numpy/doc numpy/lib numpy/lib/tests numpy/ma numpy/testing tools/osxbuild tools/win32build Message-ID: <20080902203252.8A7AF39C18A@scipy.org> Author: jarrod.millman Date: 2008-09-02 15:32:38 -0500 (Tue, 02 Sep 2008) New Revision: 5743 Modified: trunk/doc/numpybook/comparison/ctypes/filter.py trunk/doc/numpybook/comparison/ctypes/interface.py trunk/doc/numpybook/comparison/pyrex/setup.py trunk/doc/numpybook/comparison/timing.py trunk/doc/numpybook/comparison/weave/filter.py trunk/doc/numpybook/comparison/weave/inline.py trunk/doc/numpybook/runcode.py trunk/numpy/core/code_generators/generate_umath.py trunk/numpy/core/memmap.py trunk/numpy/distutils/command/scons.py trunk/numpy/doc/subclassing.py trunk/numpy/lib/_datasource.py trunk/numpy/lib/scimath.py trunk/numpy/lib/tests/test_format.py trunk/numpy/lib/ufunclike.py trunk/numpy/ma/core.py trunk/numpy/testing/nosetester.py trunk/numpy/testing/parametric.py trunk/tools/osxbuild/build.py trunk/tools/osxbuild/install_and_test.py trunk/tools/win32build/build.py trunk/tools/win32build/prepare_bootstrap.py Log: reindenting prior to release Modified: trunk/doc/numpybook/comparison/ctypes/filter.py =================================================================== --- trunk/doc/numpybook/comparison/ctypes/filter.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/doc/numpybook/comparison/ctypes/filter.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -21,6 +21,3 @@ b = N.zeros_like(a) lib.dfilter2d(a, b, a.ctypes.strides, a.ctypes.shape) return b - - - Modified: trunk/doc/numpybook/comparison/ctypes/interface.py =================================================================== --- trunk/doc/numpybook/comparison/ctypes/interface.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/doc/numpybook/comparison/ctypes/interface.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -27,7 +27,7 @@ flags='aligned, contiguous,'\ 'writeable'), ctypes.POINTER(N.ctypeslib.c_intp), - ctypes.POINTER(N.ctypeslib.c_intp)] + ctypes.POINTER(N.ctypeslib.c_intp)] def select(dtype): if dtype.char in ['?bBhHf']: @@ -49,12 +49,9 @@ c = N.empty_like(a) func(a,b,c,a.size) return c - + def filter2d(a): a = N.require(a, float, ['ALIGNED']) b = N.zeros_like(a) lib.dfilter2d(a, b, a.ctypes.strides, a.ctypes.shape) return b - - - Modified: trunk/doc/numpybook/comparison/pyrex/setup.py =================================================================== --- trunk/doc/numpybook/comparison/pyrex/setup.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/doc/numpybook/comparison/pyrex/setup.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -16,8 +16,8 @@ include_dirs = [numpy.get_include()]) pyx_ext2 = Extension('blur', - ['blur.pyx'], - include_dirs = [numpy.get_include()]) + ['blur.pyx'], + include_dirs = [numpy.get_include()]) # Call the routine which does the real work Modified: trunk/doc/numpybook/comparison/timing.py =================================================================== --- trunk/doc/numpybook/comparison/timing.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/doc/numpybook/comparison/timing.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -51,13 +51,11 @@ path = sys.path for kind in ['f2py']:#['ctypes', 'pyrex', 'weave', 'f2py']: - res[kind] = [] - sys.path = ['/Users/oliphant/numpybook/%s' % (kind,)] + path - print sys.path - for n in N: - print "%s - %d" % (kind, n) - t = timeit.Timer(eval('%s_run'%kind), eval('%s_pre %% (%d,%d)'%(kind,n,n))) - mytime = min(t.repeat(3,100)) - res[kind].append(mytime) - - + res[kind] = [] + sys.path = ['/Users/oliphant/numpybook/%s' % (kind,)] + path + print sys.path + for n in N: + print "%s - %d" % (kind, n) + t = timeit.Timer(eval('%s_run'%kind), eval('%s_pre %% (%d,%d)'%(kind,n,n))) + mytime = min(t.repeat(3,100)) + res[kind].append(mytime) Modified: trunk/doc/numpybook/comparison/weave/filter.py =================================================================== --- trunk/doc/numpybook/comparison/weave/filter.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/doc/numpybook/comparison/weave/filter.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -8,11 +8,11 @@ for(i=1;i', 'exec') try: res = eval(tstr, dic) - sys.stdout = sys.__stdout__ + sys.stdout = sys.__stdout__ except SyntaxError: try: res = None @@ -42,7 +42,7 @@ res = tempstr.getvalue() + '\n' + repr(res) if res != '': print "\nOutput is" - print res, + print res, return res # now find the code in the code segment @@ -75,8 +75,8 @@ if line != 'dummy': outlines.append(line) return "\n\\newline \n".join(outlines), end - + def runpycode(lyxstr, name='MyCode'): schobj = re.compile(r"\\layout %s\s+>>> " % name) outstr = cStringIO.StringIO() @@ -85,7 +85,7 @@ for it in schobj.finditer(lyxstr): indx.extend([it.start(), it.end()]) num += 1 - + if num == 0: print "Nothing found for %s" % name return lyxstr @@ -103,14 +103,14 @@ for k in range(num): # first write everything up to the start of the code segment substr = lyxstr[start:indx[2*k]] - outstr.write(substr) + outstr.write(substr) if start > 0: mat = newre.search(substr) # if PYNEW found, then start a new namespace if mat: edic = {} exec 'from numpy import *' in edic - exec 'set_printoptions(linewidth=65)' in edic + exec 'set_printoptions(linewidth=65)' in edic # now find the code in the code segment # endoutput will contain the index just past any output # already present in the lyx string. Modified: trunk/numpy/core/code_generators/generate_umath.py =================================================================== --- trunk/numpy/core/code_generators/generate_umath.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/numpy/core/code_generators/generate_umath.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -673,10 +673,10 @@ mlist = [] docstring = textwrap.dedent(uf.docstring).strip() docstring = docstring.encode('string-escape').replace(r'"', r'\"') - # Split the docstring because some compilers (like MS) do not like big - # string literal in C code. We split at endlines because textwrap.wrap - # do not play well with \n - docstring = '\\n\"\"'.join(docstring.split(r"\n")) + # Split the docstring because some compilers (like MS) do not like big + # string literal in C code. We split at endlines because textwrap.wrap + # do not play well with \n + docstring = '\\n\"\"'.join(docstring.split(r"\n")) mlist.append(\ r"""f = PyUFunc_FromFuncAndData(%s_functions, %s_data, %s_signatures, %d, %d, %d, %s, "%s", Modified: trunk/numpy/core/memmap.py =================================================================== --- trunk/numpy/core/memmap.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/numpy/core/memmap.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -74,7 +74,7 @@ Given a memmap ``fp``, ``isinstance(fp, numpy.ndarray)`` returns ``True``. - Notes + Notes ----- Memory-mapped arrays use the the Python memory-map object which Modified: trunk/numpy/distutils/command/scons.py =================================================================== --- trunk/numpy/distutils/command/scons.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/numpy/distutils/command/scons.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -287,11 +287,11 @@ self.post_hooks = [] self.pkg_names = [] - # To avoid trouble, just don't do anything if no sconscripts are used. - # This is useful when for example f2py uses numpy.distutils, because - # f2py does not pass compiler information to scons command, and the - # compilation setup below can crash in some situation. - if len(self.sconscripts) > 0: + # To avoid trouble, just don't do anything if no sconscripts are used. + # This is useful when for example f2py uses numpy.distutils, because + # f2py does not pass compiler information to scons command, and the + # compilation setup below can crash in some situation. + if len(self.sconscripts) > 0: # Try to get the same compiler than the ones used by distutils: this is # non trivial because distutils and scons have totally different # conventions on this one (distutils uses PATH from user's environment, Modified: trunk/numpy/doc/subclassing.py =================================================================== --- trunk/numpy/doc/subclassing.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/numpy/doc/subclassing.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -7,7 +7,7 @@ ------- This page is based with thanks on the wiki page on subclassing by Pierre -Gerard-Marchant - http://www.scipy.org/Subclasses. +Gerard-Marchant - http://www.scipy.org/Subclasses. Introduction ------------ @@ -40,21 +40,21 @@ To allow subclassing, and views of subclasses, ndarray uses the ndarray ``__new__`` method for the main work of object initialization, -rather then the more usual ``__init__`` method. +rather then the more usual ``__init__`` method. ``__new__`` and ``__init__`` ============================ ``__new__`` is a standard python method, and, if present, is called before ``__init__`` when we create a class instance. Consider the -following:: +following:: class C(object): def __new__(cls, *args): - print 'Args in __new__:', args - return object.__new__(cls, *args) + print 'Args in __new__:', args + return object.__new__(cls, *args) def __init__(self, *args): - print 'Args in __init__:', args + print 'Args in __init__:', args C('hello') @@ -75,7 +75,7 @@ As you can see, the object can be initialized in the ``__new__`` method or the ``__init__`` method, or both, and in fact ndarray does not have an ``__init__`` method, because all the initialization is -done in the ``__new__`` method. +done in the ``__new__`` method. Why use ``__new__`` rather than just the usual ``__init__``? Because in some cases, as for ndarray, we want to be able to return an object @@ -83,21 +83,21 @@ class C(object): def __new__(cls, *args): - print 'cls is:', cls - print 'Args in __new__:', args - return object.__new__(cls, *args) + print 'cls is:', cls + print 'Args in __new__:', args + return object.__new__(cls, *args) def __init__(self, *args): - print 'self is :', self - print 'Args in __init__:', args + print 'self is :', self + print 'Args in __init__:', args class D(C): def __new__(cls, *args): - print 'D cls is:', cls - print 'D args in __new__:', args - return C.__new__(C, *args) + print 'D cls is:', cls + print 'D args in __new__:', args + return C.__new__(C, *args) def __init__(self, *args): - print 'D self is :', self - print 'D args in __init__:', args + print 'D self is :', self + print 'D args in __init__:', args D('hello') @@ -131,7 +131,7 @@ ``__new__`` method knows nothing of what we have done in our own ``__new__`` method in order to set attributes, and so on. (Aside - why not call ``obj = subdtype.__new__(...`` then? Because we may not -have a ``__new__`` method with the same call signature). +have a ``__new__`` method with the same call signature). So, when creating a new view object of our subclass, we need to be able to set any extra attributes from the original object of our @@ -153,21 +153,21 @@ class InfoArray(np.ndarray): def __new__(subtype, shape, dtype=float, buffer=None, offset=0, - strides=None, order=None, info=None): - # Create the ndarray instance of our type, given the usual - # input arguments. This will call the standard ndarray - # constructor, but return an object of our type - obj = np.ndarray.__new__(subtype, shape, dtype, buffer, offset, strides, - order) - # add the new attribute to the created instance - obj.info = info - # Finally, we must return the newly created object: - return obj + strides=None, order=None, info=None): + # Create the ndarray instance of our type, given the usual + # input arguments. This will call the standard ndarray + # constructor, but return an object of our type + obj = np.ndarray.__new__(subtype, shape, dtype, buffer, offset, strides, + order) + # add the new attribute to the created instance + obj.info = info + # Finally, we must return the newly created object: + return obj def __array_finalize__(self,obj): - # reset the attribute from passed original object - self.info = getattr(obj, 'info', None) - # We do not need to return anything + # reset the attribute from passed original object + self.info = getattr(obj, 'info', None) + # We do not need to return anything obj = InfoArray(shape=(3,), info='information') print type(obj) @@ -200,18 +200,18 @@ class RealisticInfoArray(np.ndarray): def __new__(cls, input_array, info=None): - # Input array is an already formed ndarray instance - # We first cast to be our class type - obj = np.asarray(input_array).view(cls) - # add the new attribute to the created instance - obj.info = info - # Finally, we must return the newly created object: - return obj + # Input array is an already formed ndarray instance + # We first cast to be our class type + obj = np.asarray(input_array).view(cls) + # add the new attribute to the created instance + obj.info = info + # Finally, we must return the newly created object: + return obj def __array_finalize__(self,obj): - # reset the attribute from passed original object - self.info = getattr(obj, 'info', None) - # We do not need to return anything + # reset the attribute from passed original object + self.info = getattr(obj, 'info', None) + # We do not need to return anything arr = np.arange(5) obj = RealisticInfoArray(arr, info='information') Modified: trunk/numpy/lib/_datasource.py =================================================================== --- trunk/numpy/lib/_datasource.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/numpy/lib/_datasource.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -38,7 +38,7 @@ from shutil import rmtree # Using a class instead of a module-level dictionary -# to reduce the inital 'import numpy' overhead by +# to reduce the inital 'import numpy' overhead by # deferring the import of bz2 and gzip until needed # TODO: .zip support, .tar support? @@ -197,7 +197,7 @@ def _isurl(self, path): """Test if path is a net location. Tests the scheme and netloc.""" - + # We do this here to reduce the 'import numpy' initial import time. from urlparse import urlparse Modified: trunk/numpy/lib/scimath.py =================================================================== --- trunk/numpy/lib/scimath.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/numpy/lib/scimath.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -198,15 +198,15 @@ As the numpy.sqrt, this returns the principal square root of x, which is what most people mean when they use square root; the principal square root - of x is not any number z such as z^2 = x. + of x is not any number z such as z^2 = x. For positive numbers, the principal square root is defined as the positive - number z such as z^2 = x. + number z such as z^2 = x. The principal square root of -1 is i, the principal square root of any negative number -x is defined a i * sqrt(x). For any non zero complex number, it is defined by using the following branch cut: x = r e^(i t) with - r > 0 and -pi < t <= pi. The principal square root is then + r > 0 and -pi < t <= pi. The principal square root is then sqrt(r) e^(i t/2). """ x = _fix_real_lt_zero(x) Modified: trunk/numpy/lib/tests/test_format.py =================================================================== --- trunk/numpy/lib/tests/test_format.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/numpy/lib/tests/test_format.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -434,13 +434,13 @@ 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() @@ -449,7 +449,7 @@ 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 Modified: trunk/numpy/lib/ufunclike.py =================================================================== --- trunk/numpy/lib/ufunclike.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/numpy/lib/ufunclike.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -10,12 +10,12 @@ """ Round x to nearest integer towards zero. """ x = nx.asanyarray(x) - if y is None: + if y is None: y = nx.zeros_like(x) y1 = nx.floor(x) y2 = nx.ceil(x) y[...] = nx.where(x >= 0, y1, y2) - return y + return y def isposinf(x, y=None): """ Modified: trunk/numpy/ma/core.py =================================================================== --- trunk/numpy/ma/core.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/numpy/ma/core.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -86,7 +86,7 @@ return newdoc = """ %s - + Notes ----- %s @@ -896,7 +896,7 @@ """ cond = make_mask(condition) a = np.array(a, copy=copy, subok=True) - + (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistant shape between the condition and the input"\ @@ -3865,7 +3865,7 @@ if len(fb.shape) == 0: fb.shape = (1,) return np.inner(fa, fb).view(MaskedArray) -inner.__doc__ = doc_note(np.inner.__doc__, +inner.__doc__ = doc_note(np.inner.__doc__, "Masked values are replaced by 0.") innerproduct = inner Modified: trunk/numpy/testing/nosetester.py =================================================================== --- trunk/numpy/testing/nosetester.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/numpy/testing/nosetester.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -164,8 +164,8 @@ pyversion = sys.version.replace('\n','') print "Python version %s" % pyversion print "nose version %d.%d.%d" % nose.__versioninfo__ - + def test(self, label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False, **kwargs): ''' Run tests for module using nose Modified: trunk/numpy/testing/parametric.py =================================================================== --- trunk/numpy/testing/parametric.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/numpy/testing/parametric.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -61,9 +61,9 @@ _shareParTestPrefix = 'testsp' def __init__(self, methodName = 'runTest'): - warnings.warn("ParametricTestCase will be removed in the next NumPy " + warnings.warn("ParametricTestCase will be removed in the next NumPy " "release", DeprecationWarning) - unittest.TestCase.__init__(self, methodName) + unittest.TestCase.__init__(self, methodName) def exec_test(self,test,args,result): """Execute a single test. Returns a success boolean""" Modified: trunk/tools/osxbuild/build.py =================================================================== --- trunk/tools/osxbuild/build.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/tools/osxbuild/build.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -36,7 +36,7 @@ cmd = 'sudo chown -R %s %s' % (getuser(), DIST_DIR) shellcmd(cmd) shutil.rmtree(DIST_DIR) - + def build_dist(): print 'Building distribution... (using sudo)' cmd = 'sudo python setupegg.py bdist_mpkg' @@ -67,7 +67,7 @@ print 'Reverting README.txt...' cmd = 'svn revert %s' % DEV_README shellcmd(cmd) - + def shellcmd(cmd, verbose=True): """Call a shell command.""" if verbose: @@ -80,7 +80,7 @@ %s """ % str(err) raise Exception(msg) - + def build(): # update end-user documentation copy_readme() @@ -99,6 +99,6 @@ os.chdir(cwd) # restore developer documentation revert_readme() - + if __name__ == '__main__': build() Modified: trunk/tools/osxbuild/install_and_test.py =================================================================== --- trunk/tools/osxbuild/install_and_test.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/tools/osxbuild/install_and_test.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -14,7 +14,7 @@ """Add color to this print output.""" clrmsg = clrgreen + msg + clrnull print clrmsg - + distdir = os.path.join(SRC_DIR, DIST_DIR) # Find the package and build abspath to it Modified: trunk/tools/win32build/build.py =================================================================== --- trunk/tools/win32build/build.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/tools/win32build/build.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -80,7 +80,7 @@ if not os.path.exists("binaries"): os.makedirs("binaries") - shutil.move(os.path.join('dist', get_windist_exec(pyver)), + shutil.move(os.path.join('dist', get_windist_exec(pyver)), os.path.join("binaries", get_binary_name(arch))) def get_numpy_version(): @@ -110,7 +110,7 @@ if __name__ == '__main__': from optparse import OptionParser parser = OptionParser() - parser.add_option("-a", "--arch", dest="arch", + parser.add_option("-a", "--arch", dest="arch", help = "Architecture to build (sse2, sse3, nosse, etc...)") parser.add_option("-p", "--pyver", dest="pyver", help = "Python version (2.4, 2.5, etc...)") Modified: trunk/tools/win32build/prepare_bootstrap.py =================================================================== --- trunk/tools/win32build/prepare_bootstrap.py 2008-09-02 20:13:17 UTC (rev 5742) +++ trunk/tools/win32build/prepare_bootstrap.py 2008-09-02 20:32:38 UTC (rev 5743) @@ -79,7 +79,7 @@ version = subprocess.Popen(['python', '-c', 'import __builtin__; __builtin__.__NUMPY_SETUP__ = True; from numpy.version import version;print version'], stdout = subprocess.PIPE).communicate()[0] version = version.strip() if 'dev' in version: - out = subprocess.Popen(['svn', 'info'], stdout = subprocess.PIPE).communicate()[0] + out = subprocess.Popen(['svn', 'info'], stdout = subprocess.PIPE).communicate()[0] r = re.compile('Revision: ([0-9]+)') svnver = None for line in out.split('\n'): From numpy-svn at scipy.org Tue Sep 2 19:50:18 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 2 Sep 2008 18:50:18 -0500 (CDT) Subject: [Numpy-svn] r5744 - branches Message-ID: <20080902235018.EC1D939C072@scipy.org> Author: jarrod.millman Date: 2008-09-02 18:50:12 -0500 (Tue, 02 Sep 2008) New Revision: 5744 Added: branches/1.2.x/ Log: branching for 1.2 (r5743) Copied: branches/1.2.x (from rev 5743, trunk) From numpy-svn at scipy.org Tue Sep 2 19:52:38 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 2 Sep 2008 18:52:38 -0500 (CDT) Subject: [Numpy-svn] r5745 - trunk/numpy Message-ID: <20080902235238.DED9439C072@scipy.org> Author: jarrod.millman Date: 2008-09-02 18:52:37 -0500 (Tue, 02 Sep 2008) New Revision: 5745 Modified: trunk/numpy/version.py Log: trunk is open for 1.3 development Modified: trunk/numpy/version.py =================================================================== --- trunk/numpy/version.py 2008-09-02 23:50:12 UTC (rev 5744) +++ trunk/numpy/version.py 2008-09-02 23:52:37 UTC (rev 5745) @@ -1,4 +1,4 @@ -version='1.2.0' +version='1.3.0' release=False if not release: From numpy-svn at scipy.org Tue Sep 2 20:00:55 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 2 Sep 2008 19:00:55 -0500 (CDT) Subject: [Numpy-svn] r5746 - tags Message-ID: <20080903000055.C918639C072@scipy.org> Author: jarrod.millman Date: 2008-09-02 19:00:52 -0500 (Tue, 02 Sep 2008) New Revision: 5746 Added: tags/1.2.0rc1/ Log: tag for release candidate Copied: tags/1.2.0rc1 (from rev 5745, branches/1.2.x) From numpy-svn at scipy.org Tue Sep 2 20:03:06 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 2 Sep 2008 19:03:06 -0500 (CDT) Subject: [Numpy-svn] r5747 - tags/1.2.0rc1/numpy Message-ID: <20080903000306.7267539C072@scipy.org> Author: jarrod.millman Date: 2008-09-02 19:03:04 -0500 (Tue, 02 Sep 2008) New Revision: 5747 Modified: tags/1.2.0rc1/numpy/version.py Log: updating version info Modified: tags/1.2.0rc1/numpy/version.py =================================================================== --- tags/1.2.0rc1/numpy/version.py 2008-09-03 00:00:52 UTC (rev 5746) +++ tags/1.2.0rc1/numpy/version.py 2008-09-03 00:03:04 UTC (rev 5747) @@ -1,5 +1,5 @@ -version='1.2.0' -release=False +version='1.2.0rc1' +release=True if not release: version += '.dev' From numpy-svn at scipy.org Wed Sep 3 01:10:58 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 3 Sep 2008 00:10:58 -0500 (CDT) Subject: [Numpy-svn] r5748 - trunk/doc Message-ID: <20080903051058.32FBA39C072@scipy.org> Author: alan.mcintyre Date: 2008-09-03 00:10:39 -0500 (Wed, 03 Sep 2008) New Revision: 5748 Modified: trunk/doc/DISTUTILS.txt trunk/doc/TESTS.txt Log: Fix __init__.py boilerplate example in DISTUTILS.txt, and moved content from SciPy wiki entry on testing guidelines to TESTS.txt. Modified: trunk/doc/DISTUTILS.txt =================================================================== --- trunk/doc/DISTUTILS.txt 2008-09-03 00:03:04 UTC (rev 5747) +++ trunk/doc/DISTUTILS.txt 2008-09-03 05:10:39 UTC (rev 5748) @@ -450,8 +450,9 @@ from info import __doc__ ... - from numpy.testing import NumpyTest - test = NumpyTest().test + from numpy.testing import Tester + test = Tester().test + bench = Tester().bench Extra features in NumPy Distutils ''''''''''''''''''''''''''''''''' Modified: trunk/doc/TESTS.txt =================================================================== --- trunk/doc/TESTS.txt 2008-09-03 00:03:04 UTC (rev 5747) +++ trunk/doc/TESTS.txt 2008-09-03 05:10:39 UTC (rev 5748) @@ -1,52 +1,202 @@ -The ``tests/`` directory -'''''''''''''''''''''''' +[[PageOutline]] += Introduction = +!SciPy uses the [http://www.somethingaboutorange.com/mrl/projects/nose Nose testing system], with some minor convenience features added. Nose is an extension of the unit testing framework offered by [http://docs.python.org/lib/module-unittest.html unittest.py]. Our goal is that every module and package in !SciPy should have a thorough set of unit tests. These tests should exercise the full functionality of a given routine as well as its robustness to erroneous or unexpected input arguments. Long experience has shown that by far the best time to write the tests is before you write or change the code - this is [http://en.wikipedia.org/wiki/Test-driven_development test driven development]. The arguments for this can sound rather abstract, but we can assure you that you will find that writing the tests first leads to more robust and better designed code. Well-designed tests with good coverage make an enormous difference to the ease of refactoring. Whenever a new bug is found in a routine, you should write a new test for that specific case and add it to the test suite to prevent that bug from creeping back in unnoticed. -Ideally, every Python code, extension module, or subpackage in Scipy -package directory should have the corresponding ``test_.py`` -file in ``tests/`` directory. This file should define classes -derived from the ``numpy.testing.TestCase`` class (or from -``unittest.TestCase``) and have names starting with ``test``. The methods -of these classes whose names contain ``test`` or start with ``bench`` are -automatically picked up by the test machinery. +To run !SciPy's full test suite, use the following: +{{{ +>>> import scipy +>>> scipy.test() +}}} -A minimal example of a ``test_yyy.py`` file that implements tests for -a NumPy package module ``numpy.xxx.yyy`` containing a function -``zzz()``, is shown below:: +!SciPy uses the testing framework from !NumPy (specifically ``numpy.testing``), so all the !SciPy examples shown here are also applicable to !NumPy. So !NumPy's full test suite can be run as follows: +{{{ +>>> import numpy +>>> numpy.test() +}}} - import sys - from numpy.testing import * +The test method may take two or more arguments; the first is a string label specifying what should be tested and the second is an integer giving the level of output verbosity. See the docstring for numpy.test for details. The default value for the label is 'fast' - which will run the standard tests. The string 'full' will run the full battery of tests, including those identified as being slow to run. If the verbosity is 1 or less, the tests will just show information messages about the tests that are run; but if it is greater than 1, then the tests will also provide warnings on missing tests. So if you want to run every test and get messages about which modules don't have tests: +{{{ +>>> scipy.test(label='full', verbosity=2) # or +>>> scipy.test('full', 2) +}}} +Finally, if you are only interested in testing a subset of !SciPy, for example, the {{{integrate}}} module, use the following: +{{{ +>>> scipy.integrate.test() +}}} +The rest of this page will give you a basic idea of how to add unit tests to modules in !SciPy. It is extremely important for us to have extensive unit testing since this code is going to be used by scientists and researchers and is being developed by a large number of people spread across the world. So, if you are writing a package that you'd like to become part of !SciPy, please write the tests as you develop the package. Also since much of !SciPy is legacy code that was originally written without unit tests, there are still several modules that don't have tests yet. Please feel free to choose one of these modules to develop test for either after or even as you read through this introduction. - # import xxx symbols - from numpy.xxx.yyy import zzz +== Writing your own tests == +Every Python module, extension module, or subpackage in the !SciPy package directory should have a corresponding {{{test_.py}}} file. The nose framework picks up tests by first looking for any functions in the file that have test-related names (see below), or classes that inherit from {{{unittest.TestCase}}} (which is also made available as {{{numpy.testing.TestCase}}}. Any methods of these classes, that also have test-related names, are considered tests. A test-related name is simply a function or method name containing 'test'. +=== {{{test_yyy.py}}} === +Suppose you have a !SciPy module {{{scipy/xxx/yyy.py}}} containing a function {{{zzz()}}}. To test this you would start by creating a test module called {{{test_yyy.py}}}. There are several different ways to implement tests using the nose / !SciPy system. There is the standard unittest way and the nose test function way. - class test_zzz(TestCase): - def test_simple(self, level=1): - assert zzz()=='Hello from zzz' - #... +==== Standard unit test classes ==== - if __name__ == "__main__": - run_module_tests(file) +You can use the traditional unittest system by making your test file include a class that tests {{{zzz()}}}. The test class inherits from the !TestCase class, and has test methods that test various aspects of {{{zzz()}}}. Within these test methods, {{{assert()}}} is used to test whether some case is true. If the assert fails, the test fails. The line {{{nose.run(...)}}} function actually runs the test suite. A minimal example of a {{{test_yyy.py}}} file that implements tests for a Scipy package module {{{scipy.xxx.yyy}}}, is shown below: +{{{ +from numpy.testing import * -Note that all classes that are inherited from ``TestCase`` class, are -automatically picked up by the test runner. +# import xxx symbols +from scipy.xxx.yyy import zzz -``numpy.testing`` module provides also the following convenience -functions:: +class test_zzz(TestCase): + def test_simple(self): + assert zzz()=='Hello from zzz' + #... - assert_equal(actual,desired,err_msg='',verbose=1) - assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=1) - assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=1) - assert_array_equal(x,y,err_msg='') - assert_array_almost_equal(x,y,decimal=6,err_msg='') - rand(*shape) # returns random array with a given shape +if __name__ == "__main__": + run_module_suite() +}}} -To run all test scripts of the module ``xxx``, execute in Python: +Note that all classes that are inherited from {{{TestCase}}} class, are picked up by the test runner. For more detailed information on defining test classes see the official documentation for the [http://docs.python.org/lib/module-unittest.html Python Unit testing framework]. - >>> import numpy - >>> numpy.xxx.test() +==== Using test functions with nose ==== -To run only tests for ``xxx.yyy`` module, execute: +This is as simple as making a function or functions with names including 'test': - >>> NumpyTest('xxx.yyy').test(level=1,verbosity=1) +{{{ +from numpy.testing import * +# import xxx symbols +from scipy.xxx.yyy import zzz + +def test_simple(self): + assert zzz()=='Hello from zzz' + + +if __name__ == "__main__": + run_module_suite() +}}} + +You can mix nose test functions and !TestCase classes in a single test file. + +==== Labeling tests with nose ==== + +Unlabeled tests like the ones above are run in the default {{{scipy.test()}}} run. If you want to label your test as slow - and therefore reserved for a full {{{scipy.test(label='full')}}} run, you can label it with a nose decorator: + +{{{ +# numpy.testing module includes 'import decorators as dec' +from numpy.testing import * + at dec.slow +def test_big(self): + print 'Big, slow test' +}}} + +Similarly for methods: + +{{{ +class test_zzz(TestCase): + @dec.slow + def test_simple(self): + assert zzz()=='Hello from zzz' +}}} + +==== Easier setup and teardown functions / methods ==== + +Nose looks for module level setup and teardown functions by name; thus: + +{{{ +def setup(): + """Module-level setup""" + print 'doing setup' + +def teardown(): + """Module-level teardown""" + print 'doing teardown' +}}} + +You can add setup and teardown functions to functions and methods with nose decorators: + +{{{ +import nose +from numpy.testing import * +def setup_func(): + """A trivial setup function.""" + global helpful_variable + helpful_variable = 'pleasant' + print "In setup_func" + +def teardown_func(): + """A trivial teardown function.""" + global helpful_variable + del helpful_variable + print "In teardown_func" + + at nose.with_setup(setup_func, teardown_func) +def test_with_extras(): + """This test uses the setup/teardown functions.""" + global helpful_variable + print " In test_with_extras" + print " Helpful is %s" % helpful_variable +}}} + +==== Parametric tests ==== + +One very nice feature of nose is allowing easy testing across a range of parameters - a nasty problem for standard unit tests. It does this with test generators: + +{{{ +def check_even(n, nn): + """A check function to be used in a test generator.""" + assert n % 2 == 0 or nn % 2 == 0 + +def test_evens(): + for i in range(0,4,2): + yield check_even, i, i*3 +}}} + +Note that 'check_even' is not itself a test (no 'test' in the name), but 'test_evens' is a generator that returns a series of tests, using 'check_even', across a range of inputs. Nice. + +=== {{{tests/}}} === +Rather than keeping the code and the tests in the same directory, we put all the tests for a given subpackage in a {{{tests/}}} subdirectory. For our example, if it doesn't all ready exist you will need to create a {{{tests/}}} directory in {{{scipy/xxx/}}}. So the path for {{{test_yyy.py}}} is {{{scipy/xxx/tests/test_yyy.py}}}. + +Once the {{{scipy/xxx/tests/test_yyy.py}}} is written, its possible to run the tests by going to the {{{tests/}}} directory and typing: +{{{ +python test_yyy.py +}}} +Or if you add {{{scipy/xxx/tests/}}} to the Python path, you could run the tests interactively in the interpreter like this: +{{{ +>>> import test_yyy +>>> test_yyy.test() +}}} + +=== {{{__init__.py}}} and {{{setup.py}}} === +Usually however, adding the {{{tests/}}} directory to the python path isn't desirable. Instead it would better to invoke the test straight from the module {{{xxx}}}. To this end, simply place the following lines at the end of your package's {{{__init__.py}}} file: +{{{ +... +def test(level=1, verbosity=1): + from numpy.testing import Tester + return Tester().test(level, verbosity) +}}} +You will also need to add the tests directory in the configuration section of your setup.py: +{{{ +... +def configuration(parent_package='', top_path=None): + ... + config.add_data_dir('tests') + return config +... +}}} +Now you can do the following to test your module: +{{{ +>>> import scipy +>>> scipy.xxx.test() +}}} + +Also, when invoking the entire !SciPy test suite, your tests will be found and run: +{{{ +>>> import scipy +>>> scipy.test() +# your tests are included and run automatically! +}}} + + + + + + + + + + + From numpy-svn at scipy.org Wed Sep 3 02:11:32 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 3 Sep 2008 01:11:32 -0500 (CDT) Subject: [Numpy-svn] r5749 - trunk/doc Message-ID: <20080903061132.6067539C021@scipy.org> Author: alan.mcintyre Date: 2008-09-03 01:11:28 -0500 (Wed, 03 Sep 2008) New Revision: 5749 Modified: trunk/doc/DISTUTILS.txt trunk/doc/TESTS.txt Log: Updated TESTS.txt to actually be ReST. Capitalization nitpickery in DISTUTILS.txt: 'Scipy' -> 'SciPy' Modified: trunk/doc/DISTUTILS.txt =================================================================== --- trunk/doc/DISTUTILS.txt 2008-09-03 05:10:39 UTC (rev 5748) +++ trunk/doc/DISTUTILS.txt 2008-09-03 06:11:28 UTC (rev 5749) @@ -58,7 +58,7 @@ SciPy pure Python package example --------------------------------- -Below is an example of a minimal ``setup.py`` file for a pure Scipy package:: +Below is an example of a minimal ``setup.py`` file for a pure SciPy package:: #!/usr/bin/env python def configuration(parent_package='',top_path=None): @@ -399,7 +399,7 @@ The ``info.py`` file '''''''''''''''''''' -Scipy package import hooks assume that each package contains a +SciPy package import hooks assume that each package contains a ``info.py`` file. This file contains overall documentation about the package and variables defining the order of package imports, dependency relations between packages, etc. @@ -436,8 +436,8 @@ To speed up the import time and minimize memory usage, numpy uses ``ppimport`` hooks to transparently postpone importing large modules, -which might not be used during the Scipy session. In order to -have access to the documentation of all Scipy packages, including +which might not be used during the SciPy session. In order to +have access to the documentation of all SciPy packages, including postponed packages, the docstring from ``info.py`` is imported into ``__init__.py``. Modified: trunk/doc/TESTS.txt =================================================================== --- trunk/doc/TESTS.txt 2008-09-03 05:10:39 UTC (rev 5748) +++ trunk/doc/TESTS.txt 2008-09-03 06:11:28 UTC (rev 5749) @@ -1,202 +1,208 @@ -[[PageOutline]] -= Introduction = -!SciPy uses the [http://www.somethingaboutorange.com/mrl/projects/nose Nose testing system], with some minor convenience features added. Nose is an extension of the unit testing framework offered by [http://docs.python.org/lib/module-unittest.html unittest.py]. Our goal is that every module and package in !SciPy should have a thorough set of unit tests. These tests should exercise the full functionality of a given routine as well as its robustness to erroneous or unexpected input arguments. Long experience has shown that by far the best time to write the tests is before you write or change the code - this is [http://en.wikipedia.org/wiki/Test-driven_development test driven development]. The arguments for this can sound rather abstract, but we can assure you that you will find that writing the tests first leads to more robust and better designed code. Well-designed tests with good coverage make an enormous difference to the ease of refactoring. Whenever a new bug is found in a routine, you should write a new test for that specific case and add it to the test suite to prevent that bug from creeping back in unnoticed. +.. -*- rest -*- -To run !SciPy's full test suite, use the following: -{{{ ->>> import scipy ->>> scipy.test() -}}} +NumPy/SciPy Testing Guidelines +============================== -!SciPy uses the testing framework from !NumPy (specifically ``numpy.testing``), so all the !SciPy examples shown here are also applicable to !NumPy. So !NumPy's full test suite can be run as follows: -{{{ ->>> import numpy ->>> numpy.test() -}}} +.. contents:: -The test method may take two or more arguments; the first is a string label specifying what should be tested and the second is an integer giving the level of output verbosity. See the docstring for numpy.test for details. The default value for the label is 'fast' - which will run the standard tests. The string 'full' will run the full battery of tests, including those identified as being slow to run. If the verbosity is 1 or less, the tests will just show information messages about the tests that are run; but if it is greater than 1, then the tests will also provide warnings on missing tests. So if you want to run every test and get messages about which modules don't have tests: -{{{ ->>> scipy.test(label='full', verbosity=2) # or ->>> scipy.test('full', 2) -}}} -Finally, if you are only interested in testing a subset of !SciPy, for example, the {{{integrate}}} module, use the following: -{{{ +Introduction +'''''''''''' + +SciPy uses the `Nose testing system `__, with some minor convenience features added. Nose is an extension of the unit testing framework offered by `unittest.py `__. Our goal is that every module and package in SciPy should have a thorough set of unit tests. These tests should exercise the full functionality of a given routine as well as its robustness to erroneous or unexpected input arguments. Long experience has shown that by far the best time to write the tests is before you write or change the code - this is `test-driven development `__. The arguments for this can sound rather abstract, but we can assure you that you will find that writing the tests first leads to more robust and better designed code. Well-designed tests with good coverage make an enormous difference to the ease of refactoring. Whenever a new bug is found in a routine, you should write a new test for that specific case and add it to the test suite to prevent that bug from creeping back in unnoticed. + +To run SciPy's full test suite, use the following:: + + >>> import scipy + >>> scipy.test() + +SciPy uses the testing framework from NumPy (specifically ``numpy.testing``), so all the SciPy examples shown here are also applicable to NumPy. So NumPy's full test suite can be run as follows:: + + >>> import numpy + >>> numpy.test() + + +The test method may take two or more arguments; the first is a string label specifying what should be tested and the second is an integer giving the level of output verbosity. See the docstring for numpy.test for details. The default value for the label is 'fast' - which will run the standard tests. The string 'full' will run the full battery of tests, including those identified as being slow to run. If the verbosity is 1 or less, the tests will just show information messages about the tests that are run; but if it is greater than 1, then the tests will also provide warnings on missing tests. So if you want to run every test and get messages about which modules don't have tests:: + + >>> scipy.test(label='full', verbosity=2) # or + >>> scipy.test('full', 2) + +Finally, if you are only interested in testing a subset of SciPy, for example, the ``integrate`` module, use the following:: + >>> scipy.integrate.test() -}}} -The rest of this page will give you a basic idea of how to add unit tests to modules in !SciPy. It is extremely important for us to have extensive unit testing since this code is going to be used by scientists and researchers and is being developed by a large number of people spread across the world. So, if you are writing a package that you'd like to become part of !SciPy, please write the tests as you develop the package. Also since much of !SciPy is legacy code that was originally written without unit tests, there are still several modules that don't have tests yet. Please feel free to choose one of these modules to develop test for either after or even as you read through this introduction. -== Writing your own tests == -Every Python module, extension module, or subpackage in the !SciPy package directory should have a corresponding {{{test_.py}}} file. The nose framework picks up tests by first looking for any functions in the file that have test-related names (see below), or classes that inherit from {{{unittest.TestCase}}} (which is also made available as {{{numpy.testing.TestCase}}}. Any methods of these classes, that also have test-related names, are considered tests. A test-related name is simply a function or method name containing 'test'. +The rest of this page will give you a basic idea of how to add unit tests to modules in SciPy. It is extremely important for us to have extensive unit testing since this code is going to be used by scientists and researchers and is being developed by a large number of people spread across the world. So, if you are writing a package that you'd like to become part of SciPy, please write the tests as you develop the package. Also since much of SciPy is legacy code that was originally written without unit tests, there are still several modules that don't have tests yet. Please feel free to choose one of these modules to develop test for either after or even as you read through this introduction. -=== {{{test_yyy.py}}} === -Suppose you have a !SciPy module {{{scipy/xxx/yyy.py}}} containing a function {{{zzz()}}}. To test this you would start by creating a test module called {{{test_yyy.py}}}. There are several different ways to implement tests using the nose / !SciPy system. There is the standard unittest way and the nose test function way. +Writing your own tests +'''''''''''''''''''''' -==== Standard unit test classes ==== +Every Python module, extension module, or subpackage in the SciPy package directory should have a corresponding ``test_.py`` file. The nose framework picks up tests by first looking for any functions in the file that have test-related names (see below), or classes that inherit from ``unittest.TestCase`` (which is also made available as ``numpy.testing.TestCase``. Any methods of these classes, that also have test-related names, are considered tests. A test-related name is simply a function or method name containing 'test'. -You can use the traditional unittest system by making your test file include a class that tests {{{zzz()}}}. The test class inherits from the !TestCase class, and has test methods that test various aspects of {{{zzz()}}}. Within these test methods, {{{assert()}}} is used to test whether some case is true. If the assert fails, the test fails. The line {{{nose.run(...)}}} function actually runs the test suite. A minimal example of a {{{test_yyy.py}}} file that implements tests for a Scipy package module {{{scipy.xxx.yyy}}}, is shown below: -{{{ -from numpy.testing import * +Suppose you have a SciPy module ``scipy/xxx/yyy.py`` containing a function ``zzz()``. To test this you would start by creating a test module called ``test_yyy.py``. There are several different ways to implement tests using the nose / SciPy system. There is the standard unittest way and the nose test function way. -# import xxx symbols -from scipy.xxx.yyy import zzz +Standard unit test classes +-------------------------- -class test_zzz(TestCase): - def test_simple(self): - assert zzz()=='Hello from zzz' - #... +You can use the traditional unittest system by making your test file include a class that tests ``zzz()``. The test class inherits from the TestCase class, and has test methods that test various aspects of ``zzz()``. Within these test methods, ``assert()`` is used to test whether some case is true. If the assert fails, the test fails. The line ``nose.run(...)`` function actually runs the test suite. A minimal example of a ``test_yyy.py`` file that implements tests for a Scipy package module ``scipy.xxx.yyy``, is shown below:: -if __name__ == "__main__": - run_module_suite() -}}} + from numpy.testing import * -Note that all classes that are inherited from {{{TestCase}}} class, are picked up by the test runner. For more detailed information on defining test classes see the official documentation for the [http://docs.python.org/lib/module-unittest.html Python Unit testing framework]. + # import xxx symbols + from scipy.xxx.yyy import zzz -==== Using test functions with nose ==== + class test_zzz(TestCase): + def test_simple(self): + assert zzz()=='Hello from zzz' + #... -This is as simple as making a function or functions with names including 'test': + if __name__ == "__main__": + run_module_suite() -{{{ -from numpy.testing import * -# import xxx symbols -from scipy.xxx.yyy import zzz +Note that all classes that are inherited from ``TestCase`` class, are picked up by the test runner. For more detailed information on defining test classes see the official documentation for the [http://docs.python.org/lib/module-unittest.html Python Unit testing framework]. -def test_simple(self): - assert zzz()=='Hello from zzz' +Using test functions with nose +------------------------------ +This is as simple as making a function or functions with names including 'test':: -if __name__ == "__main__": - run_module_suite() -}}} + from numpy.testing import * -You can mix nose test functions and !TestCase classes in a single test file. + # import xxx symbols + from scipy.xxx.yyy import zzz -==== Labeling tests with nose ==== + def test_simple(self): + assert zzz()=='Hello from zzz' -Unlabeled tests like the ones above are run in the default {{{scipy.test()}}} run. If you want to label your test as slow - and therefore reserved for a full {{{scipy.test(label='full')}}} run, you can label it with a nose decorator: -{{{ -# numpy.testing module includes 'import decorators as dec' -from numpy.testing import * - at dec.slow -def test_big(self): - print 'Big, slow test' -}}} + if __name__ == "__main__": + run_module_suite() -Similarly for methods: -{{{ -class test_zzz(TestCase): - @dec.slow - def test_simple(self): - assert zzz()=='Hello from zzz' -}}} +You can mix nose test functions and TestCase classes in a single test file. -==== Easier setup and teardown functions / methods ==== +Labeling tests with nose +------------------------ -Nose looks for module level setup and teardown functions by name; thus: +Unlabeled tests like the ones above are run in the default ``scipy.test()`` run. If you want to label your test as slow - and therefore reserved for a full ``scipy.test(label='full')`` run, you can label it with a nose decorator:: -{{{ -def setup(): - """Module-level setup""" - print 'doing setup' + # numpy.testing module includes 'import decorators as dec' + from numpy.testing import * + @dec.slow + def test_big(self): + print 'Big, slow test' -def teardown(): - """Module-level teardown""" - print 'doing teardown' -}}} +Similarly for methods:: -You can add setup and teardown functions to functions and methods with nose decorators: + class test_zzz(TestCase): + @dec.slow + def test_simple(self): + assert zzz()=='Hello from zzz' -{{{ -import nose -from numpy.testing import * -def setup_func(): - """A trivial setup function.""" - global helpful_variable - helpful_variable = 'pleasant' - print "In setup_func" +Easier setup and teardown functions / methods +--------------------------------------------- -def teardown_func(): - """A trivial teardown function.""" - global helpful_variable - del helpful_variable - print "In teardown_func" +Nose looks for module level setup and teardown functions by name; thus:: - at nose.with_setup(setup_func, teardown_func) -def test_with_extras(): - """This test uses the setup/teardown functions.""" - global helpful_variable - print " In test_with_extras" - print " Helpful is %s" % helpful_variable -}}} + def setup(): + """Module-level setup""" + print 'doing setup' -==== Parametric tests ==== + def teardown(): + """Module-level teardown""" + print 'doing teardown' -One very nice feature of nose is allowing easy testing across a range of parameters - a nasty problem for standard unit tests. It does this with test generators: -{{{ -def check_even(n, nn): - """A check function to be used in a test generator.""" - assert n % 2 == 0 or nn % 2 == 0 +You can add setup and teardown functions to functions and methods with nose decorators:: -def test_evens(): - for i in range(0,4,2): - yield check_even, i, i*3 -}}} + import nose + from numpy.testing import * + def setup_func(): + """A trivial setup function.""" + global helpful_variable + helpful_variable = 'pleasant' + print "In setup_func" + def teardown_func(): + """A trivial teardown function.""" + global helpful_variable + del helpful_variable + print "In teardown_func" + + @nose.with_setup(setup_func, teardown_func) + def test_with_extras(): + """This test uses the setup/teardown functions.""" + global helpful_variable + print " In test_with_extras" + print " Helpful is %s" % helpful_variable + +Parametric tests +---------------- + +One very nice feature of nose is allowing easy testing across a range of parameters - a nasty problem for standard unit tests. It does this with test generators:: + + def check_even(n, nn): + """A check function to be used in a test generator.""" + assert n % 2 == 0 or nn % 2 == 0 + + def test_evens(): + for i in range(0,4,2): + yield check_even, i, i*3 + Note that 'check_even' is not itself a test (no 'test' in the name), but 'test_evens' is a generator that returns a series of tests, using 'check_even', across a range of inputs. Nice. -=== {{{tests/}}} === -Rather than keeping the code and the tests in the same directory, we put all the tests for a given subpackage in a {{{tests/}}} subdirectory. For our example, if it doesn't all ready exist you will need to create a {{{tests/}}} directory in {{{scipy/xxx/}}}. So the path for {{{test_yyy.py}}} is {{{scipy/xxx/tests/test_yyy.py}}}. +``tests/`` +---------- -Once the {{{scipy/xxx/tests/test_yyy.py}}} is written, its possible to run the tests by going to the {{{tests/}}} directory and typing: -{{{ -python test_yyy.py -}}} -Or if you add {{{scipy/xxx/tests/}}} to the Python path, you could run the tests interactively in the interpreter like this: -{{{ ->>> import test_yyy ->>> test_yyy.test() -}}} +Rather than keeping the code and the tests in the same directory, we put all the tests for a given subpackage in a ``tests/`` subdirectory. For our example, if it doesn't all ready exist you will need to create a ``tests/`` directory in ``scipy/xxx/``. So the path for ``test_yyy.py`` is ``scipy/xxx/tests/test_yyy.py``. -=== {{{__init__.py}}} and {{{setup.py}}} === -Usually however, adding the {{{tests/}}} directory to the python path isn't desirable. Instead it would better to invoke the test straight from the module {{{xxx}}}. To this end, simply place the following lines at the end of your package's {{{__init__.py}}} file: -{{{ -... -def test(level=1, verbosity=1): - from numpy.testing import Tester - return Tester().test(level, verbosity) -}}} -You will also need to add the tests directory in the configuration section of your setup.py: -{{{ -... -def configuration(parent_package='', top_path=None): - ... - config.add_data_dir('tests') - return config -... -}}} -Now you can do the following to test your module: -{{{ ->>> import scipy ->>> scipy.xxx.test() -}}} +Once the ``scipy/xxx/tests/test_yyy.py`` is written, its possible to run the tests by going to the ``tests/`` directory and typing:: -Also, when invoking the entire !SciPy test suite, your tests will be found and run: -{{{ ->>> import scipy ->>> scipy.test() -# your tests are included and run automatically! -}}} + python test_yyy.py +Or if you add ``scipy/xxx/tests/`` to the Python path, you could run the tests interactively in the interpreter like this:: + >>> import test_yyy + >>> test_yyy.test() +``__init__.py`` and ``setup.py`` +-------------------------------- +Usually however, adding the ``tests/`` directory to the python path isn't desirable. Instead it would better to invoke the test straight from the module ``xxx``. To this end, simply place the following lines at the end of your package's ``__init__.py`` file:: + ... + def test(level=1, verbosity=1): + from numpy.testing import Tester + return Tester().test(level, verbosity) +You will also need to add the tests directory in the configuration section of your setup.py:: + ... + def configuration(parent_package='', top_path=None): + ... + config.add_data_dir('tests') + return config + ... +Now you can do the following to test your module:: + >>> import scipy + >>> scipy.xxx.test() +Also, when invoking the entire SciPy test suite, your tests will be found and run: + + >>> import scipy + >>> scipy.test() + # your tests are included and run automatically! + + + + + + + + + + + + From numpy-svn at scipy.org Wed Sep 3 03:50:05 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 3 Sep 2008 02:50:05 -0500 (CDT) Subject: [Numpy-svn] r5750 - trunk/doc Message-ID: <20080903075005.1322739C021@scipy.org> Author: alan.mcintyre Date: 2008-09-03 02:49:59 -0500 (Wed, 03 Sep 2008) New Revision: 5750 Modified: trunk/doc/TESTS.txt Log: Added section discussing using subclassing to create similar tests. Modified: trunk/doc/TESTS.txt =================================================================== --- trunk/doc/TESTS.txt 2008-09-03 06:11:28 UTC (rev 5749) +++ trunk/doc/TESTS.txt 2008-09-03 07:49:59 UTC (rev 5750) @@ -185,10 +185,9 @@ Now you can do the following to test your module:: - >>> import scipy - >>> scipy.xxx.test() + >>> import scipy + >>> scipy.xxx.test() - Also, when invoking the entire SciPy test suite, your tests will be found and run: >>> import scipy @@ -196,13 +195,44 @@ # your tests are included and run automatically! +Tips & Tricks +''''''''''''' +Creating many similar tests +--------------------------- +If you have a collection of tests that must be run multiple times with minor variations, it can be helpful to create a base class containing all the common tests, and then create a subclass for each variation. Several examples of this technique exist in NumPy; below are excerpts from one in `numpy/linalg/tests/test_linalg.py `__:: + class LinalgTestCase: + def test_single(self): + a = array([[1.,2.], [3.,4.]], dtype=single) + b = array([2., 1.], dtype=single) + self.do(a, b) + def test_double(self): + a = array([[1.,2.], [3.,4.]], dtype=double) + b = array([2., 1.], dtype=double) + self.do(a, b) + ... + class TestSolve(LinalgTestCase, TestCase): + def do(self, a, b): + x = linalg.solve(a, b) + assert_almost_equal(b, dot(a, x)) + assert imply(isinstance(b, matrix), isinstance(x, matrix)) + class TestInv(LinalgTestCase, TestCase): + def do(self, a, b): + a_inv = linalg.inv(a) + assert_almost_equal(dot(a, a_inv), identity(asarray(a).shape[0])) + assert imply(isinstance(a, matrix), isinstance(a_inv, matrix)) +In this case, we wanted to test solving a linear algebra problem using matrices of several data types, using ``linalg.solve`` and ``linalg.inv``. The common test cases (for single-precision, double-precision, etc. matrices) are collected in ``LinalgTestCase``. Note that ``LinalgTestCase`` is not descended from ``TestCase``--if it were, then nose would attempt to run ``LinalgTestCase.test_single`` and ``LinalgTestCase.test_double``, which would fail because ``LinalgTestCase`` has no ``do`` method. Since ``TestSolve`` and ``TestInv`` inherit from ``LinalgTestCase`` and ``TestCase``, nose will run ``test_single`` and ``test_double`` for each class. + + + + + From numpy-svn at scipy.org Wed Sep 3 12:48:53 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 3 Sep 2008 11:48:53 -0500 (CDT) Subject: [Numpy-svn] r5751 - trunk/numpy/ma Message-ID: <20080903164853.E52F539C02A@scipy.org> Author: pierregm Date: 2008-09-03 11:48:52 -0500 (Wed, 03 Sep 2008) New Revision: 5751 Modified: trunk/numpy/ma/core.py Log: docstring update Modified: trunk/numpy/ma/core.py =================================================================== --- trunk/numpy/ma/core.py 2008-09-03 07:49:59 UTC (rev 5750) +++ trunk/numpy/ma/core.py 2008-09-03 16:48:52 UTC (rev 5751) @@ -1817,18 +1817,33 @@ def compress(self, condition, axis=None, out=None): - """Return a where condition is True. - If condition is a MaskedArray, missing values are considered as False. + """ + Return `a` where condition is ``True``. + If condition is a `MaskedArray`, missing values are considered as ``False``. - Returns - ------- - A MaskedArray object. + Parameters + ---------- + condition : var + Boolean 1-d array selecting which entries to return. If len(condition) + is less than the size of a along the axis, then output is truncated + to length of condition array. + axis : {None, int}, optional + Axis along which the operation must be performed. + out : {None, ndarray}, optional + Alternative output array in which to place the result. It must have + the same shape as the expected output but the type will be cast if + necessary. - Notes - ----- - Please note the difference with compressed() ! - The output of compress has a mask, the output of compressed does not. + Returns + ------- + result : MaskedArray + A :class:`MaskedArray` object. + Warnings + -------- + Please note the difference with :meth:`compressed` ! + The output of :meth:`compress` has a mask, the output of :meth:`compressed` does not. + """ # Get the basic components (_data, _mask) = (self._data, self._mask) @@ -2038,9 +2053,10 @@ Returns ------- - A masked array where the mask is True where all data are - masked. If axis is None, returns either a scalar ot the - masked singleton if all values are masked. + result : MaskedArray + A masked array where the mask is True where all data are + masked. If axis is None, returns either a scalar ot the + masked singleton if all values are masked. """ m = self._mask @@ -2182,7 +2198,7 @@ Check if all of the elements of `a` are true. - Performs a logical_and over the given axis and returns the result. + Performs a :func:`logical_and` over the given axis and returns the result. Masked values are considered as True during computation. For convenience, the output array is masked where ALL the values along the current axis are masked: if the output would have been a scalar and that @@ -2344,10 +2360,8 @@ def cumsum(self, axis=None, dtype=None, out=None): - """a.cumsum(axis=None, dtype=None, out=None) - + """ Return the cumulative sum of the elements along the given axis. - The cumulative sum is calculated over the flattened array by default, otherwise over the specified axis. @@ -2358,20 +2372,24 @@ Parameters ---------- axis : {None, -1, int}, optional - Axis along which the sum is computed. The default - (`axis` = None) is to compute over the flattened array. + Axis along which the sum is computed. The default (`axis` = None) is to + compute over the flattened array. `axis` may be negative, in which case + it counts from the last to the first axis. dtype : {None, dtype}, optional - Determines the type of the returned array and of the accumulator - where the elements are summed. If dtype has the value None and - the type of a is an integer type of precision less than the default - platform integer, then the default platform integer precision is - used. Otherwise, the dtype is the same as that of a. + Type of the returned array and of the accumulator in which the + elements are summed. If `dtype` is not specified, it defaults + to the dtype of `a`, unless `a` has an integer dtype with a + precision less than that of the default platform integer. In + that case, the default platform integer is used. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. - WARNING : The mask is lost if out is not a valid MaskedArray ! + Warning + ------- + The mask is lost if out is not a valid :class:`MaskedArray` ! + Returns ------- cumsum : ndarray. @@ -2380,7 +2398,8 @@ Example ------- - >>> print np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]).cumsum() + >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]) + >>> print marr.cumsum() [0 1 3 -- -- -- 9 16 24 33] @@ -2401,8 +2420,7 @@ def prod(self, axis=None, dtype=None, out=None): - """a.prod(axis=None, dtype=None, out=None) - + """ Return the product of the array elements over the given axis. Masked elements are set to 1 internally for computation. @@ -2413,8 +2431,8 @@ product is over all the array elements. dtype : {None, dtype}, optional Determines the type of the returned array and of the accumulator - where the elements are multiplied. If dtype has the value None and - the type of a is an integer type of precision less than the default + where the elements are multiplied. If ``dtype`` has the value ``None`` + and the type of a is an integer type of precision less than the default platform integer, then the default platform integer precision is used. Otherwise, the dtype is the same as that of a. out : {None, array}, optional @@ -2473,10 +2491,7 @@ def cumprod(self, axis=None, dtype=None, out=None): """ - a.cumprod(axis=None, dtype=None, out=None) - Return the cumulative product of the elements along the given axis. - The cumulative product is taken over the flattened array by default, otherwise over the specified axis. @@ -2491,21 +2506,24 @@ (`axis` = None) is to compute over the flattened array. dtype : {None, dtype}, optional Determines the type of the returned array and of the accumulator - where the elements are multiplied. If dtype has the value None and - the type of a is an integer type of precision less than the default + where the elements are multiplied. If ``dtype`` has the value ``None`` and + the type of ``a`` is an integer type of precision less than the default platform integer, then the default platform integer precision is - used. Otherwise, the dtype is the same as that of a. + used. Otherwise, the dtype is the same as that of ``a``. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. - WARNING : The mask is lost if out is not a valid MaskedArray ! + Warning + ------- + The mask is lost if out is not a valid MaskedArray ! + Returns ------- - cumprod : ndarray. - A new array holding the result is returned unless out is - specified, in which case a reference to out is returned. + cumprod : ndarray + A new array holding the result is returned unless out is specified, + in which case a reference to out is returned. Notes ----- @@ -2524,43 +2542,7 @@ def mean(self, axis=None, dtype=None, out=None): - """a.mean(axis=None, dtype=None, out=None) -> mean - - Returns the average of the array elements. The average is taken over the - flattened array by default, otherwise over the specified axis. - - Parameters - ---------- - axis : integer - Axis along which the means are computed. The default is - to compute the mean of the flattened array. - dtype : type - Type to use in computing the means. For arrays of - integer type the default is float32, for arrays of float types it - is the same as the array type. - out : ndarray - Alternative output array in which to place the result. It must have - the same shape as the expected output but the type will be cast if - necessary. - - Returns - ------- - mean : The return type varies, see above. - A new array holding the result is returned unless out is specified, - in which case a reference to out is returned. - - See Also - -------- - var : variance - std : standard deviation - - Notes - ----- - The mean is the sum of the elements along the axis divided by the - number of elements. - - - """ + "" if self._mask is nomask: result = super(MaskedArray, self).mean(axis=axis, dtype=dtype) else: @@ -2576,21 +2558,22 @@ outmask.flat = getattr(result, '_mask', nomask) return out return result + mean.__doc__ = ndarray.mean.__doc__ def anom(self, axis=None, dtype=None): - """Return the anomalies (deviations from the average) along - the given axis. + """ + Return the anomalies (deviations from the average) along the given axis. - Parameters - ---------- - axis : int, optional - Axis along which to perform the operation. - If None, applies to a flattened version of the array. - dtype : {dtype}, optional - Datatype for the intermediary computation. If not - given, the current dtype is used instead. + Parameters + ---------- + axis : int, optional + Axis along which to perform the operation. + If None, applies to a flattened version of the array. + dtype : {dtype}, optional + Datatype for the intermediary computation. + If not given, the current dtype is used instead. - """ + """ m = self.mean(axis, dtype) if not axis: return (self - m) @@ -2598,50 +2581,7 @@ return (self - expand_dims(m,axis)) def var(self, axis=None, dtype=None, out=None, ddof=0): - """a.var(axis=None, dtype=None, out=None, ddof=0) -> variance - - Returns the variance of the array elements, a measure of the spread of a - distribution. The variance is computed for the flattened array by default, - otherwise over the specified axis. - - Parameters - ---------- - axis : integer - Axis along which the variance is computed. The default is to - compute the variance of the flattened array. - dtype : data-type - Type to use in computing the variance. For arrays of integer type - the default is float32, for arrays of float types it is the same as - the array type. - out : ndarray - Alternative output array in which to place the result. It must have - the same shape as the expected output but the type will be cast if - necessary. - ddof : {0, integer}, - Means Delta Degrees of Freedom. The divisor used in calculation is - N - ddof. - - Returns - ------- - variance : The return type varies, see above. - A new array holding the result is returned unless out is specified, - in which case a reference to out is returned. - - See Also - -------- - std : standard deviation - mean: average - - Notes - ----- - The variance is the average of the squared deviations from the mean, - i.e. var = mean(abs(x - x.mean())**2). The mean is computed by - dividing by N-ddof, where N is the number of elements. The argument - ddof defaults to zero; for an unbiased estimate supply ddof=1. Note - that for complex numbers the absolute value is taken before squaring, - so that the result is always real and nonnegative. - - """ + "" # Easy case: nomask, business as usual if self._mask is nomask: return self._data.var(axis=axis, dtype=dtype, out=out, ddof=ddof) @@ -2675,52 +2615,11 @@ out.__setmask__(dvar.mask) return out return dvar + var.__doc__ = np.var.__doc__ - def std(self, axis=None, dtype=None, out=None, ddof=0): - """a.std(axis=None, dtype=None, out=None, ddof=0) - Returns the standard deviation of the array elements, a measure of the - spread of a distribution. The standard deviation is computed for the - flattened array by default, otherwise over the specified axis. - - Parameters - ---------- - axis : integer - Axis along which the standard deviation is computed. The default is - to compute the standard deviation of the flattened array. - dtype : type - Type to use in computing the standard deviation. For arrays of - integer type the default is float32, for arrays of float types it - is the same as the array type. - out : ndarray - Alternative output array in which to place the result. It must have - the same shape as the expected output but the type will be cast if - necessary. - ddof : {0, integer} - Means Delta Degrees of Freedom. The divisor used in calculations - is N-ddof. - - Returns - ------- - standard deviation : The return type varies, see above. - A new array holding the result is returned unless out is specified, - in which case a reference to out is returned. - - See Also - -------- - var : variance - mean : average - - Notes - ----- - The standard deviation is the square root of the average of the squared - deviations from the mean, i.e. var = sqrt(mean(abs(x - x.mean())**2)). The - computed standard deviation is computed by dividing by the number of - elements, N-ddof. The option ddof defaults to zero, that is, a biased - estimate. Note that for complex numbers std takes the absolute value before - squaring, so that the result is always real and nonnegative. - - """ + def std(self, axis=None, dtype=None, out=None, ddof=0): + "" dvar = self.var(axis=axis,dtype=dtype,out=out, ddof=ddof) if dvar is not masked: dvar = sqrt(dvar) @@ -2728,6 +2627,7 @@ out **= 0.5 return out return dvar + std.__doc__ = np.std.__doc__ #............................................ def round(self, decimals=0, out=None): @@ -2928,8 +2828,7 @@ #............................................ def min(self, axis=None, out=None, fill_value=None): - """a.min(axis=None, out=None, fill_value=None) - + """ Return the minimum along a given axis. Parameters @@ -2938,11 +2837,11 @@ Axis along which to operate. By default, ``axis`` is None and the flattened input is used. out : array_like, optional - Alternative output array in which to place the result. Must - be of the same shape and buffer length as the expected output. + Alternative output array in which to place the result. Must be of + the same shape and buffer length as the expected output. fill_value : {var}, optional Value used to fill in the masked values. - If None, use the output of minimum_fill_value(). + If None, use the output of `minimum_fill_value`. Returns ------- @@ -2950,6 +2849,11 @@ New array holding the result. If ``out`` was specified, ``out`` is returned. + See Also + -------- + minimum_fill_value + Returns the minimum filling value for a given datatype. + """ _mask = ndarray.__getattribute__(self, '_mask') newmask = _mask.all(axis=axis) @@ -3008,6 +2912,11 @@ New array holding the result. If ``out`` was specified, ``out`` is returned. + See Also + -------- + maximum_fill_value + Returns the maximum filling value for a given datatype. + """ _mask = ndarray.__getattribute__(self, '_mask') newmask = _mask.all(axis=axis) @@ -3649,7 +3558,8 @@ return def transpose(a, axes=None): - """Return a view of the array with dimensions permuted according to axes, + """ + Return a view of the array with dimensions permuted according to axes, as a masked array. If ``axes`` is None (default), the output view has reversed @@ -3953,7 +3863,8 @@ #---- --- Pickling --- #####-------------------------------------------------------------------------- def dump(a,F): - """Pickle the MaskedArray `a` to the file `F`. `F` can either be + """ + Pickle the MaskedArray `a` to the file `F`. `F` can either be the handle of an exiting file, or a string representing a file name. @@ -3963,15 +3874,16 @@ return cPickle.dump(a,F) def dumps(a): - """Return a string corresponding to the pickling of the - MaskedArray. + """ + Return a string corresponding to the pickling of the MaskedArray. """ return cPickle.dumps(a) def load(F): - """Wrapper around ``cPickle.load`` which accepts either a - file-like object or a filename. + """ + Wrapper around ``cPickle.load`` which accepts either a file-like object + or a filename. """ if not hasattr(F, 'readline'): From numpy-svn at scipy.org Wed Sep 3 12:54:46 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 3 Sep 2008 11:54:46 -0500 (CDT) Subject: [Numpy-svn] r5752 - trunk/doc/neps Message-ID: <20080903165446.D43C539C02A@scipy.org> Author: cdavid Date: 2008-09-03 11:54:37 -0500 (Wed, 03 Sep 2008) New Revision: 5752 Added: trunk/doc/neps/warnfix.txt Log: Start a nep for warn-free numpy build. Added: trunk/doc/neps/warnfix.txt =================================================================== --- trunk/doc/neps/warnfix.txt 2008-09-03 16:48:52 UTC (rev 5751) +++ trunk/doc/neps/warnfix.txt 2008-09-03 16:54:37 UTC (rev 5752) @@ -0,0 +1,82 @@ +=========================================================== +A proposal to build numpy without warning with a big set of +warning flags +=========================================================== + +:Author: David Cournapeau +:Contact: david at ar.media.kyoto-u.ac.jp +:Date: 2008-09-04 + +Executive summary +================= + +When building numpy and scipy, we are limited to a quite restricted set of +warning compilers, thus missing a large class of potential bugs which could be +detected with stronger warning flags. The goal of this PEP is to clean the code +and implements some policy to make numpy buildable with a bigger set of +warning flags, while keeping the build warnings free. + +Warning flags +============= + +Each compiler detects a diffferent set of potential errors. The baseline will +be gcc -Wall -W -Wextra. Ideally, a complete set would be nice: + +-W -Wall -Wextra -Wstrict-prototypes -Wmissing-prototypes -Waggregate-return +-Wcast-align -Wcast-qual -Wnested-externs -Wshadow -Wbad-function-cast +-Wwrite-strings " + +Intel compiler, VS with /W3 /Wall, Sun compilers have extra warnings too. + +Kind of warnings +================ + +C Python extension code tends to naturally generate a lot of spurious warnings. +The goal is to have some facilities to tag some typical C-Python code so that +the compilers do not generate warnings in those cases; the tag process has to +be clean, readable, and be robust. In particular, it should not make the code +more obscure or worse, break working code. + +unused parameter +---------------- + +This one appears often: any python-callable C function takes two arguments, +of which the first is not used for functions (only for methods). One way to +solve it is to tag the function argument with a macro NPY_UNUSED. This macro +uses compiler specific code to tag the variable, and mangle it such as it is +not possible to use it accidentally once it is tagged. + +The code to apply compiler specific option could be: + +#if defined(__GNUC__) + #define __COMP_NPY_UNUSED __attribute__ ((__unused__)) +# elif defined(__ICC) + #define __COMP_NPY_UNUSED __attribute__ ((__unused__)) +#else + #define __COMP_NPY_UNUSED +#endif + +The variable mangling would be: + +#define NPY_UNUSED(x) (__NPY_UNUSED_TAGGED ## x) __COMP_NPY_UNUSED + +When applied to a variable, one would get: + +int foo(int * NPY_UNUSED(dummy)) + +expanded to + +int foo(int * __NPY_UNUSED_TAGGEDdummy __COMP_NPY_UNUSED) + +Thus avoiding any accidental use of the variable. The mangling is pure C, and +thuse portable. The per-variable warning disabling is compiler specific. + +signed/unsigned comparison +-------------------------- + +More tricky: not always clear what to do + +half-initialized structures +--------------------------- + +Just put the elements with NULL in it. From numpy-svn at scipy.org Thu Sep 4 09:31:34 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 08:31:34 -0500 (CDT) Subject: [Numpy-svn] r5753 - trunk/doc/neps Message-ID: <20080904133134.BFD0F39C02D@scipy.org> Author: cdavid Date: 2008-09-04 08:31:24 -0500 (Thu, 04 Sep 2008) New Revision: 5753 Modified: trunk/doc/neps/warnfix.txt Log: Update the warnfix nep. Modified: trunk/doc/neps/warnfix.txt =================================================================== --- trunk/doc/neps/warnfix.txt 2008-09-03 16:54:37 UTC (rev 5752) +++ trunk/doc/neps/warnfix.txt 2008-09-04 13:31:24 UTC (rev 5753) @@ -12,9 +12,10 @@ When building numpy and scipy, we are limited to a quite restricted set of warning compilers, thus missing a large class of potential bugs which could be -detected with stronger warning flags. The goal of this PEP is to clean the code -and implements some policy to make numpy buildable with a bigger set of -warning flags, while keeping the build warnings free. +detected with stronger warning flags. The goal of this PEP is present the +various methods used to clean the code and implement some policy to make numpy +buildable with a bigger set of warning flags, while keeping the build warnings +free. Warning flags ============= From numpy-svn at scipy.org Thu Sep 4 09:37:17 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 08:37:17 -0500 (CDT) Subject: [Numpy-svn] r5754 - trunk/doc/neps Message-ID: <20080904133717.6831439C13A@scipy.org> Author: cdavid Date: 2008-09-04 08:36:53 -0500 (Thu, 04 Sep 2008) New Revision: 5754 Added: trunk/doc/neps/math_config_clean.txt Log: Start a nep for cleaning the math configuration. Added: trunk/doc/neps/math_config_clean.txt =================================================================== --- trunk/doc/neps/math_config_clean.txt 2008-09-04 13:31:24 UTC (rev 5753) +++ trunk/doc/neps/math_config_clean.txt 2008-09-04 13:36:53 UTC (rev 5754) @@ -0,0 +1,68 @@ +=========================================================== +Cleaning the math configuration of numpy.core +=========================================================== + +:Author: David Cournapeau +:Contact: david at ar.media.kyoto-u.ac.jp +:Date: 2008-09-04 + +Executive summary +================= + +Before building numpy.core, we use some configuration tests to gather some +information about available math functions. Over the years, the configuration +became convoluted, to the point it became difficult to support new platforms +easily. + +The goal of this proposal is to clean the configuration of the math +capabilities for easier maintenance. + +Current problems +================ + +Currently, the math configuration mainly test for some math functions, and +configure numpy accordingly. But instead of testing each desired function +independantly, the current system has been developed more as workarounds +particular platform oddities, using platform implicit knowledge. This is +against the normal philosophy of testing for capabilities only, which is the +autoconf philosophy, which showed the path toward portability (on Unix at +least) [1] This causes problems because modifying or adding configuration on +existing platforms break the implicit assumption, without a clear solution. + +For example, on windows, when numpy is built with mingw, it would be nice to +enforce the configuration sizeof(long double) == sizeof(double) because mingw +uses the MS runtime, and the MS runtime does not support long double. +Unfortunately, doing so breaks the mingw math function detection, because of +the implicit assumption that mingw has a configuration sizeof(long double) != +sizeof(double). + +Another example is the testing for set of functions using only one function: if +expf is found, it is assumed that all basic float functions are available. +Instead, each function should be tested independantly (expf, sinf, etc...). + +Requirements +============ + +We have two strong requirements: + - it should not break any currently supported platform + - it should not make the configuration much slower (1-2 seconds are + acceptable) + +Proposal +======== + +We suggest to break any implicit assumption, and test each math function +independantly from each other, as usually done by autoconf. Since testing for a +vast set of functions can be time consuming, we will use a scheme similar to +AC_CHECK_FUNCS_ONCE in autoconf, that is test for a set of function at once, +and only in the case it breaks, do the per function check. When the first check +works, it should be as fast as the current scheme, except that the assumptions +are explicitely checked (all functions implied by HAVE_LONGDOUBLE_FUNCS would +be checked together, for example). + +License +======= + +This document has been placed in the public domain. + +[1]: Autobook here From numpy-svn at scipy.org Thu Sep 4 09:49:04 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 08:49:04 -0500 (CDT) Subject: [Numpy-svn] r5755 - trunk/doc/neps Message-ID: <20080904134904.2ED9239C02A@scipy.org> Author: cdavid Date: 2008-09-04 08:49:01 -0500 (Thu, 04 Sep 2008) New Revision: 5755 Modified: trunk/doc/neps/math_config_clean.txt Log: Update clean math config nep. Modified: trunk/doc/neps/math_config_clean.txt =================================================================== --- trunk/doc/neps/math_config_clean.txt 2008-09-04 13:36:53 UTC (rev 5754) +++ trunk/doc/neps/math_config_clean.txt 2008-09-04 13:49:01 UTC (rev 5755) @@ -60,6 +60,11 @@ are explicitely checked (all functions implied by HAVE_LONGDOUBLE_FUNCS would be checked together, for example). +Issues +====== + +Static vs non static ? For basic functions, shall we define them static or not ? + License ======= From numpy-svn at scipy.org Thu Sep 4 09:49:47 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 08:49:47 -0500 (CDT) Subject: [Numpy-svn] r5756 - branches/clean_math_config/numpy/core/src Message-ID: <20080904134947.7876839C02A@scipy.org> Author: cdavid Date: 2008-09-04 08:49:42 -0500 (Thu, 04 Sep 2008) New Revision: 5756 Added: branches/clean_math_config/numpy/core/src/math_c99.c Log: Add a math_c99 compatibility module. Added: branches/clean_math_config/numpy/core/src/math_c99.c =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-04 13:49:01 UTC (rev 5755) +++ branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-04 13:49:42 UTC (rev 5756) @@ -0,0 +1,137 @@ +/* + * A small module to implement missing C99 math capabilities required by numpy + * + * Please keep this independant of python as much as possible ! + */ + +/* + * Include python.h because it may modify math.h configuration, but we won't + * use any python code at all here + */ +#include "Python.h" +#include "config.h" +#include + +/* + * Basic functions, double version. Some old/weird platforms may not have those + * + * Original code by Konrad Hinsen. + */ +#ifndef HAVE_EXPM1 +double expm1(double x) +{ + double u = exp(x); + if (u == 1.0) { + return x; + } else if (u-1.0 == -1.0) { + return -1; + } else { + return (u-1.0) * x/log(u); + } +} +#endif + +#ifndef HAVE_LOG1P +double log1p(double x) +{ + double u = 1. + x; + if (u == 1.0) { + return x; + } else { + return log(u) * x / (u-1.); + } +} +#endif + +#ifndef HAVE_HYPOT +double hypot(double x, double y) +{ + double yx; + + x = fabs(x); + y = fabs(y); + if (x < y) { + double temp = x; + x = y; + y = temp; + } + if (x == 0.) + return 0.; + else { + yx = y/x; + return x*sqrt(1.+yx*yx); + } +} +#endif + +#ifndef HAVE_ACOSH +double acosh(double x) +{ + return 2*log(sqrt((x+1.0)/2)+sqrt((x-1.0)/2)); +} +#endif + +#ifndef HAVE_ASINH +double asinh(double xx) +{ + double x, d; + int sign; + if (xx < 0.0) { + sign = -1; + x = -xx; + } + else { + sign = 1; + x = xx; + } + if (x > 1e8) { + d = x; + } else { + d = sqrt(x*x + 1); + } + return sign*log1p(x*(1.0 + x/(d+1))); +} +#endif + +#ifndef HAVE_ATANH +static double atanh(double x) +{ + return 0.5*log1p(2.0*x/(1.0-x)); +} +#endif + +#ifndef HAVE_RINT +double rint(double x) +{ + double y, r; + + y = floor(x); + r = x - y; + + if (r > 0.5) goto rndup; + + /* Round to nearest even */ + if (r==0.5) { + r = y - 2.0*floor(0.5*y); + if (r==1.0) { + rndup: + y+=1.0; + } + } + return y; +} +#endif + +#ifndef HAVE_TRUNC +double trunc(double x) +{ + if (x < 0) { + return ceil(x); + } + else { + return floor(x); + } + +} +#endif + From numpy-svn at scipy.org Thu Sep 4 09:58:51 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 08:58:51 -0500 (CDT) Subject: [Numpy-svn] r5757 - branches/clean_math_config/numpy/core/src Message-ID: <20080904135851.5103339C02A@scipy.org> Author: cdavid Date: 2008-09-04 08:58:47 -0500 (Thu, 04 Sep 2008) New Revision: 5757 Modified: branches/clean_math_config/numpy/core/src/math_c99.c Log: Add float and long double functions (C99). Modified: branches/clean_math_config/numpy/core/src/math_c99.c =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-04 13:49:42 UTC (rev 5756) +++ branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-04 13:58:47 UTC (rev 5757) @@ -135,3 +135,368 @@ } #endif +/* + * if C99 extensions not available then define dummy functions that use the + * double versions for + * + * sin, cos, tan + * sinh, cosh, tanh, + * fabs, floor, ceil, fmod, sqrt, log10, log, exp, fabs + * asin, acos, atan, + * asinh, acosh, atanh + * + * hypot, atan2, pow, expm1 + * + * We assume the above are always available in their double versions. + */ + +/* + * Long double versions + */ +#ifndef HAVE_SINL +longdouble sinl(longdouble x) +{ + return (longdouble) sin((double)x); +} +#endif + +#ifndef HAVE_COSL +longdouble cosl(longdouble x) +{ + return (longdouble) cos((double)x); +} +#endif + +#ifndef HAVE_TANL +longdouble tanl(longdouble x) +{ + return (longdouble) tan((double)x); +} +#endif + +#ifndef HAVE_SINHL +longdouble sinhl(longdouble x) +{ + return (longdouble) sinh((double)x); +} +#endif + +#ifndef HAVE_COSHL +longdouble coshl(longdouble x) +{ + return (longdouble) cosh((double)x); +} +#endif + +#ifndef HAVE_TANHL +longdouble tanhl(longdouble x) +{ + return (longdouble) tanh((double)x); +} +#endif + +#ifndef HAVE_FABSL +longdouble fabsl(longdouble x) +{ + return (longdouble) fabs((double)x); +} +#endif + +#ifndef HAVE_FLOORL +longdouble floorl(longdouble x) +{ + return (longdouble) floor((double)x); +} +#endif + +#ifndef HAVE_CEILL +longdouble ceill(longdouble x) +{ + return (longdouble) ceil((double)x); +} +#endif + +#ifndef HAVE_SQRTL +longdouble sqrtl(longdouble x) +{ + return (longdouble) sqrt((double)x); +} +#endif + +#ifndef HAVE_LOG10L +longdouble log10l(longdouble x) +{ + return (longdouble) log10((double)x); +} +#endif + +#ifndef HAVE_LOGL +longdouble logl(longdouble x) +{ + return (longdouble) log((double)x); +} +#endif + +#ifndef HAVE_EXPL +longdouble expl(longdouble x) +{ + return (longdouble) exp((double)x); +} +#endif + +#ifndef HAVE_EXPM1L +longdouble expm1l(longdouble x) +{ + return (longdouble) expm1((double)x); +} +#endif + +#ifndef HAVE_ASINL +longdouble asinl(longdouble x) +{ + return (longdouble) asin((double)x); +} +#endif + +#ifndef HAVE_ACOSL +longdouble acosl(longdouble x) +{ + return (longdouble) acos((double)x); +} +#endif + +#ifndef HAVE_ATANL +longdouble atanl(longdouble x) +{ + return (longdouble) atan((double)x); +} +#endif + +#ifndef HAVE_RINTL +longdouble rintl(longdouble x) +{ + return (longdouble) rint((double)x); +} +#endif + +#ifndef HAVE_EXPML +longdouble expml(longdouble x) +{ + return (longdouble) expm((double)x); +} +#endif + +#ifndef HAVE_ATAN2L +longdouble atan2l(longdouble x, longdouble y) +{ + return (longdouble) atan2((double)x, (double) y); +} +#endif + +#ifndef HAVE_HYPOTL +longdouble hypotl(longdouble x, longdouble y) +{ + return (longdouble) hypot((double)x, (double) y); +} +#endif + +#ifndef HAVE_POWL +longdouble powl(longdouble x, longdouble y) +{ + return (longdouble) pow((double)x, (double) y); +} +#endif + +#ifndef HAVE_FMODL +longdouble fmodl(longdouble x, longdouble y) +{ + return (longdouble) fmod((double)x, (double) y); +} +#endif + +#ifndef HAVE_MODFL +longdouble modfl(longdouble x, longdouble *iptr) +{ + double nx, niptr, y; + nx = (double) x; + y = modf(nx, &niptr); + *iptr = (longdouble) niptr; + return (longdouble) y; +} +#endif + +/* + * float versions + */ +#ifndef HAVE_SINF +float sinf(float x) +{ + return (float) sin((double)x); +} +#endif + +#ifndef HAVE_COSF +float cosf(float x) +{ + return (float) cos((double)x); +} +#endif + +#ifndef HAVE_TANF +float tanf(float x) +{ + return (float) tan((double)x); +} +#endif + +#ifndef HAVE_SINHF +float sinhf(float x) +{ + return (float) sinh((double)x); +} +#endif + +#ifndef HAVE_COSHF +float coshf(float x) +{ + return (float) cosh((double)x); +} +#endif + +#ifndef HAVE_TANHF +float tanhf(float x) +{ + return (float) tanh((double)x); +} +#endif + +#ifndef HAVE_FABSF +float fabsf(float x) +{ + return (float) fabs((double)x); +} +#endif + +#ifndef HAVE_FLOORF +float floorf(float x) +{ + return (float) floor((double)x); +} +#endif + +#ifndef HAVE_CEILF +float ceilf(float x) +{ + return (float) ceil((double)x); +} +#endif + +#ifndef HAVE_SQRTF +float sqrtf(float x) +{ + return (float) sqrt((double)x); +} +#endif + +#ifndef HAVE_LOG10F +float log10f(float x) +{ + return (float) log10((double)x); +} +#endif + +#ifndef HAVE_LOGF +float logf(float x) +{ + return (float) log((double)x); +} +#endif + +#ifndef HAVE_EXPF +float expf(float x) +{ + return (float) exp((double)x); +} +#endif + +#ifndef HAVE_EXPM1F +float expm1f(float x) +{ + return (float) expm1((double)x); +} +#endif + +#ifndef HAVE_ASINF +float asinf(float x) +{ + return (float) asin((double)x); +} +#endif + +#ifndef HAVE_ACOSF +float acosf(float x) +{ + return (float) acos((double)x); +} +#endif + +#ifndef HAVE_ATANF +float atanf(float x) +{ + return (float) atan((double)x); +} +#endif + +#ifndef HAVE_RINTF +float rintf(float x) +{ + return (float) rint((double)x); +} +#endif + +#ifndef HAVE_EXPMF +float expmf(float x) +{ + return (float) expm((double)x); +} +#endif + +#ifndef HAVE_ATAN2F +float atan2f(float x, float y) +{ + return (float) atan2((double)x, (double) y); +} +#endif + +#ifndef HAVE_HYPOTF +float hypotf(float x, float y) +{ + return (float) hypot((double)x, (double) y); +} +#endif + +#ifndef HAVE_POWF +float powf(float x, float y) +{ + return (float) pow((double)x, (double) y); +} +#endif + +#ifndef HAVE_FMODF +float fmodf(float x, float y) +{ + return (float) fmod((double)x, (double) y); +} +#endif + +#ifndef HAVE_MODFF +float modff(float x, float *iptr) +{ + double nx, niptr, y; + nx = (double) x; + y = modf(nx, &niptr); + *iptr = (float) niptr; + return (float) y; +} +#endif + From numpy-svn at scipy.org Thu Sep 4 10:35:55 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 09:35:55 -0500 (CDT) Subject: [Numpy-svn] r5758 - branches/clean_math_config/numpy/core/src Message-ID: <20080904143555.40D3C39C02A@scipy.org> Author: cdavid Date: 2008-09-04 09:35:51 -0500 (Thu, 04 Sep 2008) New Revision: 5758 Modified: branches/clean_math_config/numpy/core/src/math_c99.c Log: Use code generator for c99_math.c Modified: branches/clean_math_config/numpy/core/src/math_c99.c =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-04 13:58:47 UTC (rev 5757) +++ branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-04 14:35:51 UTC (rev 5758) @@ -141,362 +141,79 @@ * * sin, cos, tan * sinh, cosh, tanh, - * fabs, floor, ceil, fmod, sqrt, log10, log, exp, fabs + * fabs, floor, ceil, rint, trunc + * sqrt, log10, log, exp * asin, acos, atan, * asinh, acosh, atanh * - * hypot, atan2, pow, expm1 + * hypot, atan2, pow, fmod, modf * * We assume the above are always available in their double versions. */ -/* - * Long double versions +/* + * One value argument function */ -#ifndef HAVE_SINL -longdouble sinl(longdouble x) -{ - return (longdouble) sin((double)x); -} -#endif -#ifndef HAVE_COSL -longdouble cosl(longdouble x) -{ - return (longdouble) cos((double)x); -} -#endif +/**begin repeat -#ifndef HAVE_TANL -longdouble tanl(longdouble x) -{ - return (longdouble) tan((double)x); -} -#endif + #kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,rint,trunc,sqrt,log10,log,exp,asin,acos,atan,asinh,acosh,atanh)*2# + #KIND=(SIN,COS,TAN,SINH,COSH,TANH,FABS,FLOOR,CEIL,RINT,TRUNC,SQRT,LOG10,LOG,EXP,ASIN,ACOS,ATAN,ASINH,ACOSH,ATANH)*2# + #typ=longdouble*21, float*21# + #c=l*21,f*21# + #C=L*21,F*21# + #TYPE=LONGDOUBLE*21, FLOAT*21# +*/ -#ifndef HAVE_SINHL -longdouble sinhl(longdouble x) +#ifndef HAVE_ at KIND@@C@ + at typ@ @kind@@c@(@typ@ x) { - return (longdouble) sinh((double)x); + return (@typ@) @kind@((double)x); } #endif +/**end repeat**/ -#ifndef HAVE_COSHL -longdouble coshl(longdouble x) -{ - return (longdouble) cosh((double)x); -} -#endif +/* + * Two values arguments function + */ -#ifndef HAVE_TANHL -longdouble tanhl(longdouble x) -{ - return (longdouble) tanh((double)x); -} -#endif +/**begin repeat -#ifndef HAVE_FABSL -longdouble fabsl(longdouble x) + #kind=(atan2,hypot,pow,fmod)*2# + #KIND=(ATAN2,HYPOT,POW,FMOD)*2# + #typ=longdouble*4, float*4# + #c=l*4,f*4# + #C=L*4,F*4# + #TYPE=LONGDOUBLE*4,FLOAT*4# +*/ +#ifndef HAVE_ at KIND@@C@ + at typ@ @kind@@c@(@typ@ x, @typ@ y) { - return (longdouble) fabs((double)x); + return (@typ@) @kind@((double)x, (double) y); } #endif +/**end repeat**/ -#ifndef HAVE_FLOORL -longdouble floorl(longdouble x) -{ - return (longdouble) floor((double)x); -} -#endif - -#ifndef HAVE_CEILL -longdouble ceill(longdouble x) -{ - return (longdouble) ceil((double)x); -} -#endif - -#ifndef HAVE_SQRTL -longdouble sqrtl(longdouble x) -{ - return (longdouble) sqrt((double)x); -} -#endif - -#ifndef HAVE_LOG10L -longdouble log10l(longdouble x) -{ - return (longdouble) log10((double)x); -} -#endif - -#ifndef HAVE_LOGL -longdouble logl(longdouble x) -{ - return (longdouble) log((double)x); -} -#endif - -#ifndef HAVE_EXPL -longdouble expl(longdouble x) -{ - return (longdouble) exp((double)x); -} -#endif - -#ifndef HAVE_EXPM1L -longdouble expm1l(longdouble x) -{ - return (longdouble) expm1((double)x); -} -#endif - -#ifndef HAVE_ASINL -longdouble asinl(longdouble x) -{ - return (longdouble) asin((double)x); -} -#endif - -#ifndef HAVE_ACOSL -longdouble acosl(longdouble x) -{ - return (longdouble) acos((double)x); -} -#endif - -#ifndef HAVE_ATANL -longdouble atanl(longdouble x) -{ - return (longdouble) atan((double)x); -} -#endif - -#ifndef HAVE_RINTL -longdouble rintl(longdouble x) -{ - return (longdouble) rint((double)x); -} -#endif - -#ifndef HAVE_EXPML -longdouble expml(longdouble x) -{ - return (longdouble) expm((double)x); -} -#endif - -#ifndef HAVE_ATAN2L -longdouble atan2l(longdouble x, longdouble y) -{ - return (longdouble) atan2((double)x, (double) y); -} -#endif - -#ifndef HAVE_HYPOTL -longdouble hypotl(longdouble x, longdouble y) -{ - return (longdouble) hypot((double)x, (double) y); -} -#endif - -#ifndef HAVE_POWL -longdouble powl(longdouble x, longdouble y) -{ - return (longdouble) pow((double)x, (double) y); -} -#endif - -#ifndef HAVE_FMODL -longdouble fmodl(longdouble x, longdouble y) -{ - return (longdouble) fmod((double)x, (double) y); -} -#endif - -#ifndef HAVE_MODFL -longdouble modfl(longdouble x, longdouble *iptr) -{ - double nx, niptr, y; - nx = (double) x; - y = modf(nx, &niptr); - *iptr = (longdouble) niptr; - return (longdouble) y; -} -#endif - -/* - * float versions +/* + * One value - one pointer argument function */ -#ifndef HAVE_SINF -float sinf(float x) -{ - return (float) sin((double)x); -} -#endif -#ifndef HAVE_COSF -float cosf(float x) +/**begin repeat + #kind=modf*2# + #KIND=MODF*2# + #c=l,f# + #C=L,F# + #typ=longdouble, float# + #TYPE=LONGDOUBLE, FLOAT# +*/ +#ifndef HAVE_ at KIND@@C@ + at typ@ modf at c@(@typ@ x, @typ@ *iptr) { - return (float) cos((double)x); -} -#endif - -#ifndef HAVE_TANF -float tanf(float x) -{ - return (float) tan((double)x); -} -#endif - -#ifndef HAVE_SINHF -float sinhf(float x) -{ - return (float) sinh((double)x); -} -#endif - -#ifndef HAVE_COSHF -float coshf(float x) -{ - return (float) cosh((double)x); -} -#endif - -#ifndef HAVE_TANHF -float tanhf(float x) -{ - return (float) tanh((double)x); -} -#endif - -#ifndef HAVE_FABSF -float fabsf(float x) -{ - return (float) fabs((double)x); -} -#endif - -#ifndef HAVE_FLOORF -float floorf(float x) -{ - return (float) floor((double)x); -} -#endif - -#ifndef HAVE_CEILF -float ceilf(float x) -{ - return (float) ceil((double)x); -} -#endif - -#ifndef HAVE_SQRTF -float sqrtf(float x) -{ - return (float) sqrt((double)x); -} -#endif - -#ifndef HAVE_LOG10F -float log10f(float x) -{ - return (float) log10((double)x); -} -#endif - -#ifndef HAVE_LOGF -float logf(float x) -{ - return (float) log((double)x); -} -#endif - -#ifndef HAVE_EXPF -float expf(float x) -{ - return (float) exp((double)x); -} -#endif - -#ifndef HAVE_EXPM1F -float expm1f(float x) -{ - return (float) expm1((double)x); -} -#endif - -#ifndef HAVE_ASINF -float asinf(float x) -{ - return (float) asin((double)x); -} -#endif - -#ifndef HAVE_ACOSF -float acosf(float x) -{ - return (float) acos((double)x); -} -#endif - -#ifndef HAVE_ATANF -float atanf(float x) -{ - return (float) atan((double)x); -} -#endif - -#ifndef HAVE_RINTF -float rintf(float x) -{ - return (float) rint((double)x); -} -#endif - -#ifndef HAVE_EXPMF -float expmf(float x) -{ - return (float) expm((double)x); -} -#endif - -#ifndef HAVE_ATAN2F -float atan2f(float x, float y) -{ - return (float) atan2((double)x, (double) y); -} -#endif - -#ifndef HAVE_HYPOTF -float hypotf(float x, float y) -{ - return (float) hypot((double)x, (double) y); -} -#endif - -#ifndef HAVE_POWF -float powf(float x, float y) -{ - return (float) pow((double)x, (double) y); -} -#endif - -#ifndef HAVE_FMODF -float fmodf(float x, float y) -{ - return (float) fmod((double)x, (double) y); -} -#endif - -#ifndef HAVE_MODFF -float modff(float x, float *iptr) -{ double nx, niptr, y; nx = (double) x; y = modf(nx, &niptr); - *iptr = (float) niptr; - return (float) y; + *iptr = (@typ@) niptr; + return (@typ@) y; } #endif - +/**end repeat**/ From numpy-svn at scipy.org Thu Sep 4 10:37:34 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 09:37:34 -0500 (CDT) Subject: [Numpy-svn] r5759 - branches/clean_math_config/numpy/core/src Message-ID: <20080904143734.C9A2A39C02A@scipy.org> Author: cdavid Date: 2008-09-04 09:37:29 -0500 (Thu, 04 Sep 2008) New Revision: 5759 Added: branches/clean_math_config/numpy/core/src/math_c99.c.src Removed: branches/clean_math_config/numpy/core/src/math_c99.c Log: move C99 math stuff to a .src file. Deleted: branches/clean_math_config/numpy/core/src/math_c99.c =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-04 14:35:51 UTC (rev 5758) +++ branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-04 14:37:29 UTC (rev 5759) @@ -1,219 +0,0 @@ -/* - * A small module to implement missing C99 math capabilities required by numpy - * - * Please keep this independant of python as much as possible ! - */ - -/* - * Include python.h because it may modify math.h configuration, but we won't - * use any python code at all here - */ -#include "Python.h" -#include "config.h" -#include - -/* - * Basic functions, double version. Some old/weird platforms may not have those - * - * Original code by Konrad Hinsen. - */ -#ifndef HAVE_EXPM1 -double expm1(double x) -{ - double u = exp(x); - if (u == 1.0) { - return x; - } else if (u-1.0 == -1.0) { - return -1; - } else { - return (u-1.0) * x/log(u); - } -} -#endif - -#ifndef HAVE_LOG1P -double log1p(double x) -{ - double u = 1. + x; - if (u == 1.0) { - return x; - } else { - return log(u) * x / (u-1.); - } -} -#endif - -#ifndef HAVE_HYPOT -double hypot(double x, double y) -{ - double yx; - - x = fabs(x); - y = fabs(y); - if (x < y) { - double temp = x; - x = y; - y = temp; - } - if (x == 0.) - return 0.; - else { - yx = y/x; - return x*sqrt(1.+yx*yx); - } -} -#endif - -#ifndef HAVE_ACOSH -double acosh(double x) -{ - return 2*log(sqrt((x+1.0)/2)+sqrt((x-1.0)/2)); -} -#endif - -#ifndef HAVE_ASINH -double asinh(double xx) -{ - double x, d; - int sign; - if (xx < 0.0) { - sign = -1; - x = -xx; - } - else { - sign = 1; - x = xx; - } - if (x > 1e8) { - d = x; - } else { - d = sqrt(x*x + 1); - } - return sign*log1p(x*(1.0 + x/(d+1))); -} -#endif - -#ifndef HAVE_ATANH -static double atanh(double x) -{ - return 0.5*log1p(2.0*x/(1.0-x)); -} -#endif - -#ifndef HAVE_RINT -double rint(double x) -{ - double y, r; - - y = floor(x); - r = x - y; - - if (r > 0.5) goto rndup; - - /* Round to nearest even */ - if (r==0.5) { - r = y - 2.0*floor(0.5*y); - if (r==1.0) { - rndup: - y+=1.0; - } - } - return y; -} -#endif - -#ifndef HAVE_TRUNC -double trunc(double x) -{ - if (x < 0) { - return ceil(x); - } - else { - return floor(x); - } - -} -#endif - -/* - * if C99 extensions not available then define dummy functions that use the - * double versions for - * - * sin, cos, tan - * sinh, cosh, tanh, - * fabs, floor, ceil, rint, trunc - * sqrt, log10, log, exp - * asin, acos, atan, - * asinh, acosh, atanh - * - * hypot, atan2, pow, fmod, modf - * - * We assume the above are always available in their double versions. - */ - -/* - * One value argument function - */ - -/**begin repeat - - #kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,rint,trunc,sqrt,log10,log,exp,asin,acos,atan,asinh,acosh,atanh)*2# - #KIND=(SIN,COS,TAN,SINH,COSH,TANH,FABS,FLOOR,CEIL,RINT,TRUNC,SQRT,LOG10,LOG,EXP,ASIN,ACOS,ATAN,ASINH,ACOSH,ATANH)*2# - #typ=longdouble*21, float*21# - #c=l*21,f*21# - #C=L*21,F*21# - #TYPE=LONGDOUBLE*21, FLOAT*21# -*/ - -#ifndef HAVE_ at KIND@@C@ - at typ@ @kind@@c@(@typ@ x) -{ - return (@typ@) @kind@((double)x); -} -#endif -/**end repeat**/ - -/* - * Two values arguments function - */ - -/**begin repeat - - #kind=(atan2,hypot,pow,fmod)*2# - #KIND=(ATAN2,HYPOT,POW,FMOD)*2# - #typ=longdouble*4, float*4# - #c=l*4,f*4# - #C=L*4,F*4# - #TYPE=LONGDOUBLE*4,FLOAT*4# -*/ -#ifndef HAVE_ at KIND@@C@ - at typ@ @kind@@c@(@typ@ x, @typ@ y) -{ - return (@typ@) @kind@((double)x, (double) y); -} -#endif -/**end repeat**/ - -/* - * One value - one pointer argument function - */ - -/**begin repeat - #kind=modf*2# - #KIND=MODF*2# - #c=l,f# - #C=L,F# - #typ=longdouble, float# - #TYPE=LONGDOUBLE, FLOAT# -*/ -#ifndef HAVE_ at KIND@@C@ - at typ@ modf at c@(@typ@ x, @typ@ *iptr) -{ - double nx, niptr, y; - nx = (double) x; - y = modf(nx, &niptr); - *iptr = (@typ@) niptr; - return (@typ@) y; -} -#endif -/**end repeat**/ Copied: branches/clean_math_config/numpy/core/src/math_c99.c.src (from rev 5758, branches/clean_math_config/numpy/core/src/math_c99.c) =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-04 14:35:51 UTC (rev 5758) +++ branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-04 14:37:29 UTC (rev 5759) @@ -0,0 +1,219 @@ +/* + * A small module to implement missing C99 math capabilities required by numpy + * + * Please keep this independant of python as much as possible ! + */ + +/* + * Include python.h because it may modify math.h configuration, but we won't + * use any python code at all here + */ +#include "Python.h" +#include "config.h" +#include + +/* + * Basic functions, double version. Some old/weird platforms may not have those + * + * Original code by Konrad Hinsen. + */ +#ifndef HAVE_EXPM1 +double expm1(double x) +{ + double u = exp(x); + if (u == 1.0) { + return x; + } else if (u-1.0 == -1.0) { + return -1; + } else { + return (u-1.0) * x/log(u); + } +} +#endif + +#ifndef HAVE_LOG1P +double log1p(double x) +{ + double u = 1. + x; + if (u == 1.0) { + return x; + } else { + return log(u) * x / (u-1.); + } +} +#endif + +#ifndef HAVE_HYPOT +double hypot(double x, double y) +{ + double yx; + + x = fabs(x); + y = fabs(y); + if (x < y) { + double temp = x; + x = y; + y = temp; + } + if (x == 0.) + return 0.; + else { + yx = y/x; + return x*sqrt(1.+yx*yx); + } +} +#endif + +#ifndef HAVE_ACOSH +double acosh(double x) +{ + return 2*log(sqrt((x+1.0)/2)+sqrt((x-1.0)/2)); +} +#endif + +#ifndef HAVE_ASINH +double asinh(double xx) +{ + double x, d; + int sign; + if (xx < 0.0) { + sign = -1; + x = -xx; + } + else { + sign = 1; + x = xx; + } + if (x > 1e8) { + d = x; + } else { + d = sqrt(x*x + 1); + } + return sign*log1p(x*(1.0 + x/(d+1))); +} +#endif + +#ifndef HAVE_ATANH +static double atanh(double x) +{ + return 0.5*log1p(2.0*x/(1.0-x)); +} +#endif + +#ifndef HAVE_RINT +double rint(double x) +{ + double y, r; + + y = floor(x); + r = x - y; + + if (r > 0.5) goto rndup; + + /* Round to nearest even */ + if (r==0.5) { + r = y - 2.0*floor(0.5*y); + if (r==1.0) { + rndup: + y+=1.0; + } + } + return y; +} +#endif + +#ifndef HAVE_TRUNC +double trunc(double x) +{ + if (x < 0) { + return ceil(x); + } + else { + return floor(x); + } + +} +#endif + +/* + * if C99 extensions not available then define dummy functions that use the + * double versions for + * + * sin, cos, tan + * sinh, cosh, tanh, + * fabs, floor, ceil, rint, trunc + * sqrt, log10, log, exp + * asin, acos, atan, + * asinh, acosh, atanh + * + * hypot, atan2, pow, fmod, modf + * + * We assume the above are always available in their double versions. + */ + +/* + * One value argument function + */ + +/**begin repeat + + #kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,rint,trunc,sqrt,log10,log,exp,asin,acos,atan,asinh,acosh,atanh)*2# + #KIND=(SIN,COS,TAN,SINH,COSH,TANH,FABS,FLOOR,CEIL,RINT,TRUNC,SQRT,LOG10,LOG,EXP,ASIN,ACOS,ATAN,ASINH,ACOSH,ATANH)*2# + #typ=longdouble*21, float*21# + #c=l*21,f*21# + #C=L*21,F*21# + #TYPE=LONGDOUBLE*21, FLOAT*21# +*/ + +#ifndef HAVE_ at KIND@@C@ + at typ@ @kind@@c@(@typ@ x) +{ + return (@typ@) @kind@((double)x); +} +#endif +/**end repeat**/ + +/* + * Two values arguments function + */ + +/**begin repeat + + #kind=(atan2,hypot,pow,fmod)*2# + #KIND=(ATAN2,HYPOT,POW,FMOD)*2# + #typ=longdouble*4, float*4# + #c=l*4,f*4# + #C=L*4,F*4# + #TYPE=LONGDOUBLE*4,FLOAT*4# +*/ +#ifndef HAVE_ at KIND@@C@ + at typ@ @kind@@c@(@typ@ x, @typ@ y) +{ + return (@typ@) @kind@((double)x, (double) y); +} +#endif +/**end repeat**/ + +/* + * One value - one pointer argument function + */ + +/**begin repeat + #kind=modf*2# + #KIND=MODF*2# + #c=l,f# + #C=L,F# + #typ=longdouble, float# + #TYPE=LONGDOUBLE, FLOAT# +*/ +#ifndef HAVE_ at KIND@@C@ + at typ@ modf at c@(@typ@ x, @typ@ *iptr) +{ + double nx, niptr, y; + nx = (double) x; + y = modf(nx, &niptr); + *iptr = (@typ@) niptr; + return (@typ@) y; +} +#endif +/**end repeat**/ From numpy-svn at scipy.org Thu Sep 4 10:40:04 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 09:40:04 -0500 (CDT) Subject: [Numpy-svn] r5760 - branches/clean_math_config/numpy/core/src Message-ID: <20080904144004.42BDD39C02A@scipy.org> Author: cdavid Date: 2008-09-04 09:40:00 -0500 (Thu, 04 Sep 2008) New Revision: 5760 Modified: branches/clean_math_config/numpy/core/src/math_c99.c.src Log: Add expm1 function in c99 compat module. Modified: branches/clean_math_config/numpy/core/src/math_c99.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-04 14:37:29 UTC (rev 5759) +++ branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-04 14:40:00 UTC (rev 5760) @@ -142,7 +142,7 @@ * sin, cos, tan * sinh, cosh, tanh, * fabs, floor, ceil, rint, trunc - * sqrt, log10, log, exp + * sqrt, log10, log, exp, expm1 * asin, acos, atan, * asinh, acosh, atanh * @@ -157,12 +157,12 @@ /**begin repeat - #kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,rint,trunc,sqrt,log10,log,exp,asin,acos,atan,asinh,acosh,atanh)*2# - #KIND=(SIN,COS,TAN,SINH,COSH,TANH,FABS,FLOOR,CEIL,RINT,TRUNC,SQRT,LOG10,LOG,EXP,ASIN,ACOS,ATAN,ASINH,ACOSH,ATANH)*2# - #typ=longdouble*21, float*21# - #c=l*21,f*21# - #C=L*21,F*21# - #TYPE=LONGDOUBLE*21, FLOAT*21# + #kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,rint,trunc,sqrt,log10,log,exp,expm1,asin,acos,atan,asinh,acosh,atanh)*2# + #KIND=(SIN,COS,TAN,SINH,COSH,TANH,FABS,FLOOR,CEIL,RINT,TRUNC,SQRT,LOG10,LOG,EXP,EXPM1,ASIN,ACOS,ATAN,ASINH,ACOSH,ATANH)*2# + #typ=longdouble*22, float*22# + #c=l*22,f*22# + #C=L*22,F*22# + #TYPE=LONGDOUBLE*22, FLOAT*22# */ #ifndef HAVE_ at KIND@@C@ From numpy-svn at scipy.org Thu Sep 4 10:45:40 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 09:45:40 -0500 (CDT) Subject: [Numpy-svn] r5761 - in branches/clean_math_config/numpy/core: . src Message-ID: <20080904144540.0556339C02A@scipy.org> Author: cdavid Date: 2008-09-04 09:45:33 -0500 (Thu, 04 Sep 2008) New Revision: 5761 Modified: branches/clean_math_config/numpy/core/setup.py branches/clean_math_config/numpy/core/src/math_c99.c.src branches/clean_math_config/numpy/core/src/umathmodule.c.src Log: Use C99 math compatibility module. Completely broken for now, needs to update the configuration stage. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-04 14:40:00 UTC (rev 5760) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-04 14:45:33 UTC (rev 5761) @@ -293,6 +293,7 @@ config.add_extension('umath', sources = [generate_config_h, generate_numpyconfig_h, + join('src','math_c99.c.src'), join('src','umathmodule.c.src'), generate_umath_c, generate_ufunc_api, Modified: branches/clean_math_config/numpy/core/src/math_c99.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-04 14:40:00 UTC (rev 5760) +++ branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-04 14:45:33 UTC (rev 5761) @@ -1,18 +1,11 @@ /* + * vim:syntax=c * A small module to implement missing C99 math capabilities required by numpy * * Please keep this independant of python as much as possible ! */ /* - * Include python.h because it may modify math.h configuration, but we won't - * use any python code at all here - */ -#include "Python.h" -#include "config.h" -#include - -/* * Basic functions, double version. Some old/weird platforms may not have those * * Original code by Konrad Hinsen. Modified: branches/clean_math_config/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-04 14:40:00 UTC (rev 5760) +++ branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-04 14:45:33 UTC (rev 5761) @@ -18,336 +18,14 @@ ** BASIC MATH FUNCTIONS ** ***************************************************************************** */ +#include "math_c99.c" -/* A whole slew of basic math functions are provided originally - by Konrad Hinsen. */ - -#if !defined(__STDC__) && !defined(_MSC_VER) -extern double fmod (double, double); -extern double frexp (double, int *); -extern double ldexp (double, int); -extern double modf (double, double *); -#endif -#ifndef M_PI -#define M_PI 3.14159265358979323846264338328 -#endif - - -#if defined(DISTUTILS_USE_SDK) -/* win32 on AMD64 build architecture */ -/* See also http://projects.scipy.org/scipy/numpy/ticket/164 */ -#ifndef HAVE_FABSF -#ifdef fabsf -#undef fabsf -#endif -static float fabsf(float x) -{ - return (float)fabs((double)(x)); -} -#endif -#ifndef HAVE_HYPOTF -static float hypotf(float x, float y) -{ - return (float)hypot((double)(x), (double)(y)); -} -#endif -#ifndef HAVE_RINTF -#ifndef HAVE_RINT -static double rint (double x); -#endif -static float rintf(float x) -{ - return (float)rint((double)(x)); -} -#endif -#ifndef HAVE_FREXPF -static float frexpf(float x, int * i) -{ - return (float)frexp((double)(x), i); -} -#endif -#ifndef HAVE_LDEXPF -static float ldexpf(float x, int i) -{ - return (float)ldexp((double)(x), i); -} -#endif -#define tanhf nc_tanhf -#endif - -#ifndef HAVE_INVERSE_HYPERBOLIC -static double acosh(double x) -{ - return 2*log(sqrt((x+1.0)/2)+sqrt((x-1.0)/2)); -} - -double log1p(double); -static double asinh(double xx) -{ - double x, d; - int sign; - if (xx < 0.0) { - sign = -1; - x = -xx; - } - else { - sign = 1; - x = xx; - } - if (x > 1e8) { - d = x; - } else { - d = sqrt(x*x + 1); - } - return sign*log1p(x*(1.0 + x/(d+1))); -} - -static double atanh(double x) -{ - return 0.5*log1p(2.0*x/(1.0-x)); -} -#endif - -#if !defined(HAVE_INVERSE_HYPERBOLIC_FLOAT) -#ifdef HAVE_FLOAT_FUNCS -#ifdef log1pf -#undef log1pf -#endif -#ifdef logf -#undef logf -#endif -#ifdef sqrtf -#undef sqrtf -#endif -float log1pf(float); -#ifdef DISTUTILS_USE_SDK -DL_IMPORT(float) logf(float); -DL_IMPORT(float) sqrtf(float); -#else -/* should these be extern?: */ -float logf(float); -float sqrtf(float); -#endif -#ifdef acoshf -#undef acoshf -#endif -static float acoshf(float x) -{ - return 2*logf(sqrtf((x+1)/2)+sqrtf((x-1)/2)); -} - -#ifdef asinhf -#undef asinhf -#endif -static float asinhf(float xx) -{ - float x, d; - int sign; - if (xx < 0) { - sign = -1; - x = -xx; - } - else { - sign = 1; - x = xx; - } - if (x > 1e5) { - d = x; - } else { - d = sqrtf(x*x + 1); - } - return sign*log1pf(x*(1 + x/(d+1))); -} - -#ifdef atanhf -#undef atanhf -#endif -static float atanhf(float x) -{ - return log1pf(2*x/(1-x))/2; -} -#else -#ifdef acoshf -#undef acoshf -#endif -static float acoshf(float x) -{ - return (float)acosh((double)(x)); -} - -#ifdef asinhf -#undef asinhf -#endif -static float asinhf(float x) -{ - return (float)asinh((double)(x)); -} - -#ifdef atanhf -#undef atanhf -#endif -static float atanhf(float x) -{ - return (float)atanh((double)(x)); -} -#endif -#endif - - -#if !defined(HAVE_INVERSE_HYPERBOLIC_LONGDOUBLE) -#ifdef HAVE_LONGDOUBLE_FUNCS -#ifdef logl -#undef logl -#endif -#ifdef sqrtl -#undef sqrtl -#endif -#ifdef log1pl -#undef log1pl -#endif -longdouble logl(longdouble); -longdouble sqrtl(longdouble); -longdouble log1pl(longdouble); -#ifdef acoshl -#undef acoshl -#endif -static longdouble acoshl(longdouble x) -{ - return 2*logl(sqrtl((x+1.0)/2)+sqrtl((x-1.0)/2)); -} - -#ifdef asinhl -#undef asinhl -#endif -static longdouble asinhl(longdouble xx) -{ - longdouble x, d; - int sign; - if (xx < 0.0) { - sign = -1; - x = -xx; - } - else { - sign = 1; - x = xx; - } - if (x > 1e17) { - d = x; - } else { - d = sqrtl(x*x + 1); - } - return sign*log1pl(x*(1.0 + x/(d+1))); -} - -#ifdef atanhl -#undef atanhl -#endif -static longdouble atanhl(longdouble x) -{ - return 0.5*log1pl(2.0*x/(1.0-x)); -} - -#else - -#ifdef acoshl -#undef acoshl -#endif -static longdouble acoshl(longdouble x) -{ - return (longdouble)acosh((double)(x)); -} - -#ifdef asinhl -#undef asinhl -#endif -static longdouble asinhl(longdouble x) -{ - return (longdouble)asinh((double)(x)); -} - -#ifdef atanhl -#undef atanhl -#endif -static longdouble atanhl(longdouble x) -{ - return (longdouble)atanh((double)(x)); -} - -#endif -#endif - - -#ifdef HAVE_HYPOT -#if !defined(NeXT) && !defined(_MSC_VER) -extern double hypot(double, double); -#endif -#else -static double hypot(double x, double y) -{ - double yx; - - x = fabs(x); - y = fabs(y); - if (x < y) { - double temp = x; - x = y; - y = temp; - } - if (x == 0.) - return 0.; - else { - yx = y/x; - return x*sqrt(1.+yx*yx); - } -} -#endif - -#ifndef HAVE_RINT -/* needs cleanup */ -static double -rint(double x) -{ - double y, r; - - y = floor(x); - r = x - y; - - if (r > 0.5) goto rndup; - - /* Round to nearest even */ - if (r==0.5) { - r = y - 2.0*floor(0.5*y); - if (r==1.0) { - rndup: - y+=1.0; - } - } - return y; -} -#endif - /* - * Comment out trunc definition until build problems are fixed. + ***************************************************************************** + ** IEEE 754 FPU HANDLING ** + ***************************************************************************** */ -/* -#ifndef HAVE_TRUNC -static double -trunc(double x) -{ - if (x < 0) { - return ceil(x); - } - else { - return floor(x); - } -} -#endif -*/ - - - - /* Define isnan, isinf, isfinite, signbit if needed */ /* Use fpclassify if possible */ /* isnan, isinf -- @@ -463,168 +141,6 @@ return x * (M_PI/180.0L); } -/* First, the C functions that do the real work */ - -/* if C99 extensions not available then define dummy functions that use the - double versions for - - sin, cos, tan - sinh, cosh, tanh, - fabs, floor, ceil, fmod, sqrt, log10, log, exp, fabs - asin, acos, atan, - asinh, acosh, atanh - - hypot, atan2, pow -*/ - -/**begin repeat - - #kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,sqrt,log10,log,exp,asin,acos,atan,rint)*2# - #typ=longdouble*17, float*17# - #c=l*17,f*17# - #TYPE=LONGDOUBLE*17, FLOAT*17# -*/ - -#ifndef HAVE_ at TYPE@_FUNCS -#ifdef @kind@@c@ -#undef @kind@@c@ -#endif - at typ@ @kind@@c@(@typ@ x) { - return (@typ@) @kind@((double)x); -} -#endif -/**end repeat**/ - -/**begin repeat - - #kind=(atan2,hypot,pow,fmod)*2# - #typ=longdouble*4, float*4# - #c=l*4,f*4# - #TYPE=LONGDOUBLE*4,FLOAT*4# -*/ -#ifndef HAVE_ at TYPE@_FUNCS -#ifdef @kind@@c@ -#undef @kind@@c@ -#endif - at typ@ @kind@@c@(@typ@ x, @typ@ y) { - return (@typ@) @kind@((double)x, (double) y); -} -#endif -/**end repeat**/ - -/**begin repeat - #kind=modf*2# - #typ=longdouble, float# - #c=l,f# - #TYPE=LONGDOUBLE, FLOAT# -*/ -#ifndef HAVE_ at TYPE@_FUNCS -#ifdef modf at c@ -#undef modf at c@ -#endif - at typ@ modf at c@(@typ@ x, @typ@ *iptr) { - double nx, niptr, y; - nx = (double) x; - y = modf(nx, &niptr); - *iptr = (@typ@) niptr; - return (@typ@) y; -} -#endif -/**end repeat**/ - - - -#ifndef HAVE_LOG1P -double log1p(double x) -{ - double u = 1. + x; - if (u == 1.0) { - return x; - } else { - return log(u) * x / (u-1.); - } -} -#endif - -#if !defined(HAVE_LOG1P) || !defined(HAVE_LONGDOUBLE_FUNCS) -#ifdef log1pl -#undef log1pl -#endif -longdouble log1pl(longdouble x) -{ - longdouble u = 1. + x; - if (u == 1.0) { - return x; - } else { - return logl(u) * x / (u-1.); - } -} -#endif - -#if !defined(HAVE_LOG1P) || !defined(HAVE_FLOAT_FUNCS) -#ifdef log1pf -#undef log1pf -#endif -float log1pf(float x) -{ - float u = 1 + x; - if (u == 1) { - return x; - } else { - return logf(u) * x / (u-1); - } -} -#endif - -#ifndef HAVE_EXPM1 -static double expm1(double x) -{ - double u = exp(x); - if (u == 1.0) { - return x; - } else if (u-1.0 == -1.0) { - return -1; - } else { - return (u-1.0) * x/log(u); - } -} -#endif - -#if !defined(HAVE_EXPM1) || !defined(HAVE_LONGDOUBLE_FUNCS) -#ifdef expml1 -#undef expml1 -#endif -static longdouble expm1l(longdouble x) -{ - longdouble u = expl(x); - if (u == 1.0) { - return x; - } else if (u-1.0 == -1.0) { - return -1; - } else { - return (u-1.0) * x/logl(u); - } -} -#endif - -#if !defined(HAVE_EXPM1) || !defined(HAVE_FLOAT_FUNCS) -#ifdef expm1f -#undef expm1f -#endif -static float expm1f(float x) -{ - float u = expf(x); - if (u == 1) { - return x; - } else if (u-1 == -1) { - return -1; - } else { - return (u-1) * x/logf(u); - } -} -#endif - - /* ***************************************************************************** ** COMPLEX FUNCTIONS ** From numpy-svn at scipy.org Thu Sep 4 10:56:14 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 09:56:14 -0500 (CDT) Subject: [Numpy-svn] r5762 - in branches/clean_math_config: . doc doc/neps doc/numpybook doc/numpybook/comparison doc/numpybook/comparison/ctypes doc/numpybook/comparison/pyrex doc/numpybook/comparison/weave numpy numpy/core numpy/core/code_generators numpy/core/src numpy/core/tests numpy/distutils/command numpy/doc numpy/lib numpy/lib/tests numpy/ma numpy/testing tools/osxbuild tools/win32build Message-ID: <20080904145614.8775D39C02A@scipy.org> Author: cdavid Date: 2008-09-04 09:55:01 -0500 (Thu, 04 Sep 2008) New Revision: 5762 Added: branches/clean_math_config/doc/TESTS.txt branches/clean_math_config/doc/neps/math_config_clean.txt branches/clean_math_config/doc/neps/warnfix.txt Modified: branches/clean_math_config/ branches/clean_math_config/doc/DISTUTILS.txt branches/clean_math_config/doc/numpybook/comparison/ctypes/filter.py branches/clean_math_config/doc/numpybook/comparison/ctypes/interface.py branches/clean_math_config/doc/numpybook/comparison/pyrex/setup.py branches/clean_math_config/doc/numpybook/comparison/timing.py branches/clean_math_config/doc/numpybook/comparison/weave/filter.py branches/clean_math_config/doc/numpybook/comparison/weave/inline.py branches/clean_math_config/doc/numpybook/runcode.py branches/clean_math_config/numpy/core/code_generators/generate_umath.py branches/clean_math_config/numpy/core/memmap.py branches/clean_math_config/numpy/core/src/scalartypes.inc.src branches/clean_math_config/numpy/core/tests/test_regression.py branches/clean_math_config/numpy/distutils/command/scons.py branches/clean_math_config/numpy/doc/subclassing.py branches/clean_math_config/numpy/lib/_datasource.py branches/clean_math_config/numpy/lib/scimath.py branches/clean_math_config/numpy/lib/tests/test_format.py branches/clean_math_config/numpy/lib/ufunclike.py branches/clean_math_config/numpy/ma/core.py branches/clean_math_config/numpy/testing/nosetester.py branches/clean_math_config/numpy/testing/parametric.py branches/clean_math_config/numpy/version.py branches/clean_math_config/tools/osxbuild/build.py branches/clean_math_config/tools/osxbuild/install_and_test.py branches/clean_math_config/tools/win32build/build.py branches/clean_math_config/tools/win32build/prepare_bootstrap.py Log: Merged revisions 5738-5761 via svnmerge from http://svn.scipy.org/svn/numpy/trunk ........ r5739 | cdavid | 2008-09-01 21:50:46 +0900 (Mon, 01 Sep 2008) | 1 line Disable memmap test which crashes nose tests on cygwin. ........ r5740 | cdavid | 2008-09-01 22:07:30 +0900 (Mon, 01 Sep 2008) | 2 lines Fix unused variable warning in object_arrtype_new. ........ r5741 | cdavid | 2008-09-02 15:59:43 +0900 (Tue, 02 Sep 2008) | 5 lines Fix regression test #771 on 64 bits architecture. The test assumed an item was 4 bytes. Use itemsize instead of harcoding 4 bytes per item. ........ r5742 | jarrod.millman | 2008-09-03 05:13:17 +0900 (Wed, 03 Sep 2008) | 2 lines pulling out testing docs from distutils docs ........ r5743 | jarrod.millman | 2008-09-03 05:32:38 +0900 (Wed, 03 Sep 2008) | 2 lines reindenting prior to release ........ r5745 | jarrod.millman | 2008-09-03 08:52:37 +0900 (Wed, 03 Sep 2008) | 2 lines trunk is open for 1.3 development ........ r5748 | alan.mcintyre | 2008-09-03 14:10:39 +0900 (Wed, 03 Sep 2008) | 3 lines Fix __init__.py boilerplate example in DISTUTILS.txt, and moved content from SciPy wiki entry on testing guidelines to TESTS.txt. ........ r5749 | alan.mcintyre | 2008-09-03 15:11:28 +0900 (Wed, 03 Sep 2008) | 3 lines Updated TESTS.txt to actually be ReST. Capitalization nitpickery in DISTUTILS.txt: 'Scipy' -> 'SciPy' ........ r5750 | alan.mcintyre | 2008-09-03 16:49:59 +0900 (Wed, 03 Sep 2008) | 2 lines Added section discussing using subclassing to create similar tests. ........ r5751 | pierregm | 2008-09-04 01:48:52 +0900 (Thu, 04 Sep 2008) | 1 line docstring update ........ r5752 | cdavid | 2008-09-04 01:54:37 +0900 (Thu, 04 Sep 2008) | 1 line Start a nep for warn-free numpy build. ........ r5753 | cdavid | 2008-09-04 22:31:24 +0900 (Thu, 04 Sep 2008) | 1 line Update the warnfix nep. ........ r5754 | cdavid | 2008-09-04 22:36:53 +0900 (Thu, 04 Sep 2008) | 1 line Start a nep for cleaning the math configuration. ........ r5755 | cdavid | 2008-09-04 22:49:01 +0900 (Thu, 04 Sep 2008) | 1 line Update clean math config nep. ........ Property changes on: branches/clean_math_config ___________________________________________________________________ Name: svnmerge-integrated - /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5737 + /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5761 Modified: branches/clean_math_config/doc/DISTUTILS.txt =================================================================== --- branches/clean_math_config/doc/DISTUTILS.txt 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/doc/DISTUTILS.txt 2008-09-04 14:55:01 UTC (rev 5762) @@ -58,7 +58,7 @@ SciPy pure Python package example --------------------------------- -Below is an example of a minimal ``setup.py`` file for a pure Scipy package:: +Below is an example of a minimal ``setup.py`` file for a pure SciPy package:: #!/usr/bin/env python def configuration(parent_package='',top_path=None): @@ -399,7 +399,7 @@ The ``info.py`` file '''''''''''''''''''' -Scipy package import hooks assume that each package contains a +SciPy package import hooks assume that each package contains a ``info.py`` file. This file contains overall documentation about the package and variables defining the order of package imports, dependency relations between packages, etc. @@ -436,8 +436,8 @@ To speed up the import time and minimize memory usage, numpy uses ``ppimport`` hooks to transparently postpone importing large modules, -which might not be used during the Scipy session. In order to -have access to the documentation of all Scipy packages, including +which might not be used during the SciPy session. In order to +have access to the documentation of all SciPy packages, including postponed packages, the docstring from ``info.py`` is imported into ``__init__.py``. @@ -450,61 +450,10 @@ from info import __doc__ ... - from numpy.testing import NumpyTest - test = NumpyTest().test + from numpy.testing import Tester + test = Tester().test + bench = Tester().bench -The ``tests/`` directory -'''''''''''''''''''''''' - -Ideally, every Python code, extension module, or subpackage in Scipy -package directory should have the corresponding ``test_.py`` -file in ``tests/`` directory. This file should define classes -derived from the ``numpy.testing.TestCase`` class (or from -``unittest.TestCase``) and have names starting with ``test``. The methods -of these classes whose names contain ``test`` or start with ``bench`` are -automatically picked up by the test machinery. - -A minimal example of a ``test_yyy.py`` file that implements tests for -a NumPy package module ``numpy.xxx.yyy`` containing a function -``zzz()``, is shown below:: - - import sys - from numpy.testing import * - - # import xxx symbols - from numpy.xxx.yyy import zzz - - - class test_zzz(TestCase): - def test_simple(self, level=1): - assert zzz()=='Hello from zzz' - #... - - if __name__ == "__main__": - run_module_tests(file) - -Note that all classes that are inherited from ``TestCase`` class, are -automatically picked up by the test runner. - -``numpy.testing`` module provides also the following convenience -functions:: - - assert_equal(actual,desired,err_msg='',verbose=1) - assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=1) - assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=1) - assert_array_equal(x,y,err_msg='') - assert_array_almost_equal(x,y,decimal=6,err_msg='') - rand(*shape) # returns random array with a given shape - -To run all test scripts of the module ``xxx``, execute in Python: - - >>> import numpy - >>> numpy.xxx.test() - -To run only tests for ``xxx.yyy`` module, execute: - - >>> NumpyTest('xxx.yyy').test(level=1,verbosity=1) - Extra features in NumPy Distutils ''''''''''''''''''''''''''''''''' Copied: branches/clean_math_config/doc/TESTS.txt (from rev 5755, trunk/doc/TESTS.txt) Copied: branches/clean_math_config/doc/neps/math_config_clean.txt (from rev 5755, trunk/doc/neps/math_config_clean.txt) Copied: branches/clean_math_config/doc/neps/warnfix.txt (from rev 5755, trunk/doc/neps/warnfix.txt) Modified: branches/clean_math_config/doc/numpybook/comparison/ctypes/filter.py =================================================================== --- branches/clean_math_config/doc/numpybook/comparison/ctypes/filter.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/doc/numpybook/comparison/ctypes/filter.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -21,6 +21,3 @@ b = N.zeros_like(a) lib.dfilter2d(a, b, a.ctypes.strides, a.ctypes.shape) return b - - - Modified: branches/clean_math_config/doc/numpybook/comparison/ctypes/interface.py =================================================================== --- branches/clean_math_config/doc/numpybook/comparison/ctypes/interface.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/doc/numpybook/comparison/ctypes/interface.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -27,7 +27,7 @@ flags='aligned, contiguous,'\ 'writeable'), ctypes.POINTER(N.ctypeslib.c_intp), - ctypes.POINTER(N.ctypeslib.c_intp)] + ctypes.POINTER(N.ctypeslib.c_intp)] def select(dtype): if dtype.char in ['?bBhHf']: @@ -49,12 +49,9 @@ c = N.empty_like(a) func(a,b,c,a.size) return c - + def filter2d(a): a = N.require(a, float, ['ALIGNED']) b = N.zeros_like(a) lib.dfilter2d(a, b, a.ctypes.strides, a.ctypes.shape) return b - - - Modified: branches/clean_math_config/doc/numpybook/comparison/pyrex/setup.py =================================================================== --- branches/clean_math_config/doc/numpybook/comparison/pyrex/setup.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/doc/numpybook/comparison/pyrex/setup.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -16,8 +16,8 @@ include_dirs = [numpy.get_include()]) pyx_ext2 = Extension('blur', - ['blur.pyx'], - include_dirs = [numpy.get_include()]) + ['blur.pyx'], + include_dirs = [numpy.get_include()]) # Call the routine which does the real work Modified: branches/clean_math_config/doc/numpybook/comparison/timing.py =================================================================== --- branches/clean_math_config/doc/numpybook/comparison/timing.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/doc/numpybook/comparison/timing.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -51,13 +51,11 @@ path = sys.path for kind in ['f2py']:#['ctypes', 'pyrex', 'weave', 'f2py']: - res[kind] = [] - sys.path = ['/Users/oliphant/numpybook/%s' % (kind,)] + path - print sys.path - for n in N: - print "%s - %d" % (kind, n) - t = timeit.Timer(eval('%s_run'%kind), eval('%s_pre %% (%d,%d)'%(kind,n,n))) - mytime = min(t.repeat(3,100)) - res[kind].append(mytime) - - + res[kind] = [] + sys.path = ['/Users/oliphant/numpybook/%s' % (kind,)] + path + print sys.path + for n in N: + print "%s - %d" % (kind, n) + t = timeit.Timer(eval('%s_run'%kind), eval('%s_pre %% (%d,%d)'%(kind,n,n))) + mytime = min(t.repeat(3,100)) + res[kind].append(mytime) Modified: branches/clean_math_config/doc/numpybook/comparison/weave/filter.py =================================================================== --- branches/clean_math_config/doc/numpybook/comparison/weave/filter.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/doc/numpybook/comparison/weave/filter.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -8,11 +8,11 @@ for(i=1;i', 'exec') try: res = eval(tstr, dic) - sys.stdout = sys.__stdout__ + sys.stdout = sys.__stdout__ except SyntaxError: try: res = None @@ -42,7 +42,7 @@ res = tempstr.getvalue() + '\n' + repr(res) if res != '': print "\nOutput is" - print res, + print res, return res # now find the code in the code segment @@ -75,8 +75,8 @@ if line != 'dummy': outlines.append(line) return "\n\\newline \n".join(outlines), end - + def runpycode(lyxstr, name='MyCode'): schobj = re.compile(r"\\layout %s\s+>>> " % name) outstr = cStringIO.StringIO() @@ -85,7 +85,7 @@ for it in schobj.finditer(lyxstr): indx.extend([it.start(), it.end()]) num += 1 - + if num == 0: print "Nothing found for %s" % name return lyxstr @@ -103,14 +103,14 @@ for k in range(num): # first write everything up to the start of the code segment substr = lyxstr[start:indx[2*k]] - outstr.write(substr) + outstr.write(substr) if start > 0: mat = newre.search(substr) # if PYNEW found, then start a new namespace if mat: edic = {} exec 'from numpy import *' in edic - exec 'set_printoptions(linewidth=65)' in edic + exec 'set_printoptions(linewidth=65)' in edic # now find the code in the code segment # endoutput will contain the index just past any output # already present in the lyx string. Modified: branches/clean_math_config/numpy/core/code_generators/generate_umath.py =================================================================== --- branches/clean_math_config/numpy/core/code_generators/generate_umath.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/core/code_generators/generate_umath.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -673,10 +673,10 @@ mlist = [] docstring = textwrap.dedent(uf.docstring).strip() docstring = docstring.encode('string-escape').replace(r'"', r'\"') - # Split the docstring because some compilers (like MS) do not like big - # string literal in C code. We split at endlines because textwrap.wrap - # do not play well with \n - docstring = '\\n\"\"'.join(docstring.split(r"\n")) + # Split the docstring because some compilers (like MS) do not like big + # string literal in C code. We split at endlines because textwrap.wrap + # do not play well with \n + docstring = '\\n\"\"'.join(docstring.split(r"\n")) mlist.append(\ r"""f = PyUFunc_FromFuncAndData(%s_functions, %s_data, %s_signatures, %d, %d, %d, %s, "%s", Modified: branches/clean_math_config/numpy/core/memmap.py =================================================================== --- branches/clean_math_config/numpy/core/memmap.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/core/memmap.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -74,7 +74,7 @@ Given a memmap ``fp``, ``isinstance(fp, numpy.ndarray)`` returns ``True``. - Notes + Notes ----- Memory-mapped arrays use the the Python memory-map object which Modified: branches/clean_math_config/numpy/core/src/scalartypes.inc.src =================================================================== --- branches/clean_math_config/numpy/core/src/scalartypes.inc.src 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/core/src/scalartypes.inc.src 2008-09-04 14:55:01 UTC (rev 5762) @@ -1899,8 +1899,10 @@ PyObject *robj; PyObject *arr; PyArray_Descr *typecode = NULL; +#if !(@default@ == 2) int itemsize; void *dest, *src; +#endif /* allow base-class (if any) to do conversion */ /* If successful, this will jump to finish: */ Modified: branches/clean_math_config/numpy/core/tests/test_regression.py =================================================================== --- branches/clean_math_config/numpy/core/tests/test_regression.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/core/tests/test_regression.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -847,7 +847,7 @@ """Ticket #771: strides are not set correctly when reshaping 0-sized arrays""" b = np.indices((0,3,4)).T.reshape(-1,3) - assert_equal(b.strides, (12, 4)) + assert_equal(b.strides, (3 * b.itemsize, b.itemsize)) def test_object_array_refcounting(self, level=rlevel): """Ticket #633""" Modified: branches/clean_math_config/numpy/distutils/command/scons.py =================================================================== --- branches/clean_math_config/numpy/distutils/command/scons.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/distutils/command/scons.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -287,11 +287,11 @@ self.post_hooks = [] self.pkg_names = [] - # To avoid trouble, just don't do anything if no sconscripts are used. - # This is useful when for example f2py uses numpy.distutils, because - # f2py does not pass compiler information to scons command, and the - # compilation setup below can crash in some situation. - if len(self.sconscripts) > 0: + # To avoid trouble, just don't do anything if no sconscripts are used. + # This is useful when for example f2py uses numpy.distutils, because + # f2py does not pass compiler information to scons command, and the + # compilation setup below can crash in some situation. + if len(self.sconscripts) > 0: # Try to get the same compiler than the ones used by distutils: this is # non trivial because distutils and scons have totally different # conventions on this one (distutils uses PATH from user's environment, Modified: branches/clean_math_config/numpy/doc/subclassing.py =================================================================== --- branches/clean_math_config/numpy/doc/subclassing.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/doc/subclassing.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -7,7 +7,7 @@ ------- This page is based with thanks on the wiki page on subclassing by Pierre -Gerard-Marchant - http://www.scipy.org/Subclasses. +Gerard-Marchant - http://www.scipy.org/Subclasses. Introduction ------------ @@ -40,21 +40,21 @@ To allow subclassing, and views of subclasses, ndarray uses the ndarray ``__new__`` method for the main work of object initialization, -rather then the more usual ``__init__`` method. +rather then the more usual ``__init__`` method. ``__new__`` and ``__init__`` ============================ ``__new__`` is a standard python method, and, if present, is called before ``__init__`` when we create a class instance. Consider the -following:: +following:: class C(object): def __new__(cls, *args): - print 'Args in __new__:', args - return object.__new__(cls, *args) + print 'Args in __new__:', args + return object.__new__(cls, *args) def __init__(self, *args): - print 'Args in __init__:', args + print 'Args in __init__:', args C('hello') @@ -75,7 +75,7 @@ As you can see, the object can be initialized in the ``__new__`` method or the ``__init__`` method, or both, and in fact ndarray does not have an ``__init__`` method, because all the initialization is -done in the ``__new__`` method. +done in the ``__new__`` method. Why use ``__new__`` rather than just the usual ``__init__``? Because in some cases, as for ndarray, we want to be able to return an object @@ -83,21 +83,21 @@ class C(object): def __new__(cls, *args): - print 'cls is:', cls - print 'Args in __new__:', args - return object.__new__(cls, *args) + print 'cls is:', cls + print 'Args in __new__:', args + return object.__new__(cls, *args) def __init__(self, *args): - print 'self is :', self - print 'Args in __init__:', args + print 'self is :', self + print 'Args in __init__:', args class D(C): def __new__(cls, *args): - print 'D cls is:', cls - print 'D args in __new__:', args - return C.__new__(C, *args) + print 'D cls is:', cls + print 'D args in __new__:', args + return C.__new__(C, *args) def __init__(self, *args): - print 'D self is :', self - print 'D args in __init__:', args + print 'D self is :', self + print 'D args in __init__:', args D('hello') @@ -131,7 +131,7 @@ ``__new__`` method knows nothing of what we have done in our own ``__new__`` method in order to set attributes, and so on. (Aside - why not call ``obj = subdtype.__new__(...`` then? Because we may not -have a ``__new__`` method with the same call signature). +have a ``__new__`` method with the same call signature). So, when creating a new view object of our subclass, we need to be able to set any extra attributes from the original object of our @@ -153,21 +153,21 @@ class InfoArray(np.ndarray): def __new__(subtype, shape, dtype=float, buffer=None, offset=0, - strides=None, order=None, info=None): - # Create the ndarray instance of our type, given the usual - # input arguments. This will call the standard ndarray - # constructor, but return an object of our type - obj = np.ndarray.__new__(subtype, shape, dtype, buffer, offset, strides, - order) - # add the new attribute to the created instance - obj.info = info - # Finally, we must return the newly created object: - return obj + strides=None, order=None, info=None): + # Create the ndarray instance of our type, given the usual + # input arguments. This will call the standard ndarray + # constructor, but return an object of our type + obj = np.ndarray.__new__(subtype, shape, dtype, buffer, offset, strides, + order) + # add the new attribute to the created instance + obj.info = info + # Finally, we must return the newly created object: + return obj def __array_finalize__(self,obj): - # reset the attribute from passed original object - self.info = getattr(obj, 'info', None) - # We do not need to return anything + # reset the attribute from passed original object + self.info = getattr(obj, 'info', None) + # We do not need to return anything obj = InfoArray(shape=(3,), info='information') print type(obj) @@ -200,18 +200,18 @@ class RealisticInfoArray(np.ndarray): def __new__(cls, input_array, info=None): - # Input array is an already formed ndarray instance - # We first cast to be our class type - obj = np.asarray(input_array).view(cls) - # add the new attribute to the created instance - obj.info = info - # Finally, we must return the newly created object: - return obj + # Input array is an already formed ndarray instance + # We first cast to be our class type + obj = np.asarray(input_array).view(cls) + # add the new attribute to the created instance + obj.info = info + # Finally, we must return the newly created object: + return obj def __array_finalize__(self,obj): - # reset the attribute from passed original object - self.info = getattr(obj, 'info', None) - # We do not need to return anything + # reset the attribute from passed original object + self.info = getattr(obj, 'info', None) + # We do not need to return anything arr = np.arange(5) obj = RealisticInfoArray(arr, info='information') Modified: branches/clean_math_config/numpy/lib/_datasource.py =================================================================== --- branches/clean_math_config/numpy/lib/_datasource.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/lib/_datasource.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -38,7 +38,7 @@ from shutil import rmtree # Using a class instead of a module-level dictionary -# to reduce the inital 'import numpy' overhead by +# to reduce the inital 'import numpy' overhead by # deferring the import of bz2 and gzip until needed # TODO: .zip support, .tar support? @@ -197,7 +197,7 @@ def _isurl(self, path): """Test if path is a net location. Tests the scheme and netloc.""" - + # We do this here to reduce the 'import numpy' initial import time. from urlparse import urlparse Modified: branches/clean_math_config/numpy/lib/scimath.py =================================================================== --- branches/clean_math_config/numpy/lib/scimath.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/lib/scimath.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -198,15 +198,15 @@ As the numpy.sqrt, this returns the principal square root of x, which is what most people mean when they use square root; the principal square root - of x is not any number z such as z^2 = x. + of x is not any number z such as z^2 = x. For positive numbers, the principal square root is defined as the positive - number z such as z^2 = x. + number z such as z^2 = x. The principal square root of -1 is i, the principal square root of any negative number -x is defined a i * sqrt(x). For any non zero complex number, it is defined by using the following branch cut: x = r e^(i t) with - r > 0 and -pi < t <= pi. The principal square root is then + r > 0 and -pi < t <= pi. The principal square root is then sqrt(r) e^(i t/2). """ x = _fix_real_lt_zero(x) Modified: branches/clean_math_config/numpy/lib/tests/test_format.py =================================================================== --- branches/clean_math_config/numpy/lib/tests/test_format.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/lib/tests/test_format.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -421,7 +421,7 @@ def test_memmap_roundtrip(): # XXX: test crashes nose on windows. Fix this - if not sys.platform == 'win32': + 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. @@ -434,13 +434,13 @@ 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() @@ -449,7 +449,7 @@ 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 Modified: branches/clean_math_config/numpy/lib/ufunclike.py =================================================================== --- branches/clean_math_config/numpy/lib/ufunclike.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/lib/ufunclike.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -10,12 +10,12 @@ """ Round x to nearest integer towards zero. """ x = nx.asanyarray(x) - if y is None: + if y is None: y = nx.zeros_like(x) y1 = nx.floor(x) y2 = nx.ceil(x) y[...] = nx.where(x >= 0, y1, y2) - return y + return y def isposinf(x, y=None): """ Modified: branches/clean_math_config/numpy/ma/core.py =================================================================== --- branches/clean_math_config/numpy/ma/core.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/ma/core.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -86,7 +86,7 @@ return newdoc = """ %s - + Notes ----- %s @@ -896,7 +896,7 @@ """ cond = make_mask(condition) a = np.array(a, copy=copy, subok=True) - + (cshape, ashape) = (cond.shape, a.shape) if cshape and cshape != ashape: raise IndexError("Inconsistant shape between the condition and the input"\ @@ -1817,18 +1817,33 @@ def compress(self, condition, axis=None, out=None): - """Return a where condition is True. - If condition is a MaskedArray, missing values are considered as False. + """ + Return `a` where condition is ``True``. + If condition is a `MaskedArray`, missing values are considered as ``False``. - Returns - ------- - A MaskedArray object. + Parameters + ---------- + condition : var + Boolean 1-d array selecting which entries to return. If len(condition) + is less than the size of a along the axis, then output is truncated + to length of condition array. + axis : {None, int}, optional + Axis along which the operation must be performed. + out : {None, ndarray}, optional + Alternative output array in which to place the result. It must have + the same shape as the expected output but the type will be cast if + necessary. - Notes - ----- - Please note the difference with compressed() ! - The output of compress has a mask, the output of compressed does not. + Returns + ------- + result : MaskedArray + A :class:`MaskedArray` object. + Warnings + -------- + Please note the difference with :meth:`compressed` ! + The output of :meth:`compress` has a mask, the output of :meth:`compressed` does not. + """ # Get the basic components (_data, _mask) = (self._data, self._mask) @@ -2038,9 +2053,10 @@ Returns ------- - A masked array where the mask is True where all data are - masked. If axis is None, returns either a scalar ot the - masked singleton if all values are masked. + result : MaskedArray + A masked array where the mask is True where all data are + masked. If axis is None, returns either a scalar ot the + masked singleton if all values are masked. """ m = self._mask @@ -2182,7 +2198,7 @@ Check if all of the elements of `a` are true. - Performs a logical_and over the given axis and returns the result. + Performs a :func:`logical_and` over the given axis and returns the result. Masked values are considered as True during computation. For convenience, the output array is masked where ALL the values along the current axis are masked: if the output would have been a scalar and that @@ -2344,10 +2360,8 @@ def cumsum(self, axis=None, dtype=None, out=None): - """a.cumsum(axis=None, dtype=None, out=None) - + """ Return the cumulative sum of the elements along the given axis. - The cumulative sum is calculated over the flattened array by default, otherwise over the specified axis. @@ -2358,20 +2372,24 @@ Parameters ---------- axis : {None, -1, int}, optional - Axis along which the sum is computed. The default - (`axis` = None) is to compute over the flattened array. + Axis along which the sum is computed. The default (`axis` = None) is to + compute over the flattened array. `axis` may be negative, in which case + it counts from the last to the first axis. dtype : {None, dtype}, optional - Determines the type of the returned array and of the accumulator - where the elements are summed. If dtype has the value None and - the type of a is an integer type of precision less than the default - platform integer, then the default platform integer precision is - used. Otherwise, the dtype is the same as that of a. + Type of the returned array and of the accumulator in which the + elements are summed. If `dtype` is not specified, it defaults + to the dtype of `a`, unless `a` has an integer dtype with a + precision less than that of the default platform integer. In + that case, the default platform integer is used. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. - WARNING : The mask is lost if out is not a valid MaskedArray ! + Warning + ------- + The mask is lost if out is not a valid :class:`MaskedArray` ! + Returns ------- cumsum : ndarray. @@ -2380,7 +2398,8 @@ Example ------- - >>> print np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]).cumsum() + >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]) + >>> print marr.cumsum() [0 1 3 -- -- -- 9 16 24 33] @@ -2401,8 +2420,7 @@ def prod(self, axis=None, dtype=None, out=None): - """a.prod(axis=None, dtype=None, out=None) - + """ Return the product of the array elements over the given axis. Masked elements are set to 1 internally for computation. @@ -2413,8 +2431,8 @@ product is over all the array elements. dtype : {None, dtype}, optional Determines the type of the returned array and of the accumulator - where the elements are multiplied. If dtype has the value None and - the type of a is an integer type of precision less than the default + where the elements are multiplied. If ``dtype`` has the value ``None`` + and the type of a is an integer type of precision less than the default platform integer, then the default platform integer precision is used. Otherwise, the dtype is the same as that of a. out : {None, array}, optional @@ -2473,10 +2491,7 @@ def cumprod(self, axis=None, dtype=None, out=None): """ - a.cumprod(axis=None, dtype=None, out=None) - Return the cumulative product of the elements along the given axis. - The cumulative product is taken over the flattened array by default, otherwise over the specified axis. @@ -2491,21 +2506,24 @@ (`axis` = None) is to compute over the flattened array. dtype : {None, dtype}, optional Determines the type of the returned array and of the accumulator - where the elements are multiplied. If dtype has the value None and - the type of a is an integer type of precision less than the default + where the elements are multiplied. If ``dtype`` has the value ``None`` and + the type of ``a`` is an integer type of precision less than the default platform integer, then the default platform integer precision is - used. Otherwise, the dtype is the same as that of a. + used. Otherwise, the dtype is the same as that of ``a``. out : ndarray, optional Alternative output array in which to place the result. It must have the same shape and buffer length as the expected output but the type will be cast if necessary. - WARNING : The mask is lost if out is not a valid MaskedArray ! + Warning + ------- + The mask is lost if out is not a valid MaskedArray ! + Returns ------- - cumprod : ndarray. - A new array holding the result is returned unless out is - specified, in which case a reference to out is returned. + cumprod : ndarray + A new array holding the result is returned unless out is specified, + in which case a reference to out is returned. Notes ----- @@ -2524,43 +2542,7 @@ def mean(self, axis=None, dtype=None, out=None): - """a.mean(axis=None, dtype=None, out=None) -> mean - - Returns the average of the array elements. The average is taken over the - flattened array by default, otherwise over the specified axis. - - Parameters - ---------- - axis : integer - Axis along which the means are computed. The default is - to compute the mean of the flattened array. - dtype : type - Type to use in computing the means. For arrays of - integer type the default is float32, for arrays of float types it - is the same as the array type. - out : ndarray - Alternative output array in which to place the result. It must have - the same shape as the expected output but the type will be cast if - necessary. - - Returns - ------- - mean : The return type varies, see above. - A new array holding the result is returned unless out is specified, - in which case a reference to out is returned. - - See Also - -------- - var : variance - std : standard deviation - - Notes - ----- - The mean is the sum of the elements along the axis divided by the - number of elements. - - - """ + "" if self._mask is nomask: result = super(MaskedArray, self).mean(axis=axis, dtype=dtype) else: @@ -2576,21 +2558,22 @@ outmask.flat = getattr(result, '_mask', nomask) return out return result + mean.__doc__ = ndarray.mean.__doc__ def anom(self, axis=None, dtype=None): - """Return the anomalies (deviations from the average) along - the given axis. + """ + Return the anomalies (deviations from the average) along the given axis. - Parameters - ---------- - axis : int, optional - Axis along which to perform the operation. - If None, applies to a flattened version of the array. - dtype : {dtype}, optional - Datatype for the intermediary computation. If not - given, the current dtype is used instead. + Parameters + ---------- + axis : int, optional + Axis along which to perform the operation. + If None, applies to a flattened version of the array. + dtype : {dtype}, optional + Datatype for the intermediary computation. + If not given, the current dtype is used instead. - """ + """ m = self.mean(axis, dtype) if not axis: return (self - m) @@ -2598,50 +2581,7 @@ return (self - expand_dims(m,axis)) def var(self, axis=None, dtype=None, out=None, ddof=0): - """a.var(axis=None, dtype=None, out=None, ddof=0) -> variance - - Returns the variance of the array elements, a measure of the spread of a - distribution. The variance is computed for the flattened array by default, - otherwise over the specified axis. - - Parameters - ---------- - axis : integer - Axis along which the variance is computed. The default is to - compute the variance of the flattened array. - dtype : data-type - Type to use in computing the variance. For arrays of integer type - the default is float32, for arrays of float types it is the same as - the array type. - out : ndarray - Alternative output array in which to place the result. It must have - the same shape as the expected output but the type will be cast if - necessary. - ddof : {0, integer}, - Means Delta Degrees of Freedom. The divisor used in calculation is - N - ddof. - - Returns - ------- - variance : The return type varies, see above. - A new array holding the result is returned unless out is specified, - in which case a reference to out is returned. - - See Also - -------- - std : standard deviation - mean: average - - Notes - ----- - The variance is the average of the squared deviations from the mean, - i.e. var = mean(abs(x - x.mean())**2). The mean is computed by - dividing by N-ddof, where N is the number of elements. The argument - ddof defaults to zero; for an unbiased estimate supply ddof=1. Note - that for complex numbers the absolute value is taken before squaring, - so that the result is always real and nonnegative. - - """ + "" # Easy case: nomask, business as usual if self._mask is nomask: return self._data.var(axis=axis, dtype=dtype, out=out, ddof=ddof) @@ -2675,52 +2615,11 @@ out.__setmask__(dvar.mask) return out return dvar + var.__doc__ = np.var.__doc__ - def std(self, axis=None, dtype=None, out=None, ddof=0): - """a.std(axis=None, dtype=None, out=None, ddof=0) - Returns the standard deviation of the array elements, a measure of the - spread of a distribution. The standard deviation is computed for the - flattened array by default, otherwise over the specified axis. - - Parameters - ---------- - axis : integer - Axis along which the standard deviation is computed. The default is - to compute the standard deviation of the flattened array. - dtype : type - Type to use in computing the standard deviation. For arrays of - integer type the default is float32, for arrays of float types it - is the same as the array type. - out : ndarray - Alternative output array in which to place the result. It must have - the same shape as the expected output but the type will be cast if - necessary. - ddof : {0, integer} - Means Delta Degrees of Freedom. The divisor used in calculations - is N-ddof. - - Returns - ------- - standard deviation : The return type varies, see above. - A new array holding the result is returned unless out is specified, - in which case a reference to out is returned. - - See Also - -------- - var : variance - mean : average - - Notes - ----- - The standard deviation is the square root of the average of the squared - deviations from the mean, i.e. var = sqrt(mean(abs(x - x.mean())**2)). The - computed standard deviation is computed by dividing by the number of - elements, N-ddof. The option ddof defaults to zero, that is, a biased - estimate. Note that for complex numbers std takes the absolute value before - squaring, so that the result is always real and nonnegative. - - """ + def std(self, axis=None, dtype=None, out=None, ddof=0): + "" dvar = self.var(axis=axis,dtype=dtype,out=out, ddof=ddof) if dvar is not masked: dvar = sqrt(dvar) @@ -2728,6 +2627,7 @@ out **= 0.5 return out return dvar + std.__doc__ = np.std.__doc__ #............................................ def round(self, decimals=0, out=None): @@ -2928,8 +2828,7 @@ #............................................ def min(self, axis=None, out=None, fill_value=None): - """a.min(axis=None, out=None, fill_value=None) - + """ Return the minimum along a given axis. Parameters @@ -2938,11 +2837,11 @@ Axis along which to operate. By default, ``axis`` is None and the flattened input is used. out : array_like, optional - Alternative output array in which to place the result. Must - be of the same shape and buffer length as the expected output. + Alternative output array in which to place the result. Must be of + the same shape and buffer length as the expected output. fill_value : {var}, optional Value used to fill in the masked values. - If None, use the output of minimum_fill_value(). + If None, use the output of `minimum_fill_value`. Returns ------- @@ -2950,6 +2849,11 @@ New array holding the result. If ``out`` was specified, ``out`` is returned. + See Also + -------- + minimum_fill_value + Returns the minimum filling value for a given datatype. + """ _mask = ndarray.__getattribute__(self, '_mask') newmask = _mask.all(axis=axis) @@ -3008,6 +2912,11 @@ New array holding the result. If ``out`` was specified, ``out`` is returned. + See Also + -------- + maximum_fill_value + Returns the maximum filling value for a given datatype. + """ _mask = ndarray.__getattribute__(self, '_mask') newmask = _mask.all(axis=axis) @@ -3649,7 +3558,8 @@ return def transpose(a, axes=None): - """Return a view of the array with dimensions permuted according to axes, + """ + Return a view of the array with dimensions permuted according to axes, as a masked array. If ``axes`` is None (default), the output view has reversed @@ -3865,7 +3775,7 @@ if len(fb.shape) == 0: fb.shape = (1,) return np.inner(fa, fb).view(MaskedArray) -inner.__doc__ = doc_note(np.inner.__doc__, +inner.__doc__ = doc_note(np.inner.__doc__, "Masked values are replaced by 0.") innerproduct = inner @@ -3953,7 +3863,8 @@ #---- --- Pickling --- #####-------------------------------------------------------------------------- def dump(a,F): - """Pickle the MaskedArray `a` to the file `F`. `F` can either be + """ + Pickle the MaskedArray `a` to the file `F`. `F` can either be the handle of an exiting file, or a string representing a file name. @@ -3963,15 +3874,16 @@ return cPickle.dump(a,F) def dumps(a): - """Return a string corresponding to the pickling of the - MaskedArray. + """ + Return a string corresponding to the pickling of the MaskedArray. """ return cPickle.dumps(a) def load(F): - """Wrapper around ``cPickle.load`` which accepts either a - file-like object or a filename. + """ + Wrapper around ``cPickle.load`` which accepts either a file-like object + or a filename. """ if not hasattr(F, 'readline'): Modified: branches/clean_math_config/numpy/testing/nosetester.py =================================================================== --- branches/clean_math_config/numpy/testing/nosetester.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/testing/nosetester.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -164,8 +164,8 @@ pyversion = sys.version.replace('\n','') print "Python version %s" % pyversion print "nose version %d.%d.%d" % nose.__versioninfo__ - + def test(self, label='fast', verbose=1, extra_argv=None, doctests=False, coverage=False, **kwargs): ''' Run tests for module using nose Modified: branches/clean_math_config/numpy/testing/parametric.py =================================================================== --- branches/clean_math_config/numpy/testing/parametric.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/testing/parametric.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -61,9 +61,9 @@ _shareParTestPrefix = 'testsp' def __init__(self, methodName = 'runTest'): - warnings.warn("ParametricTestCase will be removed in the next NumPy " + warnings.warn("ParametricTestCase will be removed in the next NumPy " "release", DeprecationWarning) - unittest.TestCase.__init__(self, methodName) + unittest.TestCase.__init__(self, methodName) def exec_test(self,test,args,result): """Execute a single test. Returns a success boolean""" Modified: branches/clean_math_config/numpy/version.py =================================================================== --- branches/clean_math_config/numpy/version.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/numpy/version.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -1,4 +1,4 @@ -version='1.2.0' +version='1.3.0' release=False if not release: Modified: branches/clean_math_config/tools/osxbuild/build.py =================================================================== --- branches/clean_math_config/tools/osxbuild/build.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/tools/osxbuild/build.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -36,7 +36,7 @@ cmd = 'sudo chown -R %s %s' % (getuser(), DIST_DIR) shellcmd(cmd) shutil.rmtree(DIST_DIR) - + def build_dist(): print 'Building distribution... (using sudo)' cmd = 'sudo python setupegg.py bdist_mpkg' @@ -67,7 +67,7 @@ print 'Reverting README.txt...' cmd = 'svn revert %s' % DEV_README shellcmd(cmd) - + def shellcmd(cmd, verbose=True): """Call a shell command.""" if verbose: @@ -80,7 +80,7 @@ %s """ % str(err) raise Exception(msg) - + def build(): # update end-user documentation copy_readme() @@ -99,6 +99,6 @@ os.chdir(cwd) # restore developer documentation revert_readme() - + if __name__ == '__main__': build() Modified: branches/clean_math_config/tools/osxbuild/install_and_test.py =================================================================== --- branches/clean_math_config/tools/osxbuild/install_and_test.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/tools/osxbuild/install_and_test.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -14,7 +14,7 @@ """Add color to this print output.""" clrmsg = clrgreen + msg + clrnull print clrmsg - + distdir = os.path.join(SRC_DIR, DIST_DIR) # Find the package and build abspath to it Modified: branches/clean_math_config/tools/win32build/build.py =================================================================== --- branches/clean_math_config/tools/win32build/build.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/tools/win32build/build.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -80,7 +80,7 @@ if not os.path.exists("binaries"): os.makedirs("binaries") - shutil.move(os.path.join('dist', get_windist_exec(pyver)), + shutil.move(os.path.join('dist', get_windist_exec(pyver)), os.path.join("binaries", get_binary_name(arch))) def get_numpy_version(): @@ -110,7 +110,7 @@ if __name__ == '__main__': from optparse import OptionParser parser = OptionParser() - parser.add_option("-a", "--arch", dest="arch", + parser.add_option("-a", "--arch", dest="arch", help = "Architecture to build (sse2, sse3, nosse, etc...)") parser.add_option("-p", "--pyver", dest="pyver", help = "Python version (2.4, 2.5, etc...)") Modified: branches/clean_math_config/tools/win32build/prepare_bootstrap.py =================================================================== --- branches/clean_math_config/tools/win32build/prepare_bootstrap.py 2008-09-04 14:45:33 UTC (rev 5761) +++ branches/clean_math_config/tools/win32build/prepare_bootstrap.py 2008-09-04 14:55:01 UTC (rev 5762) @@ -79,7 +79,7 @@ version = subprocess.Popen(['python', '-c', 'import __builtin__; __builtin__.__NUMPY_SETUP__ = True; from numpy.version import version;print version'], stdout = subprocess.PIPE).communicate()[0] version = version.strip() if 'dev' in version: - out = subprocess.Popen(['svn', 'info'], stdout = subprocess.PIPE).communicate()[0] + out = subprocess.Popen(['svn', 'info'], stdout = subprocess.PIPE).communicate()[0] r = re.compile('Revision: ([0-9]+)') svnver = None for line in out.split('\n'): From numpy-svn at scipy.org Thu Sep 4 11:12:48 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 10:12:48 -0500 (CDT) Subject: [Numpy-svn] r5763 - branches/clean_math_config/numpy/core Message-ID: <20080904151248.9407039C02D@scipy.org> Author: cdavid Date: 2008-09-04 10:12:45 -0500 (Thu, 04 Sep 2008) New Revision: 5763 Modified: branches/clean_math_config/numpy/core/setup.py Log: put the setup code to check for match cap in a separate function. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-04 14:55:01 UTC (rev 5762) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-04 15:12:45 UTC (rev 5763) @@ -49,6 +49,26 @@ nosmp = 0 return nosmp == 1 +def check_math_capabilities(config, moredefs, mathlibs): + def check_func(func_name): + return config.check_func(func_name, libraries=mathlibs, decl=True) + + def name_to_defsymb(name): + return "HAVE_%s" % name.upper() + + mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", + "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", "acos", + "atan"] + + for f in mandatory_funcs: + if not check_func(f): + raise SystemError("Function %s is mandatory to build numpy." % f) + moredefs.append(name_to_defsymb(f)) + +# for func_name, defsymbol in FUNCTIONS_TO_CHECK: +# if check_func(func_name): +# moredefs.append(defsymbol) + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration,dot_join from numpy.distutils.system_info import get_info, default_lib_dirs @@ -106,15 +126,8 @@ ext.libraries.extend(mathlibs) moredefs.append(('MATHLIB',','.join(mathlibs))) - def check_func(func_name): - return config_cmd.check_func(func_name, - libraries=mathlibs, decl=False, - headers=['math.h']) + check_math_capabilities(config_cmd, moredefs, mathlibs) - for func_name, defsymbol in FUNCTIONS_TO_CHECK: - if check_func(func_name): - moredefs.append(defsymbol) - if is_npy_no_signal(): moredefs.append('__NPY_PRIVATE_NO_SIGNAL') From numpy-svn at scipy.org Thu Sep 4 11:32:00 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 10:32:00 -0500 (CDT) Subject: [Numpy-svn] r5764 - branches/clean_math_config/numpy/core Message-ID: <20080904153200.8855839C02A@scipy.org> Author: cdavid Date: 2008-09-04 10:31:57 -0500 (Thu, 04 Sep 2008) New Revision: 5764 Modified: branches/clean_math_config/numpy/core/setup.py Log: Check for non-mandatory, basic, double functions. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-04 15:12:45 UTC (rev 5763) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-04 15:31:57 UTC (rev 5764) @@ -56,15 +56,27 @@ def name_to_defsymb(name): return "HAVE_%s" % name.upper() + # Mandatory functions: if not found, fail the build mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", "acos", "atan"] + # Standard functions which may not be available and for which we have a + # replacement implementation + # XXX: we do not test for hypot because python checks for it (HAVE_HYPOT in + # python.h... I wish they would clean their public headers someday) + optional_stdfuncs = ["expm1", "log1p", "acosh", "asinh", "atanh", + "rint", "trunc"] + for f in mandatory_funcs: if not check_func(f): raise SystemError("Function %s is mandatory to build numpy." % f) moredefs.append(name_to_defsymb(f)) + for f in optional_stdfuncs: + if check_func(f): + moredefs.append(name_to_defsymb(f)) + # for func_name, defsymbol in FUNCTIONS_TO_CHECK: # if check_func(func_name): # moredefs.append(defsymbol) From numpy-svn at scipy.org Thu Sep 4 11:32:32 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 10:32:32 -0500 (CDT) Subject: [Numpy-svn] r5765 - branches/clean_math_config/numpy/core Message-ID: <20080904153232.6EDFB39C02A@scipy.org> Author: cdavid Date: 2008-09-04 10:32:29 -0500 (Thu, 04 Sep 2008) New Revision: 5765 Modified: branches/clean_math_config/numpy/core/setup.py Log: Do not build math_c99.c, only set it as a dependency. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-04 15:31:57 UTC (rev 5764) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-04 15:32:29 UTC (rev 5765) @@ -288,6 +288,7 @@ join('src','arraymethods.c'), join('src','scalartypes.inc.src'), join('src','arraytypes.inc.src'), + join('src','math_c99.c.src'), join('src','_signbit.c'), join('src','_isnan.c'), join('src','ucsnarrow.c'), @@ -318,7 +319,6 @@ config.add_extension('umath', sources = [generate_config_h, generate_numpyconfig_h, - join('src','math_c99.c.src'), join('src','umathmodule.c.src'), generate_umath_c, generate_ufunc_api, From numpy-svn at scipy.org Thu Sep 4 11:39:44 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 10:39:44 -0500 (CDT) Subject: [Numpy-svn] r5766 - in branches/clean_math_config/numpy/core: . src Message-ID: <20080904153944.3E6B039C02A@scipy.org> Author: cdavid Date: 2008-09-04 10:39:38 -0500 (Thu, 04 Sep 2008) New Revision: 5766 Added: branches/clean_math_config/numpy/core/src/math_c99.c Modified: branches/clean_math_config/numpy/core/setup.py Log: Manually generate math_c99.c I did not find a way to generate math_c99.c from math_c99.src with distutils, so let's include the generated file for now. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-04 15:32:29 UTC (rev 5765) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-04 15:39:38 UTC (rev 5766) @@ -288,7 +288,6 @@ join('src','arraymethods.c'), join('src','scalartypes.inc.src'), join('src','arraytypes.inc.src'), - join('src','math_c99.c.src'), join('src','_signbit.c'), join('src','_isnan.c'), join('src','ucsnarrow.c'), @@ -327,6 +326,7 @@ ], depends = [join('src','ufuncobject.c'), generate_umath_py, + join('src','math_c99.c'), join(codegen_dir,'generate_ufunc_api.py'), ]+deps, ) Added: branches/clean_math_config/numpy/core/src/math_c99.c =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-04 15:32:29 UTC (rev 5765) +++ branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-04 15:39:38 UTC (rev 5766) @@ -0,0 +1,654 @@ + +/* + ***************************************************************************** + ** This file was autogenerated from a template DO NOT EDIT!!!! ** + ** Changes should be made to the original source (.src) file ** + ***************************************************************************** + */ + +#line 1 +/* + * vim:syntax=c + * A small module to implement missing C99 math capabilities required by numpy + * + * Please keep this independant of python as much as possible ! + */ + +/* + * Basic functions, double version. Some old/weird platforms may not have those + * + * Original code by Konrad Hinsen. + */ +#ifndef HAVE_EXPM1 +double expm1(double x) +{ + double u = exp(x); + if (u == 1.0) { + return x; + } else if (u-1.0 == -1.0) { + return -1; + } else { + return (u-1.0) * x/log(u); + } +} +#endif + +#ifndef HAVE_LOG1P +double log1p(double x) +{ + double u = 1. + x; + if (u == 1.0) { + return x; + } else { + return log(u) * x / (u-1.); + } +} +#endif + +#ifndef HAVE_HYPOT +double hypot(double x, double y) +{ + double yx; + + x = fabs(x); + y = fabs(y); + if (x < y) { + double temp = x; + x = y; + y = temp; + } + if (x == 0.) + return 0.; + else { + yx = y/x; + return x*sqrt(1.+yx*yx); + } +} +#endif + +#ifndef HAVE_ACOSH +double acosh(double x) +{ + return 2*log(sqrt((x+1.0)/2)+sqrt((x-1.0)/2)); +} +#endif + +#ifndef HAVE_ASINH +double asinh(double xx) +{ + double x, d; + int sign; + if (xx < 0.0) { + sign = -1; + x = -xx; + } + else { + sign = 1; + x = xx; + } + if (x > 1e8) { + d = x; + } else { + d = sqrt(x*x + 1); + } + return sign*log1p(x*(1.0 + x/(d+1))); +} +#endif + +#ifndef HAVE_ATANH +static double atanh(double x) +{ + return 0.5*log1p(2.0*x/(1.0-x)); +} +#endif + +#ifndef HAVE_RINT +double rint(double x) +{ + double y, r; + + y = floor(x); + r = x - y; + + if (r > 0.5) goto rndup; + + /* Round to nearest even */ + if (r==0.5) { + r = y - 2.0*floor(0.5*y); + if (r==1.0) { + rndup: + y+=1.0; + } + } + return y; +} +#endif + +#ifndef HAVE_TRUNC +double trunc(double x) +{ + if (x < 0) { + return ceil(x); + } + else { + return floor(x); + } + +} +#endif + +/* + * if C99 extensions not available then define dummy functions that use the + * double versions for + * + * sin, cos, tan + * sinh, cosh, tanh, + * fabs, floor, ceil, rint, trunc + * sqrt, log10, log, exp, expm1 + * asin, acos, atan, + * asinh, acosh, atanh + * + * hypot, atan2, pow, fmod, modf + * + * We assume the above are always available in their double versions. + */ + +/* + * One value argument function + */ + +#line 160 + +#ifndef HAVE_SINL +longdouble sinl(longdouble x) +{ + return (longdouble) sin((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_COSL +longdouble cosl(longdouble x) +{ + return (longdouble) cos((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_TANL +longdouble tanl(longdouble x) +{ + return (longdouble) tan((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_SINHL +longdouble sinhl(longdouble x) +{ + return (longdouble) sinh((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_COSHL +longdouble coshl(longdouble x) +{ + return (longdouble) cosh((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_TANHL +longdouble tanhl(longdouble x) +{ + return (longdouble) tanh((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_FABSL +longdouble fabsl(longdouble x) +{ + return (longdouble) fabs((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_FLOORL +longdouble floorl(longdouble x) +{ + return (longdouble) floor((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_CEILL +longdouble ceill(longdouble x) +{ + return (longdouble) ceil((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_RINTL +longdouble rintl(longdouble x) +{ + return (longdouble) rint((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_TRUNCL +longdouble truncl(longdouble x) +{ + return (longdouble) trunc((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_SQRTL +longdouble sqrtl(longdouble x) +{ + return (longdouble) sqrt((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_LOG10L +longdouble log10l(longdouble x) +{ + return (longdouble) log10((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_LOGL +longdouble logl(longdouble x) +{ + return (longdouble) log((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_EXPL +longdouble expl(longdouble x) +{ + return (longdouble) exp((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_EXPM1L +longdouble expm1l(longdouble x) +{ + return (longdouble) expm1((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ASINL +longdouble asinl(longdouble x) +{ + return (longdouble) asin((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ACOSL +longdouble acosl(longdouble x) +{ + return (longdouble) acos((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ATANL +longdouble atanl(longdouble x) +{ + return (longdouble) atan((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ASINHL +longdouble asinhl(longdouble x) +{ + return (longdouble) asinh((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ACOSHL +longdouble acoshl(longdouble x) +{ + return (longdouble) acosh((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ATANHL +longdouble atanhl(longdouble x) +{ + return (longdouble) atanh((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_SINF +float sinf(float x) +{ + return (float) sin((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_COSF +float cosf(float x) +{ + return (float) cos((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_TANF +float tanf(float x) +{ + return (float) tan((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_SINHF +float sinhf(float x) +{ + return (float) sinh((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_COSHF +float coshf(float x) +{ + return (float) cosh((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_TANHF +float tanhf(float x) +{ + return (float) tanh((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_FABSF +float fabsf(float x) +{ + return (float) fabs((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_FLOORF +float floorf(float x) +{ + return (float) floor((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_CEILF +float ceilf(float x) +{ + return (float) ceil((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_RINTF +float rintf(float x) +{ + return (float) rint((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_TRUNCF +float truncf(float x) +{ + return (float) trunc((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_SQRTF +float sqrtf(float x) +{ + return (float) sqrt((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_LOG10F +float log10f(float x) +{ + return (float) log10((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_LOGF +float logf(float x) +{ + return (float) log((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_EXPF +float expf(float x) +{ + return (float) exp((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_EXPM1F +float expm1f(float x) +{ + return (float) expm1((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ASINF +float asinf(float x) +{ + return (float) asin((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ACOSF +float acosf(float x) +{ + return (float) acos((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ATANF +float atanf(float x) +{ + return (float) atan((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ASINHF +float asinhf(float x) +{ + return (float) asinh((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ACOSHF +float acoshf(float x) +{ + return (float) acosh((double)x); +} +#endif + +#line 160 + +#ifndef HAVE_ATANHF +float atanhf(float x) +{ + return (float) atanh((double)x); +} +#endif + + +/* + * Two values arguments function + */ + +#line 182 +#ifndef HAVE_ATAN2L +longdouble atan2l(longdouble x, longdouble y) +{ + return (longdouble) atan2((double)x, (double) y); +} +#endif + +#line 182 +#ifndef HAVE_HYPOTL +longdouble hypotl(longdouble x, longdouble y) +{ + return (longdouble) hypot((double)x, (double) y); +} +#endif + +#line 182 +#ifndef HAVE_POWL +longdouble powl(longdouble x, longdouble y) +{ + return (longdouble) pow((double)x, (double) y); +} +#endif + +#line 182 +#ifndef HAVE_FMODL +longdouble fmodl(longdouble x, longdouble y) +{ + return (longdouble) fmod((double)x, (double) y); +} +#endif + +#line 182 +#ifndef HAVE_ATAN2F +float atan2f(float x, float y) +{ + return (float) atan2((double)x, (double) y); +} +#endif + +#line 182 +#ifndef HAVE_HYPOTF +float hypotf(float x, float y) +{ + return (float) hypot((double)x, (double) y); +} +#endif + +#line 182 +#ifndef HAVE_POWF +float powf(float x, float y) +{ + return (float) pow((double)x, (double) y); +} +#endif + +#line 182 +#ifndef HAVE_FMODF +float fmodf(float x, float y) +{ + return (float) fmod((double)x, (double) y); +} +#endif + + +/* + * One value - one pointer argument function + */ + +#line 202 +#ifndef HAVE_MODFL +longdouble modfl(longdouble x, longdouble *iptr) +{ + double nx, niptr, y; + nx = (double) x; + y = modf(nx, &niptr); + *iptr = (longdouble) niptr; + return (longdouble) y; +} +#endif + +#line 202 +#ifndef HAVE_MODFF +float modff(float x, float *iptr) +{ + double nx, niptr, y; + nx = (double) x; + y = modf(nx, &niptr); + *iptr = (float) niptr; + return (float) y; +} +#endif + + From numpy-svn at scipy.org Thu Sep 4 12:29:14 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 11:29:14 -0500 (CDT) Subject: [Numpy-svn] r5767 - branches/clean_math_config/numpy/core Message-ID: <20080904162914.36FDB39C02A@scipy.org> Author: cdavid Date: 2008-09-04 11:29:09 -0500 (Thu, 04 Sep 2008) New Revision: 5767 Modified: branches/clean_math_config/numpy/core/setup.py Log: Keep the cruft for compatibility for now. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-04 15:39:38 UTC (rev 5766) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-04 16:29:09 UTC (rev 5767) @@ -77,9 +77,10 @@ if check_func(f): moredefs.append(name_to_defsymb(f)) -# for func_name, defsymbol in FUNCTIONS_TO_CHECK: -# if check_func(func_name): -# moredefs.append(defsymbol) + # Keep this for compatibility for now + for func_name, defsymbol in FUNCTIONS_TO_CHECK: + if check_func(func_name): + moredefs.append(defsymbol) def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration,dot_join From numpy-svn at scipy.org Thu Sep 4 14:04:43 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 13:04:43 -0500 (CDT) Subject: [Numpy-svn] r5768 - in trunk/numpy/core: src tests Message-ID: <20080904180443.490CB39C02A@scipy.org> Author: ptvirtan Date: 2008-09-04 13:04:35 -0500 (Thu, 04 Sep 2008) New Revision: 5768 Modified: trunk/numpy/core/src/ufuncobject.c trunk/numpy/core/tests/test_umath.py Log: Ufunc docstrings: show the 'out' arguments in a more standard way Modified: trunk/numpy/core/src/ufuncobject.c =================================================================== --- trunk/numpy/core/src/ufuncobject.c 2008-09-04 16:29:09 UTC (rev 5767) +++ trunk/numpy/core/src/ufuncobject.c 2008-09-04 18:04:35 UTC (rev 5768) @@ -4046,19 +4046,20 @@ y1,y2,...,yn */ static PyObject * -_makeargs(int num, char *ltr) +_makeargs(int num, char *ltr, int null_if_none) { PyObject *str; int i; switch (num) { case 0: + if (null_if_none) return NULL; return PyString_FromString(""); case 1: return PyString_FromString(ltr); } - str = PyString_FromFormat("%s1,%s2", ltr, ltr); + str = PyString_FromFormat("%s1, %s2", ltr, ltr); for(i = 3; i <= num; ++i) { - PyString_ConcatAndDel(&str, PyString_FromFormat(",%s%d", ltr, i)); + PyString_ConcatAndDel(&str, PyString_FromFormat(", %s%d", ltr, i)); } return str; } @@ -4082,17 +4083,26 @@ /* to automate the first part of it */ /* the doc string shouldn't need the calling convention */ /* construct - y1,y2,,... = name(x1,x2,...) __doc__ + name(x1, x2, ...,[ out1, out2, ...]) + + __doc__ */ PyObject *outargs, *inargs, *doc; - outargs = _makeargs(self->nout, "y"); - inargs = _makeargs(self->nin, "x"); - doc = PyString_FromFormat("%s = %s(%s)\n\n%s", - PyString_AS_STRING(outargs), - self->name, - PyString_AS_STRING(inargs), - self->doc); - Py_DECREF(outargs); + outargs = _makeargs(self->nout, "out", 1); + inargs = _makeargs(self->nin, "x", 0); + if (outargs == NULL) { + doc = PyString_FromFormat("%s(%s)\n\n%s", + self->name, + PyString_AS_STRING(inargs), + self->doc); + } else { + doc = PyString_FromFormat("%s(%s[, %s])\n\n%s", + self->name, + PyString_AS_STRING(inargs), + PyString_AS_STRING(outargs), + self->doc); + Py_DECREF(outargs); + } Py_DECREF(inargs); return doc; } Modified: trunk/numpy/core/tests/test_umath.py =================================================================== --- trunk/numpy/core/tests/test_umath.py 2008-09-04 16:29:09 UTC (rev 5767) +++ trunk/numpy/core/tests/test_umath.py 2008-09-04 18:04:35 UTC (rev 5768) @@ -271,7 +271,7 @@ def test_attributes(self): add = ncu.add assert_equal(add.__name__, 'add') - assert add.__doc__.startswith('y = add(x1,x2)\n\n') + assert add.__doc__.startswith('add(x1, x2[, out])\n\n') self.failUnless(add.ntypes >= 18) # don't fail if types added self.failUnless('ii->i' in add.types) assert_equal(add.nin, 2) From numpy-svn at scipy.org Thu Sep 4 14:23:59 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 13:23:59 -0500 (CDT) Subject: [Numpy-svn] r5769 - in trunk/numpy: core/tests testing Message-ID: <20080904182359.B813639C02A@scipy.org> Author: alan.mcintyre Date: 2008-09-04 13:23:48 -0500 (Thu, 04 Sep 2008) New Revision: 5769 Modified: trunk/numpy/core/tests/test_umath.py trunk/numpy/testing/decorators.py trunk/numpy/testing/noseclasses.py trunk/numpy/testing/nosetester.py Log: Replaced numpy.testing.decorators.skipknownfailure with knownfailureif, which allows flagging tests as known failures rather than skips. Updated test_umath to use knownfailureif. Modified: trunk/numpy/core/tests/test_umath.py =================================================================== --- trunk/numpy/core/tests/test_umath.py 2008-09-04 18:04:35 UTC (rev 5768) +++ trunk/numpy/core/tests/test_umath.py 2008-09-04 18:23:48 UTC (rev 5769) @@ -229,6 +229,7 @@ yield _check_branch_cut, np.arccosh, [-2j, 2j, 2], [1, 1, 1j], 1, 1 yield _check_branch_cut, np.arctanh, [-2j, 2j, 0], [1, 1, 1j], 1, 1 + @dec.knownfailureif(True, "These branch cuts are known to fail") def test_branch_cuts_failing(self): # XXX: signed zeros are not OK for sqrt or for the arc* functions yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True @@ -238,7 +239,6 @@ yield _check_branch_cut, np.arcsinh, [-2j, 2j], [-1, 1], -1, 1, True yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, -1j], 1, -1, True - test_branch_cuts_failing = dec.skipknownfailure(test_branch_cuts_failing) def test_against_cmath(self): import cmath, sys Modified: trunk/numpy/testing/decorators.py =================================================================== --- trunk/numpy/testing/decorators.py 2008-09-04 18:04:35 UTC (rev 5768) +++ trunk/numpy/testing/decorators.py 2008-09-04 18:23:48 UTC (rev 5769) @@ -83,12 +83,41 @@ return nose.tools.make_decorator(f)(skipper) return skip_decorator -def skipknownfailure(f): - ''' Decorator to raise SkipTest for test known to fail +def knownfailureif(skip_condition, msg=None): + ''' Make function raise KnownFailureTest exception if skip_condition is true + + Parameters + --------- + skip_condition : bool + Flag to determine whether to mark test as known failure (True) + or not (False) + msg : string + Message to give on raising a KnownFailureTest exception + + Returns + ------- + decorator : function + Decorator, which, when applied to a function, causes SkipTest + to be raised when the skip_condition was True, and the function + to be called normally otherwise. + + Notes + ----- + You will see from the code that we had to further decorate the + decorator with the nose.tools.make_decorator function in order to + transmit function name, and various other metadata. ''' - # Local import to avoid a hard nose dependency and only incur the - # import time overhead at actual test-time. - import nose - def skipper(*args, **kwargs): - raise nose.SkipTest, 'This test is known to fail' - return nose.tools.make_decorator(f)(skipper) + if msg is None: + msg = 'Test skipped due to known failure' + def skip_decorator(f): + # Local import to avoid a hard nose dependency and only incur the + # import time overhead at actual test-time. + import nose + from noseclasses import KnownFailureTest + def skipper(*args, **kwargs): + if skip_condition: + raise KnownFailureTest, msg + else: + return f(*args, **kwargs) + return nose.tools.make_decorator(f)(skipper) + return skip_decorator Modified: trunk/numpy/testing/noseclasses.py =================================================================== --- trunk/numpy/testing/noseclasses.py 2008-09-04 18:04:35 UTC (rev 5768) +++ trunk/numpy/testing/noseclasses.py 2008-09-04 18:23:48 UTC (rev 5769) @@ -7,6 +7,7 @@ import doctest from nose.plugins import doctests as npd +from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin from nose.plugins.base import Plugin from nose.util import src, tolist import numpy @@ -16,8 +17,8 @@ _doctest_ignore = ['generate_numpy_api.py', 'scons_support.py', 'setupscons.py', 'setup.py'] -# All the classes in this module begin with 'numpy' to clearly distinguish them -# from the plethora of very similar names from nose/unittest/doctest +# Some of the classes in this module begin with 'numpy' to clearly distinguish +# them from the plethora of very similar names from nose/unittest/doctest #----------------------------------------------------------------------------- @@ -246,3 +247,35 @@ if bn in _doctest_ignore: return False return npd.Doctest.wantFile(self, file) + + +class KnownFailureTest(Exception): + '''Raise this exception to mark a test as a known failing test.''' + pass + + +class KnownFailure(ErrorClassPlugin): + '''Plugin that installs a KNOWNFAIL error class for the + KnownFailureClass exception. When KnownFailureTest is raised, + the exception will be logged in the knownfail attribute of the + result, 'K' or 'KNOWNFAIL' (verbose) will be output, and the + exception will not be counted as an error or failure.''' + enabled = True + knownfail = ErrorClass(KnownFailureTest, + label='KNOWNFAIL', + isfailure=False) + + def options(self, parser, env=os.environ): + env_opt = 'NOSE_WITHOUT_KNOWNFAIL' + parser.add_option('--no-knownfail', action='store_true', + dest='noKnownFail', default=env.get(env_opt, False), + help='Disable special handling of KnownFailureTest ' + 'exceptions') + + def configure(self, options, conf): + if not self.can_configure: + return + self.conf = conf + disable = getattr(options, 'noKnownFail', False) + if disable: + self.enabled = False Modified: trunk/numpy/testing/nosetester.py =================================================================== --- trunk/numpy/testing/nosetester.py 2008-09-04 18:04:35 UTC (rev 5768) +++ trunk/numpy/testing/nosetester.py 2008-09-04 18:23:48 UTC (rev 5769) @@ -266,8 +266,8 @@ # construct list of plugins, omitting the existing doctest plugin import nose.plugins.builtin - from noseclasses import numpyDoctest - plugins = [numpyDoctest()] + from noseclasses import numpyDoctest, KnownFailure + plugins = [numpyDoctest(), KnownFailure()] for p in nose.plugins.builtin.plugins: plug = p() if plug.name == 'doctest': From numpy-svn at scipy.org Thu Sep 4 17:13:33 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 16:13:33 -0500 (CDT) Subject: [Numpy-svn] r5770 - trunk/numpy/testing Message-ID: <20080904211333.BAAA539C02A@scipy.org> Author: alan.mcintyre Date: 2008-09-04 16:13:29 -0500 (Thu, 04 Sep 2008) New Revision: 5770 Modified: trunk/numpy/testing/noseclasses.py trunk/numpy/testing/nosetester.py Log: Renamed classes to conform to PEP 8. Modified: trunk/numpy/testing/noseclasses.py =================================================================== --- trunk/numpy/testing/noseclasses.py 2008-09-04 18:23:48 UTC (rev 5769) +++ trunk/numpy/testing/noseclasses.py 2008-09-04 21:13:29 UTC (rev 5770) @@ -17,14 +17,14 @@ _doctest_ignore = ['generate_numpy_api.py', 'scons_support.py', 'setupscons.py', 'setup.py'] -# Some of the classes in this module begin with 'numpy' to clearly distinguish +# Some of the classes in this module begin with 'Numpy' to clearly distinguish # them from the plethora of very similar names from nose/unittest/doctest #----------------------------------------------------------------------------- # Modified version of the one in the stdlib, that fixes a python bug (doctests # not found in extension modules, http://bugs.python.org/issue3158) -class numpyDocTestFinder(doctest.DocTestFinder): +class NumpyDocTestFinder(doctest.DocTestFinder): def _from_module(self, module, object): """ @@ -114,7 +114,7 @@ globs, seen) -class numpyDocTestCase(npd.DocTestCase): +class NumpyDocTestCase(npd.DocTestCase): """Proxy for DocTestCase: provides an address() method that returns the correct address for the doctest case. Otherwise acts as a proxy to the test case. To provide hints for address(), @@ -138,7 +138,7 @@ # second-chance checker; if the default comparison doesn't # pass, then see if the expected output string contains flags that # tell us to ignore the output -class numpyOutputChecker(doctest.OutputChecker): +class NumpyOutputChecker(doctest.OutputChecker): def check_output(self, want, got, optionflags): ret = doctest.OutputChecker.check_output(self, want, got, optionflags) @@ -152,7 +152,7 @@ # Subclass nose.plugins.doctests.DocTestCase to work around a bug in # its constructor that blocks non-default arguments from being passed # down into doctest.DocTestCase -class numpyDocTestCase(npd.DocTestCase): +class NumpyDocTestCase(npd.DocTestCase): def __init__(self, test, optionflags=0, setUp=None, tearDown=None, checker=None, obj=None, result_var='_'): self._result_var = result_var @@ -165,7 +165,7 @@ print_state = numpy.get_printoptions() -class numpyDoctest(npd.Doctest): +class NumpyDoctest(npd.Doctest): name = 'numpydoctest' # call nosetests with --with-numpydoctest enabled = True @@ -176,7 +176,7 @@ Plugin.configure(self, options, config) self.doctest_tests = True # self.extension = tolist(options.doctestExtension) - self.finder = numpyDocTestFinder() + self.finder = NumpyDocTestFinder() self.parser = doctest.DocTestParser() # Turn on whitespace normalization, set a minimal execution context @@ -230,9 +230,9 @@ # always use whitespace and ellipsis options optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS - yield numpyDocTestCase(test, + yield NumpyDocTestCase(test, optionflags=optionflags, - checker=numpyOutputChecker()) + checker=NumpyOutputChecker()) # Add an afterContext method to nose.plugins.doctests.Doctest in order Modified: trunk/numpy/testing/nosetester.py =================================================================== --- trunk/numpy/testing/nosetester.py 2008-09-04 18:23:48 UTC (rev 5769) +++ trunk/numpy/testing/nosetester.py 2008-09-04 21:13:29 UTC (rev 5770) @@ -266,8 +266,8 @@ # construct list of plugins, omitting the existing doctest plugin import nose.plugins.builtin - from noseclasses import numpyDoctest, KnownFailure - plugins = [numpyDoctest(), KnownFailure()] + from noseclasses import NumpyDoctest, KnownFailure + plugins = [NumpyDoctest(), KnownFailure()] for p in nose.plugins.builtin.plugins: plug = p() if plug.name == 'doctest': From numpy-svn at scipy.org Thu Sep 4 18:06:04 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 17:06:04 -0500 (CDT) Subject: [Numpy-svn] r5771 - trunk/doc Message-ID: <20080904220604.E7D8539C02A@scipy.org> Author: alan.mcintyre Date: 2008-09-04 17:06:01 -0500 (Thu, 04 Sep 2008) New Revision: 5771 Modified: trunk/doc/HOWTO_DOCUMENT.txt Log: Fix link to example.py. Modified: trunk/doc/HOWTO_DOCUMENT.txt =================================================================== --- trunk/doc/HOWTO_DOCUMENT.txt 2008-09-04 21:13:29 UTC (rev 5770) +++ trunk/doc/HOWTO_DOCUMENT.txt 2008-09-04 22:06:01 UTC (rev 5771) @@ -7,7 +7,7 @@ .. Note:: For an accompanying example, see `example.py - `_. + `_. Overview -------- From numpy-svn at scipy.org Thu Sep 4 21:20:28 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 20:20:28 -0500 (CDT) Subject: [Numpy-svn] r5772 - trunk/numpy/testing Message-ID: <20080905012028.0957139C02A@scipy.org> Author: alan.mcintyre Date: 2008-09-04 20:20:09 -0500 (Thu, 04 Sep 2008) New Revision: 5772 Modified: trunk/numpy/testing/noseclasses.py Log: Remove debugging code. Modified: trunk/numpy/testing/noseclasses.py =================================================================== --- trunk/numpy/testing/noseclasses.py 2008-09-04 22:06:01 UTC (rev 5771) +++ trunk/numpy/testing/noseclasses.py 2008-09-05 01:20:09 UTC (rev 5772) @@ -224,9 +224,6 @@ p2 = p[-1] test.globs[p2] = __import__(pkg_name, test.globs, {}, [p2]) - print 'additional import for %s: from %s import %s' % (test.filename, p1, p2) - print ' (%s): %r' % (pkg_name, test.globs[p2]) - # always use whitespace and ellipsis options optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS From numpy-svn at scipy.org Thu Sep 4 23:12:42 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 22:12:42 -0500 (CDT) Subject: [Numpy-svn] r5773 - branches/clean_math_config/numpy/core Message-ID: <20080905031242.0264439C089@scipy.org> Author: cdavid Date: 2008-09-04 22:12:37 -0500 (Thu, 04 Sep 2008) New Revision: 5773 Modified: branches/clean_math_config/numpy/core/setup.py Log: Check for all float/long double C99 math funcs explicitely. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 01:20:09 UTC (rev 5772) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 03:12:37 UTC (rev 5773) @@ -77,6 +77,19 @@ if check_func(f): moredefs.append(name_to_defsymb(f)) + c99_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", +"ceil", "rint", "trunc", "sqrt", "log10", "log", "exp", "expm1", "asin", +"acos", "atan", "asinh", "acosh", "atanh", "hypot", "atan2", "pow", "fmod", +"modf"] + + for f in c99_funcs: + name = "%sl" % f + if check_func(name): + moredefs.append(name_to_defsymb(name)) + name = "%sf" % f + if check_func(name): + moredefs.append(name_to_defsymb(name)) + # Keep this for compatibility for now for func_name, defsymbol in FUNCTIONS_TO_CHECK: if check_func(func_name): From numpy-svn at scipy.org Thu Sep 4 23:15:30 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 22:15:30 -0500 (CDT) Subject: [Numpy-svn] r5774 - branches/clean_math_config/numpy/core Message-ID: <20080905031530.A6E8639C02A@scipy.org> Author: cdavid Date: 2008-09-04 22:15:25 -0500 (Thu, 04 Sep 2008) New Revision: 5774 Modified: branches/clean_math_config/numpy/core/setup.py Log: Use calling version of check func. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 03:12:37 UTC (rev 5773) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 03:15:25 UTC (rev 5774) @@ -51,7 +51,8 @@ def check_math_capabilities(config, moredefs, mathlibs): def check_func(func_name): - return config.check_func(func_name, libraries=mathlibs, decl=True) + return config.check_func(func_name, libraries=mathlibs, + decl=True, call=True) def name_to_defsymb(name): return "HAVE_%s" % name.upper() From numpy-svn at scipy.org Thu Sep 4 23:19:08 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 4 Sep 2008 22:19:08 -0500 (CDT) Subject: [Numpy-svn] r5775 - branches/clean_math_config/numpy/core Message-ID: <20080905031908.0931439C02A@scipy.org> Author: cdavid Date: 2008-09-04 22:19:04 -0500 (Thu, 04 Sep 2008) New Revision: 5775 Modified: branches/clean_math_config/numpy/core/setup.py Log: Use the way formely used by setup to set backward-compatible defines. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 03:15:25 UTC (rev 5774) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 03:19:04 UTC (rev 5775) @@ -8,15 +8,11 @@ FUNCTIONS_TO_CHECK = [ ('expl', 'HAVE_LONGDOUBLE_FUNCS'), ('expf', 'HAVE_FLOAT_FUNCS'), - ('log1p', 'HAVE_LOG1P'), - ('expm1', 'HAVE_EXPM1'), ('asinh', 'HAVE_INVERSE_HYPERBOLIC'), ('atanhf', 'HAVE_INVERSE_HYPERBOLIC_FLOAT'), ('atanhl', 'HAVE_INVERSE_HYPERBOLIC_LONGDOUBLE'), ('isnan', 'HAVE_ISNAN'), ('isinf', 'HAVE_ISINF'), - ('rint', 'HAVE_RINT'), - ('trunc', 'HAVE_TRUNC'), ] def is_npy_no_signal(): @@ -92,8 +88,12 @@ moredefs.append(name_to_defsymb(name)) # Keep this for compatibility for now + def check_func_old(func_name): + return config.check_func(func_name, libraries=mathlibs, + decl=False, headers = ["math.h"]) + for func_name, defsymbol in FUNCTIONS_TO_CHECK: - if check_func(func_name): + if check_func_old(func_name): moredefs.append(defsymbol) def configuration(parent_package='',top_path=None): From numpy-svn at scipy.org Fri Sep 5 01:37:10 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 00:37:10 -0500 (CDT) Subject: [Numpy-svn] r5776 - branches/clean_math_config/numpy/core/src Message-ID: <20080905053710.AF8A139C02A@scipy.org> Author: cdavid Date: 2008-09-05 00:37:06 -0500 (Fri, 05 Sep 2008) New Revision: 5776 Modified: branches/clean_math_config/numpy/core/src/umathmodule.c.src Log: Tell vim to recognize umathmodule.c.src as a C file. Modified: branches/clean_math_config/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-05 03:19:04 UTC (rev 5775) +++ branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-05 05:37:06 UTC (rev 5776) @@ -1,6 +1,10 @@ /* -*- c -*- */ /* + * vim:syntax=c + */ + +/* ***************************************************************************** ** INCLUDES ** ***************************************************************************** From numpy-svn at scipy.org Fri Sep 5 01:44:42 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 00:44:42 -0500 (CDT) Subject: [Numpy-svn] r5777 - branches/clean_math_config/numpy/core Message-ID: <20080905054442.C8BCD39C02A@scipy.org> Author: cdavid Date: 2008-09-05 00:44:39 -0500 (Fri, 05 Sep 2008) New Revision: 5777 Modified: branches/clean_math_config/numpy/core/setup.py Log: Add fmod and modf as mandatory functions. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 05:37:06 UTC (rev 5776) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 05:44:39 UTC (rev 5777) @@ -56,7 +56,7 @@ # Mandatory functions: if not found, fail the build mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", "acos", - "atan"] + "atan", "fmod", "modf"] # Standard functions which may not be available and for which we have a # replacement implementation From numpy-svn at scipy.org Fri Sep 5 01:49:35 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 00:49:35 -0500 (CDT) Subject: [Numpy-svn] r5778 - branches/clean_math_config/numpy/core Message-ID: <20080905054935.7342D39C02A@scipy.org> Author: cdavid Date: 2008-09-05 00:49:32 -0500 (Fri, 05 Sep 2008) New Revision: 5778 Modified: branches/clean_math_config/numpy/core/setup.py Log: Add frexp and ldexp as the functions to lookf for C99 versions. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 05:44:39 UTC (rev 5777) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 05:49:32 UTC (rev 5778) @@ -56,7 +56,7 @@ # Mandatory functions: if not found, fail the build mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", "acos", - "atan", "fmod", "modf"] + "atan", "fmod", 'modf', 'frexp'] # Standard functions which may not be available and for which we have a # replacement implementation @@ -77,7 +77,7 @@ c99_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", "ceil", "rint", "trunc", "sqrt", "log10", "log", "exp", "expm1", "asin", "acos", "atan", "asinh", "acosh", "atanh", "hypot", "atan2", "pow", "fmod", -"modf"] +"modf", 'frexp', 'ldexp'] for f in c99_funcs: name = "%sl" % f From numpy-svn at scipy.org Fri Sep 5 02:11:30 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 01:11:30 -0500 (CDT) Subject: [Numpy-svn] r5779 - branches/clean_math_config/numpy/distutils/command Message-ID: <20080905061130.DC5E639C02A@scipy.org> Author: cdavid Date: 2008-09-05 01:11:26 -0500 (Fri, 05 Sep 2008) New Revision: 5779 Modified: branches/clean_math_config/numpy/distutils/command/config.py Log: Add a check_funcs_once function to speed up func checks. Modified: branches/clean_math_config/numpy/distutils/command/config.py =================================================================== --- branches/clean_math_config/numpy/distutils/command/config.py 2008-09-05 05:49:32 UTC (rev 5778) +++ branches/clean_math_config/numpy/distutils/command/config.py 2008-09-05 06:11:26 UTC (rev 5779) @@ -140,6 +140,61 @@ return self.try_link(body, headers, include_dirs, libraries, library_dirs) + def check_funcs_once(self, funcs, + headers=None, include_dirs=None, + libraries=None, library_dirs=None, + decl=False, call=False, call_args=None): + """Check a list of functions at once. + + This is useful to speed up things, since all the functions in the funcs + list will be put in one compilation unit. + + Arguments + --------- + + funcs: seq + list of functions to test + include_dirs : seq + list of header paths + libraries : seq + list of libraries to link the code snippet to + libraru_dirs : seq + list of library paths + decl : dict + for every (key, value), the declaration in the value will be + used for function in key. If a function is not in the + dictionay, no declaration will be used. + call : dict + for every item (f, value), if the value is True, a call will be + done to the function f""" + self._check_compiler() + body = [] + if decl: + for f, v in decl.items(): + if v: + body.append("int %s ();" % f) + + body.append("int main (void) {") + if call: + for f in funcs: + if call.has_key(f) and call[f]: + if not (call_args and call_args.has_key(f) and call_args[f]): + args = '' + else: + args = call_args[f] + body.append(" %s(%s);" % (f, args)) + else: + body.append(" %s;" % f) + else: + for f in funcs: + body.append(" %s;" % f) + body.append(" return 0;") + body.append("}") + body = '\n'.join(body) + "\n" + + return self.try_link(body, headers, include_dirs, + libraries, library_dirs) + def get_output(self, body, headers=None, include_dirs=None, libraries=None, library_dirs=None, lang="c"): From numpy-svn at scipy.org Fri Sep 5 02:21:22 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 01:21:22 -0500 (CDT) Subject: [Numpy-svn] r5780 - branches/clean_math_config/numpy/core Message-ID: <20080905062122.6132539C02A@scipy.org> Author: cdavid Date: 2008-09-05 01:21:18 -0500 (Fri, 05 Sep 2008) New Revision: 5780 Modified: branches/clean_math_config/numpy/core/setup.py Log: Use check_funcs_once to speed-up configuration on sane platforms. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:11:26 UTC (rev 5779) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:21:18 UTC (rev 5780) @@ -50,6 +50,15 @@ return config.check_func(func_name, libraries=mathlibs, decl=True, call=True) + def check_funcs_once(funcs_name): + decl = dict([(f, True) for f in funcs_name]) + st = config.check_funcs_once(funcs_name, libraries=mathlibs, + decl=decl, call=decl) + if st: + moredefs.extend([name_to_defsymb(f) for f in funcs_name]) + return st + + def name_to_defsymb(name): return "HAVE_%s" % name.upper() @@ -58,6 +67,10 @@ "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", "acos", "atan", "fmod", 'modf', 'frexp'] + if not check_funcs_once(mandatory_funcs): + raise SystemError("One of the required function to build numpy is not" + " available (the list is %s)." % str(mandatory_funcs)) + # Standard functions which may not be available and for which we have a # replacement implementation # XXX: we do not test for hypot because python checks for it (HAVE_HYPOT in @@ -65,11 +78,6 @@ optional_stdfuncs = ["expm1", "log1p", "acosh", "asinh", "atanh", "rint", "trunc"] - for f in mandatory_funcs: - if not check_func(f): - raise SystemError("Function %s is mandatory to build numpy." % f) - moredefs.append(name_to_defsymb(f)) - for f in optional_stdfuncs: if check_func(f): moredefs.append(name_to_defsymb(f)) @@ -79,13 +87,13 @@ "acos", "atan", "asinh", "acosh", "atanh", "hypot", "atan2", "pow", "fmod", "modf", 'frexp', 'ldexp'] - for f in c99_funcs: - name = "%sl" % f - if check_func(name): - moredefs.append(name_to_defsymb(name)) - name = "%sf" % f - if check_func(name): - moredefs.append(name_to_defsymb(name)) + for prec in ['l', 'f']: + if not check_funcs_once([f + prec for f in c99_funcs]): + # Global check failed, check func per func + for f in c99_funcs: + name = f + prec + if check_func(name): + moredefs.append(name_to_defsymb(name)) # Keep this for compatibility for now def check_func_old(func_name): From numpy-svn at scipy.org Fri Sep 5 02:26:00 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 01:26:00 -0500 (CDT) Subject: [Numpy-svn] r5781 - branches/clean_math_config/numpy/core Message-ID: <20080905062600.A4D5D39C02A@scipy.org> Author: cdavid Date: 2008-09-05 01:25:57 -0500 (Fri, 05 Sep 2008) New Revision: 5781 Modified: branches/clean_math_config/numpy/core/setup.py Log: Speed up the math configuration using check_funcs_once. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:21:18 UTC (rev 5780) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:25:57 UTC (rev 5781) @@ -58,6 +58,17 @@ moredefs.extend([name_to_defsymb(f) for f in funcs_name]) return st + def check_funcs(funcs_name): + # Use check_funcs_once first, and if it does not work, test func per + # func. Return success only if all the functions are available + if not check_funcs_once(funcs_name): + # Global check failed, check func per func + for f in funcs_name: + if check_func(f): + moredefs.append(name_to_defsymb(f)) + return 0 + else: + return 1 def name_to_defsymb(name): return "HAVE_%s" % name.upper() @@ -78,22 +89,17 @@ optional_stdfuncs = ["expm1", "log1p", "acosh", "asinh", "atanh", "rint", "trunc"] - for f in optional_stdfuncs: - if check_func(f): - moredefs.append(name_to_defsymb(f)) + check_funcs(optional_stdfuncs) + # C99 functions: float and long double versions c99_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", "ceil", "rint", "trunc", "sqrt", "log10", "log", "exp", "expm1", "asin", "acos", "atan", "asinh", "acosh", "atanh", "hypot", "atan2", "pow", "fmod", "modf", 'frexp', 'ldexp'] for prec in ['l', 'f']: - if not check_funcs_once([f + prec for f in c99_funcs]): - # Global check failed, check func per func - for f in c99_funcs: - name = f + prec - if check_func(name): - moredefs.append(name_to_defsymb(name)) + fns = [f + prec for f in c99_funcs] + check_funcs(fns) # Keep this for compatibility for now def check_func_old(func_name): From numpy-svn at scipy.org Fri Sep 5 02:34:59 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 01:34:59 -0500 (CDT) Subject: [Numpy-svn] r5782 - branches/clean_math_config/numpy/core Message-ID: <20080905063459.1520939C02A@scipy.org> Author: cdavid Date: 2008-09-05 01:34:55 -0500 (Fri, 05 Sep 2008) New Revision: 5782 Modified: branches/clean_math_config/numpy/core/setup.py Log: Fix indentation. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:25:57 UTC (rev 5781) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:34:55 UTC (rev 5782) @@ -75,8 +75,8 @@ # Mandatory functions: if not found, fail the build mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", - "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", "acos", - "atan", "fmod", 'modf', 'frexp'] + "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", + "acos", "atan", "fmod", 'modf', 'frexp'] if not check_funcs_once(mandatory_funcs): raise SystemError("One of the required function to build numpy is not" @@ -93,9 +93,9 @@ # C99 functions: float and long double versions c99_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", -"ceil", "rint", "trunc", "sqrt", "log10", "log", "exp", "expm1", "asin", -"acos", "atan", "asinh", "acosh", "atanh", "hypot", "atan2", "pow", "fmod", -"modf", 'frexp', 'ldexp'] + "ceil", "rint", "trunc", "sqrt", "log10", "log", "exp", + "expm1", "asin", "acos", "atan", "asinh", "acosh", "atanh", + "hypot", "atan2", "pow", "fmod", "modf", 'frexp', 'ldexp'] for prec in ['l', 'f']: fns = [f + prec for f in c99_funcs] From numpy-svn at scipy.org Fri Sep 5 02:47:13 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 01:47:13 -0500 (CDT) Subject: [Numpy-svn] r5783 - branches/clean_math_config/numpy/core/src Message-ID: <20080905064713.62E2839C02A@scipy.org> Author: cdavid Date: 2008-09-05 01:47:10 -0500 (Fri, 05 Sep 2008) New Revision: 5783 Modified: branches/clean_math_config/numpy/core/src/umathmodule.c.src Log: Remove HAVE_FLOAT_FUNCS, and use function-specific HAVE_ instead. Modified: branches/clean_math_config/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-05 06:34:55 UTC (rev 5782) +++ branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-05 06:47:10 UTC (rev 5783) @@ -1628,13 +1628,13 @@ } /**end repeat**/ -#define HAVE_DOUBLE_FUNCS /**begin repeat #TYPE=FLOAT, DOUBLE, LONGDOUBLE# #typ=float, double, longdouble# #c=f,,l# + #C=F,,L# */ -#ifdef HAVE_ at TYPE@_FUNCS +#ifdef HAVE_FREXP at C@ static void @TYPE at _frexp(char **args, intp *dimensions, intp *steps, void *func) { @@ -1650,7 +1650,9 @@ *((int *) op2) = y2; } } +#endif +#ifdef HAVE_LDEXP at C@ static void @TYPE at _ldexp(char **args, intp *dimensions, intp *steps, void *func) { @@ -1668,47 +1670,46 @@ } #endif /**end repeat**/ -#undef HAVE_DOUBLE_FUNCS static PyUFuncGenericFunction frexp_functions[] = { -#ifdef HAVE_FLOAT_FUNCS +#ifdef HAVE_FREXPF FLOAT_frexp, #endif DOUBLE_frexp -#ifdef HAVE_LONGDOUBLE_FUNCS +#ifdef HAVE_FREXPL ,LONGDOUBLE_frexp #endif }; static void * blank3_data[] = { (void *)NULL, (void *)NULL, (void *)NULL}; static char frexp_signatures[] = { -#ifdef HAVE_FLOAT_FUNCS +#ifdef HAVE_FREXPF PyArray_FLOAT, PyArray_FLOAT, PyArray_INT, #endif PyArray_DOUBLE, PyArray_DOUBLE, PyArray_INT -#ifdef HAVE_LONGDOUBLE_FUNCS +#ifdef HAVE_FREXPL ,PyArray_LONGDOUBLE, PyArray_LONGDOUBLE, PyArray_INT #endif }; static PyUFuncGenericFunction ldexp_functions[] = { -#ifdef HAVE_FLOAT_FUNCS +#ifdef HAVE_LDEXPF FLOAT_ldexp, #endif DOUBLE_ldexp -#ifdef HAVE_LONGDOUBLE_FUNCS +#ifdef HAVE_LDEXPL ,LONGDOUBLE_ldexp #endif }; static char ldexp_signatures[] = { -#ifdef HAVE_FLOAT_FUNCS +#ifdef HAVE_LDEXPF PyArray_FLOAT, PyArray_INT, PyArray_FLOAT, #endif PyArray_DOUBLE, PyArray_INT, PyArray_DOUBLE -#ifdef HAVE_LONGDOUBLE_FUNCS +#ifdef HAVE_LDEXPL ,PyArray_LONGDOUBLE, PyArray_INT, PyArray_LONGDOUBLE #endif }; @@ -1761,10 +1762,10 @@ PyObject *f; int num=1; -#ifdef HAVE_LONGDOUBLE_FUNCS +#ifdef HAVE_FREXPL num += 1; #endif -#ifdef HAVE_FLOAT_FUNCS +#ifdef HAVE_FREXPF num += 1; #endif f = PyUFunc_FromFuncAndData(frexp_functions, blank3_data, @@ -1775,6 +1776,13 @@ PyDict_SetItemString(dictionary, "frexp", f); Py_DECREF(f); + num = 1; +#ifdef HAVE_LDEXPL + num += 1; +#endif +#ifdef HAVE_LDEXPF + num += 1; +#endif f = PyUFunc_FromFuncAndData(ldexp_functions, blank3_data, ldexp_signatures, num, 2, 1, PyUFunc_None, "ldexp", "Compute y = x1 * 2**x2.",0); From numpy-svn at scipy.org Fri Sep 5 02:47:44 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 01:47:44 -0500 (CDT) Subject: [Numpy-svn] r5784 - branches/clean_math_config/numpy/core Message-ID: <20080905064744.736D039C02A@scipy.org> Author: cdavid Date: 2008-09-05 01:47:40 -0500 (Fri, 05 Sep 2008) New Revision: 5784 Modified: branches/clean_math_config/numpy/core/setup.py Log: Remove HAVE_INVERSE_* for inverse hyperbolic funcs: not needed anymore. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:47:10 UTC (rev 5783) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:47:40 UTC (rev 5784) @@ -8,9 +8,6 @@ FUNCTIONS_TO_CHECK = [ ('expl', 'HAVE_LONGDOUBLE_FUNCS'), ('expf', 'HAVE_FLOAT_FUNCS'), - ('asinh', 'HAVE_INVERSE_HYPERBOLIC'), - ('atanhf', 'HAVE_INVERSE_HYPERBOLIC_FLOAT'), - ('atanhl', 'HAVE_INVERSE_HYPERBOLIC_LONGDOUBLE'), ('isnan', 'HAVE_ISNAN'), ('isinf', 'HAVE_ISINF'), ] From numpy-svn at scipy.org Fri Sep 5 02:49:51 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 01:49:51 -0500 (CDT) Subject: [Numpy-svn] r5785 - branches/clean_math_config/numpy/core Message-ID: <20080905064951.B5B3E39C02A@scipy.org> Author: cdavid Date: 2008-09-05 01:49:48 -0500 (Fri, 05 Sep 2008) New Revision: 5785 Modified: branches/clean_math_config/numpy/core/setup.py Log: Check for isnan and isinf. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:47:40 UTC (rev 5784) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:49:48 UTC (rev 5785) @@ -7,10 +7,7 @@ FUNCTIONS_TO_CHECK = [ ('expl', 'HAVE_LONGDOUBLE_FUNCS'), - ('expf', 'HAVE_FLOAT_FUNCS'), - ('isnan', 'HAVE_ISNAN'), - ('isinf', 'HAVE_ISINF'), - ] + ('expf', 'HAVE_FLOAT_FUNCS')] def is_npy_no_signal(): """Return True if the NPY_NO_SIGNAL symbol must be defined in configuration @@ -98,6 +95,9 @@ fns = [f + prec for f in c99_funcs] check_funcs(fns) + # IEEE754 handling + check_funcs(["isnan", "isinf"]) + # Keep this for compatibility for now def check_func_old(func_name): return config.check_func(func_name, libraries=mathlibs, From numpy-svn at scipy.org Fri Sep 5 02:59:47 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 01:59:47 -0500 (CDT) Subject: [Numpy-svn] r5786 - branches/clean_math_config/numpy/core Message-ID: <20080905065947.6604939C02A@scipy.org> Author: cdavid Date: 2008-09-05 01:59:44 -0500 (Fri, 05 Sep 2008) New Revision: 5786 Modified: branches/clean_math_config/numpy/core/setup.py Log: Do not check for the same functions twice. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:49:48 UTC (rev 5785) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:59:44 UTC (rev 5786) @@ -5,10 +5,6 @@ from numpy.distutils import log from distutils.dep_util import newer -FUNCTIONS_TO_CHECK = [ - ('expl', 'HAVE_LONGDOUBLE_FUNCS'), - ('expf', 'HAVE_FLOAT_FUNCS')] - def is_npy_no_signal(): """Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header.""" @@ -98,15 +94,6 @@ # IEEE754 handling check_funcs(["isnan", "isinf"]) - # Keep this for compatibility for now - def check_func_old(func_name): - return config.check_func(func_name, libraries=mathlibs, - decl=False, headers = ["math.h"]) - - for func_name, defsymbol in FUNCTIONS_TO_CHECK: - if check_func_old(func_name): - moredefs.append(defsymbol) - def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration,dot_join from numpy.distutils.system_info import get_info, default_lib_dirs @@ -187,6 +174,17 @@ target_f.write('#define %s\n' % (d)) else: target_f.write('#define %s %s\n' % (d[0],d[1])) + + # Keep those for backward compatibility for now + target_f.write(""" +#ifdef HAVE_EXPL +#define HAVE_LONGDOUBLE_FUNCS +#endif + +#ifdef HAVE_EXPF +#define HAVE_FUNCS_FUNCS +#endif +""") target_f.close() print 'File:',target target_f = open(target) From numpy-svn at scipy.org Fri Sep 5 03:00:16 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 02:00:16 -0500 (CDT) Subject: [Numpy-svn] r5787 - branches/clean_math_config/numpy/core Message-ID: <20080905070016.D785339C02A@scipy.org> Author: cdavid Date: 2008-09-05 02:00:12 -0500 (Fri, 05 Sep 2008) New Revision: 5787 Modified: branches/clean_math_config/numpy/core/setup.py Log: ldexp is a mandatory function. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-05 06:59:44 UTC (rev 5786) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-05 07:00:12 UTC (rev 5787) @@ -66,7 +66,7 @@ # Mandatory functions: if not found, fail the build mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", - "acos", "atan", "fmod", 'modf', 'frexp'] + "acos", "atan", "fmod", 'modf', 'frexp', 'ldexp'] if not check_funcs_once(mandatory_funcs): raise SystemError("One of the required function to build numpy is not" From numpy-svn at scipy.org Fri Sep 5 09:58:02 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 08:58:02 -0500 (CDT) Subject: [Numpy-svn] r5788 - in trunk/numpy/lib: . tests Message-ID: <20080905135802.BD5AE39C414@scipy.org> Author: dhuard Date: 2008-09-05 08:58:00 -0500 (Fri, 05 Sep 2008) New Revision: 5788 Modified: trunk/numpy/lib/io.py trunk/numpy/lib/tests/test_io.py Log: Applied patch from R. May fixing ticket #905 (loadtxt). Fixed other bug occurring when both usecols and converters are provided. Added related regression tests. Modified: trunk/numpy/lib/io.py =================================================================== --- trunk/numpy/lib/io.py 2008-09-05 07:00:12 UTC (rev 5787) +++ trunk/numpy/lib/io.py 2008-09-05 13:58:00 UTC (rev 5788) @@ -312,7 +312,10 @@ """ user_converters = converters - + + if usecols is not None: + usecols = list(usecols) + if _string_like(fname): if fname.endswith('.gz'): import gzip @@ -373,7 +376,7 @@ # By preference, use the converters specified by the user for i, conv in (user_converters or {}).iteritems(): if usecols: - i = usecols.find(i) + i = usecols.index(i) converters[i] = conv # Parse each line, including the first Modified: trunk/numpy/lib/tests/test_io.py =================================================================== --- trunk/numpy/lib/tests/test_io.py 2008-09-05 07:00:12 UTC (rev 5787) +++ trunk/numpy/lib/tests/test_io.py 2008-09-05 13:58:00 UTC (rev 5788) @@ -170,7 +170,6 @@ 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') @@ -180,6 +179,16 @@ 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') @@ -221,6 +230,11 @@ 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 From numpy-svn at scipy.org Fri Sep 5 10:06:08 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 09:06:08 -0500 (CDT) Subject: [Numpy-svn] r5789 - trunk/doc/neps Message-ID: <20080905140608.F0A4239C442@scipy.org> Author: oliphant Date: 2008-09-05 09:06:02 -0500 (Fri, 05 Sep 2008) New Revision: 5789 Added: trunk/doc/neps/datetime-proposal3.rst Removed: trunk/doc/neps/datetime.rst Log: Add final date-time proposal. Added: trunk/doc/neps/datetime-proposal3.rst =================================================================== --- trunk/doc/neps/datetime-proposal3.rst 2008-09-05 13:58:00 UTC (rev 5788) +++ trunk/doc/neps/datetime-proposal3.rst 2008-09-05 14:06:02 UTC (rev 5789) @@ -0,0 +1,574 @@ +==================================================================== + A (third) proposal for implementing some date/time types in NumPy +==================================================================== + +:Author: Francesc Alted i Abad +:Contact: faltet at pytables.com +:Author: Ivan Vilata i Balaguer +:Contact: ivan at selidor.net +:Date: 2008-07-30 + + +Executive summary +================= + +A date/time mark is something very handy to have in many fields where +one has to deal with data sets. While Python has several modules that +define a date/time type (like the integrated ``datetime`` [1]_ or +``mx.DateTime`` [2]_), NumPy has a lack of them. + +In this document, we are proposing the addition of a series of date/time +types to fill this gap. The requirements for the proposed types are +two-folded: 1) they have to be fast to operate with and 2) they have to +be as compatible as possible with the existing ``datetime`` module that +comes with Python. + + +Types proposed +============== + +To start with, it is virtually impossible to come up with a single +date/time type that fills the needs of every case of use. So, after +pondering about different possibilities, we have stuck with *two* +different types, namely ``datetime64`` and ``timedelta64`` (these names +are preliminary and can be changed), that can have different time units +so as to cover different needs. + +.. Important:: the time unit is conceived here as metadata that + *complements* a date/time dtype, *without changing the base type*. It + provides information about the *meaning* of the stored numbers, not + about their *structure*. + +Now follows a detailed description of the proposed types. + + +``datetime64`` +-------------- + +It represents a time that is absolute (i.e. not relative). It is +implemented internally as an ``int64`` type. The internal epoch is the +POSIX epoch (see [3]_). Like POSIX, the representation of a date +doesn't take leap seconds into account. + +In time unit *conversions* and time *representations* (but not in other +time computations), the value -2**63 (0x8000000000000000) is interpreted +as an invalid or unknown date, *Not a Time* or *NaT*. See the section +on time unit conversions for more information. + +Time units +~~~~~~~~~~ + +It accepts different time units, each of them implying a different time +span. The table below describes the time units supported with their +corresponding time spans. + +======== ================ ========================== + Time unit Time span (years) +------------------------- -------------------------- + Code Meaning +======== ================ ========================== + Y year [9.2e18 BC, 9.2e18 AC] + M month [7.6e17 BC, 7.6e17 AC] + W week [1.7e17 BC, 1.7e17 AC] + B business day [3.5e16 BC, 3.5e16 AC] + D day [2.5e16 BC, 2.5e16 AC] + h hour [1.0e15 BC, 1.0e15 AC] + m minute [1.7e13 BC, 1.7e13 AC] + s second [ 2.9e9 BC, 2.9e9 AC] + ms millisecond [ 2.9e6 BC, 2.9e6 AC] + us microsecond [290301 BC, 294241 AC] + ns nanosecond [ 1678 AC, 2262 AC] +======== ================ ========================== + +The value of an absolute date is thus *an integer number of units of the +chosen time unit* passed since the internal epoch. When working with +business days, Saturdays and Sundays are simply ignored from the count +(i.e. day 3 in business days is not Saturday 1970-01-03, but Monday +1970-01-05). + +Building a ``datetime64`` dtype +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The proposed ways to specify the time unit in the dtype constructor are: + +Using the long string notation:: + + dtype('datetime64[us]') + +Using the short string notation:: + + dtype('T8[us]') + +Note that a time unit should always be specified, as there is not a +default. + + +Setting and getting values +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The objects with this dtype can be set in a series of ways:: + + t = numpy.ones(3, dtype='T8[s]') + t[0] = 1199164176 # assign to July 30th, 2008 at 17:31:00 + t[1] = datetime.datetime(2008, 7, 30, 17, 31, 01) # with datetime module + t[2] = '2008-07-30T17:31:02' # with ISO 8601 + +And can be get in different ways too:: + + str(t[0]) --> 2008-07-30T17:31:00 + repr(t[1]) --> datetime64(1199164177, 's') + str(t[0].item()) --> 2008-07-30 17:31:00 # datetime module object + repr(t[0].item()) --> datetime.datetime(2008, 7, 30, 17, 31) # idem + str(t) --> [2008-07-30T17:31:00 2008-07-30T17:31:01 2008-07-30T17:31:02] + repr(t) --> array([1199164176, 1199164177, 1199164178], + dtype='datetime64[s]') + +Comparisons +~~~~~~~~~~~ + +The comparisons will be supported too:: + + numpy.array(['1980'], 'T8[Y]') == numpy.array(['1979'], 'T8[Y]') + --> [False] + +or by applying broadcasting:: + + numpy.array(['1979', '1980'], 'T8[Y]') == numpy.datetime64('1980', 'Y') + --> [False, True] + +The next should work too:: + + numpy.array(['1979', '1980'], 'T8[Y]') == '1980-01-01' + --> [False, True] + +because the right hand expression can be broadcasted into an array of 2 +elements of dtype 'T8[Y]'. + +Compatibility issues +~~~~~~~~~~~~~~~~~~~~ + +This will be fully compatible with the ``datetime`` class of the +``datetime`` module of Python only when using a time unit of +microseconds. For other time units, the conversion process will loose +precision or will overflow as needed. The conversion from/to a +``datetime`` object doesn't take leap seconds into account. + + +``timedelta64`` +--------------- + +It represents a time that is relative (i.e. not absolute). It is +implemented internally as an ``int64`` type. + +In time unit *conversions* and time *representations* (but not in other +time computations), the value -2**63 (0x8000000000000000) is interpreted +as an invalid or unknown time, *Not a Time* or *NaT*. See the section +on time unit conversions for more information. + +Time units +~~~~~~~~~~ + +It accepts different time units, each of them implying a different time +span. The table below describes the time units supported with their +corresponding time spans. + +======== ================ ========================== + Time unit Time span +------------------------- -------------------------- + Code Meaning +======== ================ ========================== + Y year +- 9.2e18 years + M month +- 7.6e17 years + W week +- 1.7e17 years + B business day +- 3.5e16 years + D day +- 2.5e16 years + h hour +- 1.0e15 years + m minute +- 1.7e13 years + s second +- 2.9e12 years + ms millisecond +- 2.9e9 years + us microsecond +- 2.9e6 years + ns nanosecond +- 292 years + ps picosecond +- 106 days + fs femtosecond +- 2.6 hours + as attosecond +- 9.2 seconds +======== ================ ========================== + +The value of a time delta is thus *an integer number of units of the +chosen time unit*. + +Building a ``timedelta64`` dtype +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The proposed ways to specify the time unit in the dtype constructor are: + +Using the long string notation:: + + dtype('timedelta64[us]') + +Using the short string notation:: + + dtype('t8[us]') + +Note that a time unit should always be specified, as there is not a +default. + +Setting and getting values +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The objects with this dtype can be set in a series of ways:: + + t = numpy.ones(3, dtype='t8[ms]') + t[0] = 12 # assign to 12 ms + t[1] = datetime.timedelta(0, 0, 13000) # 13 ms + t[2] = '0:00:00.014' # 14 ms + +And can be get in different ways too:: + + str(t[0]) --> 0:00:00.012 + repr(t[1]) --> timedelta64(13, 'ms') + str(t[0].item()) --> 0:00:00.012000 # datetime module object + repr(t[0].item()) --> datetime.timedelta(0, 0, 12000) # idem + str(t) --> [0:00:00.012 0:00:00.014 0:00:00.014] + repr(t) --> array([12, 13, 14], dtype="timedelta64[ms]") + +Comparisons +~~~~~~~~~~~ + +The comparisons will be supported too:: + + numpy.array([12, 13, 14], 't8[ms]') == numpy.array([12, 13, 13], 't8[ms]') + --> [True, True, False] + +or by applying broadcasting:: + + numpy.array([12, 13, 14], 't8[ms]') == numpy.timedelta64(13, 'ms') + --> [False, True, False] + +The next should work too:: + + numpy.array([12, 13, 14], 't8[ms]') == '0:00:00.012' + --> [True, False, False] + +because the right hand expression can be broadcasted into an array of 3 +elements of dtype 't8[ms]'. + +Compatibility issues +~~~~~~~~~~~~~~~~~~~~ + +This will be fully compatible with the ``timedelta`` class of the +``datetime`` module of Python only when using a time unit of +microseconds. For other units, the conversion process will loose +precision or will overflow as needed. + + +Examples of use +=============== + +Here it is an example of use for the ``datetime64``:: + + In [5]: numpy.datetime64(42, 'us') + Out[5]: datetime64(42, 'us') + + In [6]: print numpy.datetime64(42, 'us') + 1970-01-01T00:00:00.000042 # representation in ISO 8601 format + + In [7]: print numpy.datetime64(367.7, 'D') # decimal part is lost + 1971-01-02 # still ISO 8601 format + + In [8]: numpy.datetime('2008-07-18T12:23:18', 'm') # from ISO 8601 + Out[8]: datetime64(20273063, 'm') + + In [9]: print numpy.datetime('2008-07-18T12:23:18', 'm') + Out[9]: 2008-07-18T12:23 + + In [10]: t = numpy.zeros(5, dtype="datetime64[ms]") + + In [11]: t[0] = datetime.datetime.now() # setter in action + + In [12]: print t + [2008-07-16T13:39:25.315 1970-01-01T00:00:00.000 + 1970-01-01T00:00:00.000 1970-01-01T00:00:00.000 + 1970-01-01T00:00:00.000] + + In [13]: repr(t) + Out[13]: array([267859210457, 0, 0, 0, 0], dtype="datetime64[ms]") + + In [14]: t[0].item() # getter in action + Out[14]: datetime.datetime(2008, 7, 16, 13, 39, 25, 315000) + + In [15]: print t.dtype + dtype('datetime64[ms]') + +And here it goes an example of use for the ``timedelta64``:: + + In [5]: numpy.timedelta64(10, 'us') + Out[5]: timedelta64(10, 'us') + + In [6]: print numpy.timedelta64(10, 'us') + 0:00:00.000010 + + In [7]: print numpy.timedelta64(3600.2, 'm') # decimal part is lost + 2 days, 12:00 + + In [8]: t1 = numpy.zeros(5, dtype="datetime64[ms]") + + In [9]: t2 = numpy.ones(5, dtype="datetime64[ms]") + + In [10]: t = t2 - t1 + + In [11]: t[0] = datetime.timedelta(0, 24) # setter in action + + In [12]: print t + [0:00:24.000 0:00:01.000 0:00:01.000 0:00:01.000 0:00:01.000] + + In [13]: print repr(t) + Out[13]: array([24000, 1, 1, 1, 1], dtype="timedelta64[ms]") + + In [14]: t[0].item() # getter in action + Out[14]: datetime.timedelta(0, 24) + + In [15]: print t.dtype + dtype('timedelta64[s]') + + +Operating with date/time arrays +=============================== + +``datetime64`` vs ``datetime64`` +-------------------------------- + +The only arithmetic operation allowed between absolute dates is the +subtraction:: + + In [10]: numpy.ones(3, "T8[s]") - numpy.zeros(3, "T8[s]") + Out[10]: array([1, 1, 1], dtype=timedelta64[s]) + +But not other operations:: + + In [11]: numpy.ones(3, "T8[s]") + numpy.zeros(3, "T8[s]") + TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'numpy.ndarray' + +Comparisons between absolute dates are allowed. + +Casting rules +~~~~~~~~~~~~~ + +When operating (basically, only the subtraction will be allowed) two +absolute times with different unit times, the outcome would be to raise +an exception. This is because the ranges and time-spans of the different +time units can be very different, and it is not clear at all what time +unit will be preferred for the user. For example, this should be +allowed:: + + >>> numpy.ones(3, dtype="T8[Y]") - numpy.zeros(3, dtype="T8[Y]") + array([1, 1, 1], dtype="timedelta64[Y]") + +But the next should not:: + + >>> numpy.ones(3, dtype="T8[Y]") - numpy.zeros(3, dtype="T8[ns]") + raise numpy.IncompatibleUnitError # what unit to choose? + + +``datetime64`` vs ``timedelta64`` +--------------------------------- + +It will be possible to add and subtract relative times from absolute +dates:: + + In [10]: numpy.zeros(5, "T8[Y]") + numpy.ones(5, "t8[Y]") + Out[10]: array([1971, 1971, 1971, 1971, 1971], dtype=datetime64[Y]) + + In [11]: numpy.ones(5, "T8[Y]") - 2 * numpy.ones(5, "t8[Y]") + Out[11]: array([1969, 1969, 1969, 1969, 1969], dtype=datetime64[Y]) + +But not other operations:: + + In [12]: numpy.ones(5, "T8[Y]") * numpy.ones(5, "t8[Y]") + TypeError: unsupported operand type(s) for *: 'numpy.ndarray' and 'numpy.ndarray' + +Casting rules +~~~~~~~~~~~~~ + +In this case the absolute time should have priority for determining the +time unit of the outcome. That would represent what the people wants to +do most of the times. For example, this would allow to do:: + + >>> series = numpy.array(['1970-01-01', '1970-02-01', '1970-09-01'], + dtype='datetime64[D]') + >>> series2 = series + numpy.timedelta(1, 'Y') # Add 2 relative years + >>> series2 + array(['1972-01-01', '1972-02-01', '1972-09-01'], + dtype='datetime64[D]') # the 'D'ay time unit has been chosen + + +``timedelta64`` vs ``timedelta64`` +---------------------------------- + +Finally, it will be possible to operate with relative times as if they +were regular int64 dtypes *as long as* the result can be converted back +into a ``timedelta64``:: + + In [10]: numpy.ones(3, 't8[us]') + Out[10]: array([1, 1, 1], dtype="timedelta64[us]") + + In [11]: (numpy.ones(3, 't8[M]') + 2) ** 3 + Out[11]: array([27, 27, 27], dtype="timedelta64[M]") + +But:: + + In [12]: numpy.ones(5, 't8') + 1j + TypeError: the result cannot be converted into a ``timedelta64`` + +Casting rules +~~~~~~~~~~~~~ + +When combining two ``timedelta64`` dtypes with different time units the +outcome will be the shorter of both ("keep the precision" rule). For +example:: + + In [10]: numpy.ones(3, 't8[s]') + numpy.ones(3, 't8[m]') + Out[10]: array([61, 61, 61], dtype="timedelta64[s]") + +However, due to the impossibility to know the exact duration of a +relative year or a relative month, when these time units appear in one +of the operands, the operation will not be allowed:: + + In [11]: numpy.ones(3, 't8[Y]') + numpy.ones(3, 't8[D]') + raise numpy.IncompatibleUnitError # how to convert relative years to days? + +In order to being able to perform the above operation a new NumPy +function, called ``change_timeunit`` is proposed. Its signature will +be:: + + change_timeunit(time_object, new_unit, reference) + +where 'time_object' is the time object whose unit is to be changed, +'new_unit' is the desired new time unit, and 'reference' is an absolute +date (NumPy datetime64 scalar) that will be used to allow the conversion +of relative times in case of using time units with an uncertain number +of smaller time units (relative years or months cannot be expressed in +days). + +With this, the above operation can be done as follows:: + + In [10]: t_years = numpy.ones(3, 't8[Y]') + + In [11]: t_days = numpy.change_timeunit(t_years, 'D', '2001-01-01') + + In [12]: t_days + numpy.ones(3, 't8[D]') + Out[12]: array([366, 366, 366], dtype="timedelta64[D]") + + +dtype vs time units conversions +=============================== + +For changing the date/time dtype of an existing array, we propose to use +the ``.astype()`` method. This will be mainly useful for changing time +units. + +For example, for absolute dates:: + + In[10]: t1 = numpy.zeros(5, dtype="datetime64[s]") + + In[11]: print t1 + [1970-01-01T00:00:00 1970-01-01T00:00:00 1970-01-01T00:00:00 + 1970-01-01T00:00:00 1970-01-01T00:00:00] + + In[12]: print t1.astype('datetime64[D]') + [1970-01-01 1970-01-01 1970-01-01 1970-01-01 1970-01-01] + +For relative times:: + + In[10]: t1 = numpy.ones(5, dtype="timedelta64[s]") + + In[11]: print t1 + [1 1 1 1 1] + + In[12]: print t1.astype('timedelta64[ms]') + [1000 1000 1000 1000 1000] + +Changing directly from/to relative to/from absolute dtypes will not be +supported:: + + In[13]: numpy.zeros(5, dtype="datetime64[s]").astype('timedelta64') + TypeError: data type cannot be converted to the desired type + +Business days have the peculiarity that they do not cover a continuous +line of time (they have gaps at weekends). Thus, when converting from +any ordinary time to business days, it can happen that the original time +is not representable. In that case, the result of the conversion is +*Not a Time* (*NaT*):: + + In[10]: t1 = numpy.arange(5, dtype="datetime64[D]") + + In[11]: print t1 + [1970-01-01 1970-01-02 1970-01-03 1970-01-04 1970-01-05] + + In[12]: t2 = t1.astype("datetime64[B]") + + In[13]: print t2 # 1970 begins in a Thursday + [1970-01-01 1970-01-02 NaT NaT 1970-01-05] + +When converting back to ordinary days, NaT values are left untouched +(this happens in all time unit conversions):: + + In[14]: t3 = t2.astype("datetime64[D]") + + In[13]: print t3 + [1970-01-01 1970-01-02 NaT NaT 1970-01-05] + + +Final considerations +==================== + +Why the ``origin`` metadata disappeared +--------------------------------------- + +During the discussion of the date/time dtypes in the NumPy list, the +idea of having an ``origin`` metadata that complemented the definition +of the absolute ``datetime64`` was initially found to be useful. + +However, after thinking more about this, we found that the combination +of an absolute ``datetime64`` with a relative ``timedelta64`` does offer +the same functionality while removing the need for the additional +``origin`` metadata. This is why we have removed it from this proposal. + +Operations with mixed time units +-------------------------------- + +Whenever an operation between two time values of the same dtype with the +same unit is accepted, the same operation with time values of different +units should be possible (e.g. adding a time delta in seconds and one in +microseconds), resulting in an adequate time unit. The exact semantics +of this kind of operations is defined int the "Casting rules" +subsections of the "Operating with date/time arrays" section. + +Due to the peculiarities of business days, it is most probable that +operations mixing business days with other time units will not be +allowed. + +Why there is not a ``quarter`` time unit? +----------------------------------------- + +This proposal tries to focus on the most common used set of time units +to operate with, and the ``quarter`` can be considered more of a derived +unit. Besides, the use of a ``quarter`` normally requires that it can +start at whatever month of the year, and as we are not including support +for a time ``origin`` metadata, this is not a viable venue here. +Finally, if we were to add the ``quarter`` then people should expect to +find a ``biweekly``, ``semester`` or ``biyearly`` just to put some +examples of other derived units, and we find this a bit too overwhelming +for this proposal purposes. + + +.. [1] http://docs.python.org/lib/module-datetime.html +.. [2] http://www.egenix.com/products/python/mxBase/mxDateTime +.. [3] http://en.wikipedia.org/wiki/Unix_time + + +.. Local Variables: +.. mode: rst +.. coding: utf-8 +.. fill-column: 72 +.. End: + Property changes on: trunk/doc/neps/datetime-proposal3.rst ___________________________________________________________________ Name: svn:eol-style + native Deleted: trunk/doc/neps/datetime.rst =================================================================== --- trunk/doc/neps/datetime.rst 2008-09-05 13:58:00 UTC (rev 5788) +++ trunk/doc/neps/datetime.rst 2008-09-05 14:06:02 UTC (rev 5789) @@ -1,354 +0,0 @@ -==================================================================== - A (second) proposal for implementing some date/time types in NumPy -==================================================================== - -:Author: Francesc Alted i Abad -:Contact: faltet at pytables.com -:Author: Ivan Vilata i Balaguer -:Contact: ivan at selidor.net -:Date: 2008-07-16 - - -Executive summary -================= - -A date/time mark is something very handy to have in many fields where -one has to deal with data sets. While Python has several modules that -define a date/time type (like the integrated ``datetime`` [1]_ or -``mx.DateTime`` [2]_), NumPy has a lack of them. - -In this document, we are proposing the addition of a series of date/time -types to fill this gap. The requirements for the proposed types are -two-folded: 1) they have to be fast to operate with and 2) they have to -be as compatible as possible with the existing ``datetime`` module that -comes with Python. - - -Types proposed -============== - -To start with, it is virtually impossible to come up with a single -date/time type that fills the needs of every case of use. So, after -pondering about different possibilities, we have stick with *two* -different types, namely ``datetime64`` and ``timedelta64`` (these names -are preliminary and can be changed), that can have different resolutions -so as to cover different needs. - -**Important note:** the resolution is conceived here as a metadata that - *complements* a date/time dtype, *without changing the base type*. - -Now it goes a detailed description of the proposed types. - - -``datetime64`` --------------- - -It represents a time that is absolute (i.e. not relative). It is -implemented internally as an ``int64`` type. The internal epoch is -POSIX epoch (see [3]_). - -Resolution -~~~~~~~~~~ - -It accepts different resolutions and for each of these resolutions, it -will support different time spans. The table below describes the -resolutions supported with its corresponding time spans. - -+----------------------+----------------------------------+ -| Resolution | Time span (years) | -+----------------------+----------------------------------+ -| Code | Meaning | | -+======================+==================================+ -| Y | year | [9.2e18 BC, 9.2e18 AC] | -| Q | quarter | [3.0e18 BC, 3.0e18 AC] | -| M | month | [7.6e17 BC, 7.6e17 AC] | -| W | week | [1.7e17 BC, 1.7e17 AC] | -| d | day | [2.5e16 BC, 2.5e16 AC] | -| h | hour | [1.0e15 BC, 1.0e15 AC] | -| m | minute | [1.7e13 BC, 1.7e13 AC] | -| s | second | [ 2.9e9 BC, 2.9e9 AC] | -| ms | millisecond | [ 2.9e6 BC, 2.9e6 AC] | -| us | microsecond | [290301 BC, 294241 AC] | -| ns | nanosecond | [ 1678 AC, 2262 AC] | -+----------------------+----------------------------------+ - -Building a ``datetime64`` dtype -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The proposed way to specify the resolution in the dtype constructor -is: - -Using parameters in the constructor:: - - dtype('datetime64', res="us") # the default res. is microseconds - -Using the long string notation:: - - dtype('datetime64[us]') # equivalent to dtype('datetime64') - -Using the short string notation:: - - dtype('T8[us]') # equivalent to dtype('T8') - -Compatibility issues -~~~~~~~~~~~~~~~~~~~~ - -This will be fully compatible with the ``datetime`` class of the -``datetime`` module of Python only when using a resolution of -microseconds. For other resolutions, the conversion process will -loose precision or will overflow as needed. - - -``timedelta64`` ---------------- - -It represents a time that is relative (i.e. not absolute). It is -implemented internally as an ``int64`` type. - -Resolution -~~~~~~~~~~ - -It accepts different resolutions and for each of these resolutions, it -will support different time spans. The table below describes the -resolutions supported with its corresponding time spans. - -+----------------------+--------------------------+ -| Resolution | Time span | -+----------------------+--------------------------+ -| Code | Meaning | | -+======================+==========================+ -| W | week | +- 1.7e17 years | -| D | day | +- 2.5e16 years | -| h | hour | +- 1.0e15 years | -| m | minute | +- 1.7e13 years | -| s | second | +- 2.9e12 years | -| ms | millisecond | +- 2.9e9 years | -| us | microsecond | +- 2.9e6 years | -| ns | nanosecond | +- 292 years | -| ps | picosecond | +- 106 days | -| fs | femtosecond | +- 2.6 hours | -| as | attosecond | +- 9.2 seconds | -+----------------------+--------------------------+ - -Building a ``timedelta64`` dtype -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The proposed way to specify the resolution in the dtype constructor -is: - -Using parameters in the constructor:: - - dtype('timedelta64', res="us") # the default res. is microseconds - -Using the long string notation:: - - dtype('timedelta64[us]') # equivalent to dtype('datetime64') - -Using the short string notation:: - - dtype('t8[us]') # equivalent to dtype('t8') - -Compatibility issues -~~~~~~~~~~~~~~~~~~~~ - -This will be fully compatible with the ``timedelta`` class of the -``datetime`` module of Python only when using a resolution of -microseconds. For other resolutions, the conversion process will -loose precision or will overflow as needed. - - -Example of use -============== - -Here it is an example of use for the ``datetime64``:: - - In [10]: t = numpy.zeros(5, dtype="datetime64[ms]") - - In [11]: t[0] = datetime.datetime.now() # setter in action - - In [12]: t[0] - Out[12]: '2008-07-16T13:39:25.315' # representation in ISO 8601 format - - In [13]: print t - [2008-07-16T13:39:25.315 1970-01-01T00:00:00.0 - 1970-01-01T00:00:00.0 1970-01-01T00:00:00.0 1970-01-01T00:00:00.0] - - In [14]: t[0].item() # getter in action - Out[14]: datetime.datetime(2008, 7, 16, 13, 39, 25, 315000) - - In [15]: print t.dtype - datetime64[ms] - -And here it goes an example of use for the ``timedelta64``:: - - In [8]: t1 = numpy.zeros(5, dtype="datetime64[s]") - - In [9]: t2 = numpy.ones(5, dtype="datetime64[s]") - - In [10]: t = t2 - t1 - - In [11]: t[0] = 24 # setter in action (setting to 24 seconds) - - In [12]: t[0] - Out[12]: 24 # representation as an int64 - - In [13]: print t - [24 1 1 1 1] - - In [14]: t[0].item() # getter in action - Out[14]: datetime.timedelta(0, 24) - - In [15]: print t.dtype - timedelta64[s] - - -Operating with date/time arrays -=============================== - -``datetime64`` vs ``datetime64`` --------------------------------- - -The only operation allowed between absolute dates is the subtraction:: - - In [10]: numpy.ones(5, "T8") - numpy.zeros(5, "T8") - Out[10]: array([1, 1, 1, 1, 1], dtype=timedelta64[us]) - -But not other operations:: - - In [11]: numpy.ones(5, "T8") + numpy.zeros(5, "T8") - TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'numpy.ndarray' - -``datetime64`` vs ``timedelta64`` ---------------------------------- - -It will be possible to add and subtract relative times from absolute -dates:: - - In [10]: numpy.zeros(5, "T8[Y]") + numpy.ones(5, "t8[Y]") - Out[10]: array([1971, 1971, 1971, 1971, 1971], dtype=datetime64[Y]) - - In [11]: numpy.ones(5, "T8[Y]") - 2 * numpy.ones(5, "t8[Y]") - Out[11]: array([1969, 1969, 1969, 1969, 1969], dtype=datetime64[Y]) - -But not other operations:: - - In [12]: numpy.ones(5, "T8[Y]") * numpy.ones(5, "t8[Y]") - TypeError: unsupported operand type(s) for *: 'numpy.ndarray' and 'numpy.ndarray' - -``timedelta64`` vs anything ---------------------------- - -Finally, it will be possible to operate with relative times as if they -were regular int64 dtypes *as long as* the result can be converted back -into a ``timedelta64``:: - - In [10]: numpy.ones(5, 't8') - Out[10]: array([1, 1, 1, 1, 1], dtype=timedelta64[us]) - - In [11]: (numpy.ones(5, 't8[M]') + 2) ** 3 - Out[11]: array([27, 27, 27, 27, 27], dtype=timedelta64[M]) - -But:: - - In [12]: numpy.ones(5, 't8') + 1j - TypeError: The result cannot be converted into a ``timedelta64`` - - -dtype/resolution conversions -============================ - -For changing the date/time dtype of an existing array, we propose to use -the ``.astype()`` method. This will be mainly useful for changing -resolutions. - -For example, for absolute dates:: - - In[10]: t1 = numpy.zeros(5, dtype="datetime64[s]") - - In[11]: print t1 - [1970-01-01T00:00:00 1970-01-01T00:00:00 1970-01-01T00:00:00 - 1970-01-01T00:00:00 1970-01-01T00:00:00] - - In[12]: print t1.astype('datetime64[d]') - [1970-01-01 1970-01-01 1970-01-01 1970-01-01 1970-01-01] - -For relative times:: - - In[10]: t1 = numpy.ones(5, dtype="timedelta64[s]") - - In[11]: print t1 - [1 1 1 1 1] - - In[12]: print t1.astype('timedelta64[ms]') - [1000 1000 1000 1000 1000] - -Changing directly from/to relative to/from absolute dtypes will not be -supported:: - - In[13]: numpy.zeros(5, dtype="datetime64[s]").astype('timedelta64') - TypeError: data type cannot be converted to the desired type - - -Final considerations -==================== - -Why the ``origin`` metadata disappeared ---------------------------------------- - -During the discussion of the date/time dtypes in the NumPy list, the -idea of having an ``origin`` metadata that complemented the definition -of the absolute ``datetime64`` was initially found to be useful. - -However, after thinking more about this, Ivan and me find that the -combination of an absolute ``datetime64`` with a relative -``timedelta64`` does offer the same functionality while removing the -need for the additional ``origin`` metadata. This is why we have -removed it from this proposal. - - -Resolution and dtype issues ---------------------------- - -The date/time dtype's resolution metadata cannot be used in general as -part of typical dtype usage. For example, in:: - - numpy.zeros(5, dtype=numpy.datetime64) - -we have to found yet a sensible way to pass the resolution. Perhaps the -next would work:: - - numpy.zeros(5, dtype=numpy.datetime64(res='Y')) - -but we are not sure if this would collide with the spirit of the NumPy -dtypes. - -At any rate, one can always do:: - - numpy.zeros(5, dtype=numpy.dtype('datetime64', res='Y')) - -BTW, prior to all of this, one should also elucidate whether:: - - numpy.dtype('datetime64', res='Y') - -or:: - - numpy.dtype('datetime64[Y]') - numpy.dtype('T8[Y]') - -would be a consistent way to instantiate a dtype in NumPy. We do really -think that could be a good way, but we would need to hear the opinion of -the expert. Travis? - - - -.. [1] http://docs.python.org/lib/module-datetime.html -.. [2] http://www.egenix.com/products/python/mxBase/mxDateTime -.. [3] http://en.wikipedia.org/wiki/Unix_time - - -.. Local Variables: -.. mode: rst -.. coding: utf-8 -.. fill-column: 72 -.. End: - From numpy-svn at scipy.org Fri Sep 5 12:51:09 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 11:51:09 -0500 (CDT) Subject: [Numpy-svn] r5790 - in branches/1.2.x/numpy/lib: . tests Message-ID: <20080905165109.8886639C02D@scipy.org> Author: dhuard Date: 2008-09-05 11:51:06 -0500 (Fri, 05 Sep 2008) New Revision: 5790 Modified: branches/1.2.x/numpy/lib/io.py branches/1.2.x/numpy/lib/tests/test_io.py Log: backporting r5788 to 1.2.x branch (loadtxt) Modified: branches/1.2.x/numpy/lib/io.py =================================================================== --- branches/1.2.x/numpy/lib/io.py 2008-09-05 14:06:02 UTC (rev 5789) +++ branches/1.2.x/numpy/lib/io.py 2008-09-05 16:51:06 UTC (rev 5790) @@ -312,7 +312,10 @@ """ user_converters = converters - + + if usecols is not None: + usecols = list(usecols) + if _string_like(fname): if fname.endswith('.gz'): import gzip @@ -373,7 +376,7 @@ # By preference, use the converters specified by the user for i, conv in (user_converters or {}).iteritems(): if usecols: - i = usecols.find(i) + i = usecols.index(i) converters[i] = conv # Parse each line, including the first Modified: branches/1.2.x/numpy/lib/tests/test_io.py =================================================================== --- branches/1.2.x/numpy/lib/tests/test_io.py 2008-09-05 14:06:02 UTC (rev 5789) +++ branches/1.2.x/numpy/lib/tests/test_io.py 2008-09-05 16:51:06 UTC (rev 5790) @@ -170,7 +170,6 @@ 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') @@ -180,6 +179,16 @@ 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') @@ -221,6 +230,11 @@ 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 From numpy-svn at scipy.org Fri Sep 5 19:38:47 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 5 Sep 2008 18:38:47 -0500 (CDT) Subject: [Numpy-svn] r5791 - in trunk/numpy/ma: . tests Message-ID: <20080905233847.3D13C39C424@scipy.org> Author: pierregm Date: 2008-09-05 18:38:44 -0500 (Fri, 05 Sep 2008) New Revision: 5791 Modified: trunk/numpy/ma/core.py trunk/numpy/ma/tests/test_core.py Log: * fixed deepcopy of masked arrays (bug #906) Modified: trunk/numpy/ma/core.py =================================================================== --- trunk/numpy/ma/core.py 2008-09-05 16:51:06 UTC (rev 5790) +++ trunk/numpy/ma/core.py 2008-09-05 23:38:44 UTC (rev 5791) @@ -3123,6 +3123,14 @@ return (_mareconstruct, (self.__class__, self._baseclass, (0,), 'b', ), self.__getstate__()) + # + def __deepcopy__(self, memo={}): + from copy import deepcopy + copied = MaskedArray.__new__(type(self), self, copy=True) + memo[id(self)] = copied + for (k,v) in self.__dict__.iteritems(): + copied.__dict__[k] = deepcopy(v, memo) + return copied def _mareconstruct(subtype, baseclass, baseshape, basetype,): Modified: trunk/numpy/ma/tests/test_core.py =================================================================== --- trunk/numpy/ma/tests/test_core.py 2008-09-05 16:51:06 UTC (rev 5790) +++ trunk/numpy/ma/tests/test_core.py 2008-09-05 23:38:44 UTC (rev 5791) @@ -330,6 +330,24 @@ assert_not_equal(y._mask.ctypes.data, x._mask.ctypes.data) + def test_deepcopy(self): + from copy import deepcopy + a = array([0,1,2], mask=[False,True,False]) + copied = deepcopy(a) + assert_equal(copied.mask, a.mask) + assert_not_equal(id(a._mask), id(copied._mask)) + # + copied[1] = 1 + assert_equal(copied.mask,[0,0,0]) + assert_equal(a.mask, [0,1,0]) + # + copied = deepcopy(a) + assert_equal(copied.mask, a.mask) + copied.mask[1] = False + assert_equal(copied.mask,[0,0,0]) + assert_equal(a.mask, [0,1,0]) + + def test_pickling(self): "Tests pickling" import cPickle From numpy-svn at scipy.org Sat Sep 6 06:48:42 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 6 Sep 2008 05:48:42 -0500 (CDT) Subject: [Numpy-svn] r5792 - in branches/1.2.x/numpy: core/tests testing Message-ID: <20080906104842.C878239C0CA@scipy.org> Author: alan.mcintyre Date: 2008-09-06 05:48:38 -0500 (Sat, 06 Sep 2008) New Revision: 5792 Modified: branches/1.2.x/numpy/core/tests/test_umath.py branches/1.2.x/numpy/testing/decorators.py branches/1.2.x/numpy/testing/noseclasses.py branches/1.2.x/numpy/testing/nosetester.py Log: Backports for: rev 5769 - Replaced numpy.testing.decorators.skipknownfailure with knownfailureif, which allows flagging tests as known failures rather than skips. Updated test_umath to use knownfailureif. rev 5770 - Renamed classes in nosetester.py/noseclasses.py to conform to PEP 8. rev 5772 - Removed debugging code from noseclasses.py Modified: branches/1.2.x/numpy/core/tests/test_umath.py =================================================================== --- branches/1.2.x/numpy/core/tests/test_umath.py 2008-09-05 23:38:44 UTC (rev 5791) +++ branches/1.2.x/numpy/core/tests/test_umath.py 2008-09-06 10:48:38 UTC (rev 5792) @@ -229,6 +229,7 @@ yield _check_branch_cut, np.arccosh, [-2j, 2j, 2], [1, 1, 1j], 1, 1 yield _check_branch_cut, np.arctanh, [-2j, 2j, 0], [1, 1, 1j], 1, 1 + @dec.knownfailureif(True, "These branch cuts are known to fail") def test_branch_cuts_failing(self): # XXX: signed zeros are not OK for sqrt or for the arc* functions yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True @@ -238,7 +239,6 @@ yield _check_branch_cut, np.arcsinh, [-2j, 2j], [-1, 1], -1, 1, True yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, -1j], 1, -1, True - test_branch_cuts_failing = dec.skipknownfailure(test_branch_cuts_failing) def test_against_cmath(self): import cmath, sys Modified: branches/1.2.x/numpy/testing/decorators.py =================================================================== --- branches/1.2.x/numpy/testing/decorators.py 2008-09-05 23:38:44 UTC (rev 5791) +++ branches/1.2.x/numpy/testing/decorators.py 2008-09-06 10:48:38 UTC (rev 5792) @@ -83,12 +83,41 @@ return nose.tools.make_decorator(f)(skipper) return skip_decorator -def skipknownfailure(f): - ''' Decorator to raise SkipTest for test known to fail +def knownfailureif(skip_condition, msg=None): + ''' Make function raise KnownFailureTest exception if skip_condition is true + + Parameters + --------- + skip_condition : bool + Flag to determine whether to mark test as known failure (True) + or not (False) + msg : string + Message to give on raising a KnownFailureTest exception + + Returns + ------- + decorator : function + Decorator, which, when applied to a function, causes SkipTest + to be raised when the skip_condition was True, and the function + to be called normally otherwise. + + Notes + ----- + You will see from the code that we had to further decorate the + decorator with the nose.tools.make_decorator function in order to + transmit function name, and various other metadata. ''' - # Local import to avoid a hard nose dependency and only incur the - # import time overhead at actual test-time. - import nose - def skipper(*args, **kwargs): - raise nose.SkipTest, 'This test is known to fail' - return nose.tools.make_decorator(f)(skipper) + if msg is None: + msg = 'Test skipped due to known failure' + def skip_decorator(f): + # Local import to avoid a hard nose dependency and only incur the + # import time overhead at actual test-time. + import nose + from noseclasses import KnownFailureTest + def skipper(*args, **kwargs): + if skip_condition: + raise KnownFailureTest, msg + else: + return f(*args, **kwargs) + return nose.tools.make_decorator(f)(skipper) + return skip_decorator Modified: branches/1.2.x/numpy/testing/noseclasses.py =================================================================== --- branches/1.2.x/numpy/testing/noseclasses.py 2008-09-05 23:38:44 UTC (rev 5791) +++ branches/1.2.x/numpy/testing/noseclasses.py 2008-09-06 10:48:38 UTC (rev 5792) @@ -7,6 +7,7 @@ import doctest from nose.plugins import doctests as npd +from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin from nose.plugins.base import Plugin from nose.util import src, tolist import numpy @@ -16,14 +17,14 @@ _doctest_ignore = ['generate_numpy_api.py', 'scons_support.py', 'setupscons.py', 'setup.py'] -# All the classes in this module begin with 'numpy' to clearly distinguish them -# from the plethora of very similar names from nose/unittest/doctest +# Some of the classes in this module begin with 'Numpy' to clearly distinguish +# them from the plethora of very similar names from nose/unittest/doctest #----------------------------------------------------------------------------- # Modified version of the one in the stdlib, that fixes a python bug (doctests # not found in extension modules, http://bugs.python.org/issue3158) -class numpyDocTestFinder(doctest.DocTestFinder): +class NumpyDocTestFinder(doctest.DocTestFinder): def _from_module(self, module, object): """ @@ -113,7 +114,7 @@ globs, seen) -class numpyDocTestCase(npd.DocTestCase): +class NumpyDocTestCase(npd.DocTestCase): """Proxy for DocTestCase: provides an address() method that returns the correct address for the doctest case. Otherwise acts as a proxy to the test case. To provide hints for address(), @@ -137,7 +138,7 @@ # second-chance checker; if the default comparison doesn't # pass, then see if the expected output string contains flags that # tell us to ignore the output -class numpyOutputChecker(doctest.OutputChecker): +class NumpyOutputChecker(doctest.OutputChecker): def check_output(self, want, got, optionflags): ret = doctest.OutputChecker.check_output(self, want, got, optionflags) @@ -151,7 +152,7 @@ # Subclass nose.plugins.doctests.DocTestCase to work around a bug in # its constructor that blocks non-default arguments from being passed # down into doctest.DocTestCase -class numpyDocTestCase(npd.DocTestCase): +class NumpyDocTestCase(npd.DocTestCase): def __init__(self, test, optionflags=0, setUp=None, tearDown=None, checker=None, obj=None, result_var='_'): self._result_var = result_var @@ -164,7 +165,7 @@ print_state = numpy.get_printoptions() -class numpyDoctest(npd.Doctest): +class NumpyDoctest(npd.Doctest): name = 'numpydoctest' # call nosetests with --with-numpydoctest enabled = True @@ -175,7 +176,7 @@ Plugin.configure(self, options, config) self.doctest_tests = True # self.extension = tolist(options.doctestExtension) - self.finder = numpyDocTestFinder() + self.finder = NumpyDocTestFinder() self.parser = doctest.DocTestParser() # Turn on whitespace normalization, set a minimal execution context @@ -223,15 +224,12 @@ p2 = p[-1] test.globs[p2] = __import__(pkg_name, test.globs, {}, [p2]) - print 'additional import for %s: from %s import %s' % (test.filename, p1, p2) - print ' (%s): %r' % (pkg_name, test.globs[p2]) - # always use whitespace and ellipsis options optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS - yield numpyDocTestCase(test, + yield NumpyDocTestCase(test, optionflags=optionflags, - checker=numpyOutputChecker()) + checker=NumpyOutputChecker()) # Add an afterContext method to nose.plugins.doctests.Doctest in order @@ -246,3 +244,35 @@ if bn in _doctest_ignore: return False return npd.Doctest.wantFile(self, file) + + +class KnownFailureTest(Exception): + '''Raise this exception to mark a test as a known failing test.''' + pass + + +class KnownFailure(ErrorClassPlugin): + '''Plugin that installs a KNOWNFAIL error class for the + KnownFailureClass exception. When KnownFailureTest is raised, + the exception will be logged in the knownfail attribute of the + result, 'K' or 'KNOWNFAIL' (verbose) will be output, and the + exception will not be counted as an error or failure.''' + enabled = True + knownfail = ErrorClass(KnownFailureTest, + label='KNOWNFAIL', + isfailure=False) + + def options(self, parser, env=os.environ): + env_opt = 'NOSE_WITHOUT_KNOWNFAIL' + parser.add_option('--no-knownfail', action='store_true', + dest='noKnownFail', default=env.get(env_opt, False), + help='Disable special handling of KnownFailureTest ' + 'exceptions') + + def configure(self, options, conf): + if not self.can_configure: + return + self.conf = conf + disable = getattr(options, 'noKnownFail', False) + if disable: + self.enabled = False Modified: branches/1.2.x/numpy/testing/nosetester.py =================================================================== --- branches/1.2.x/numpy/testing/nosetester.py 2008-09-05 23:38:44 UTC (rev 5791) +++ branches/1.2.x/numpy/testing/nosetester.py 2008-09-06 10:48:38 UTC (rev 5792) @@ -266,8 +266,8 @@ # construct list of plugins, omitting the existing doctest plugin import nose.plugins.builtin - from noseclasses import numpyDoctest - plugins = [numpyDoctest()] + from noseclasses import NumpyDoctest, KnownFailure + plugins = [NumpyDoctest(), KnownFailure()] for p in nose.plugins.builtin.plugins: plug = p() if plug.name == 'doctest': From numpy-svn at scipy.org Sun Sep 7 03:16:32 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 7 Sep 2008 02:16:32 -0500 (CDT) Subject: [Numpy-svn] r5793 - trunk/numpy/distutils/command Message-ID: <20080907071632.C0D7239C27D@scipy.org> Author: cdavid Date: 2008-09-07 02:16:28 -0500 (Sun, 07 Sep 2008) New Revision: 5793 Modified: trunk/numpy/distutils/command/scons.py Log: scons command: fix one more issue related to build dir. The distutils installation directory relative to the scons build directory was not always computed right. The relative position on the fs does not depend on the source directory (in out-of-place builds), but on the package *name* translated to a directly only. Modified: trunk/numpy/distutils/command/scons.py =================================================================== --- trunk/numpy/distutils/command/scons.py 2008-09-06 10:48:38 UTC (rev 5792) +++ trunk/numpy/distutils/command/scons.py 2008-09-07 07:16:28 UTC (rev 5793) @@ -44,11 +44,12 @@ from numscons import get_scons_path return get_scons_path() -def get_distutils_libdir(cmd, sconscript_path): +def get_distutils_libdir(cmd, pkg): """Returns the path where distutils install libraries, relatively to the scons build directory.""" from numscons import get_scons_build_dir - scdir = pjoin(get_scons_build_dir(), pdirname(sconscript_path)) + from numscons.core.utils import pkg_to_path + scdir = pjoin(get_scons_build_dir(), pkg_to_path(pkg)) n = scdir.count(os.sep) return pjoin(os.sep.join([os.pardir for i in range(n+1)]), cmd.build_lib) @@ -424,7 +425,7 @@ #cmd.append('distutils_libdir=%s' % protect_path(pjoin(self.build_lib, # pdirname(sconscript)))) cmd.append('distutils_libdir=%s' % - protect_path(get_distutils_libdir(self, sconscript))) + protect_path(get_distutils_libdir(self, pkg_name))) if not self._bypass_distutils_cc: cmd.append('cc_opt=%s' % self.scons_compiler) From numpy-svn at scipy.org Sun Sep 7 03:19:24 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 7 Sep 2008 02:19:24 -0500 (CDT) Subject: [Numpy-svn] r5794 - branches/1.2.x/numpy/distutils/command Message-ID: <20080907071924.D165B39C27D@scipy.org> Author: cdavid Date: 2008-09-07 02:19:21 -0500 (Sun, 07 Sep 2008) New Revision: 5794 Modified: branches/1.2.x/numpy/distutils/command/scons.py Log: Backport r5793 for scons command. Modified: branches/1.2.x/numpy/distutils/command/scons.py =================================================================== --- branches/1.2.x/numpy/distutils/command/scons.py 2008-09-07 07:16:28 UTC (rev 5793) +++ branches/1.2.x/numpy/distutils/command/scons.py 2008-09-07 07:19:21 UTC (rev 5794) @@ -44,11 +44,12 @@ from numscons import get_scons_path return get_scons_path() -def get_distutils_libdir(cmd, sconscript_path): +def get_distutils_libdir(cmd, pkg): """Returns the path where distutils install libraries, relatively to the scons build directory.""" from numscons import get_scons_build_dir - scdir = pjoin(get_scons_build_dir(), pdirname(sconscript_path)) + from numscons.core.utils import pkg_to_path + scdir = pjoin(get_scons_build_dir(), pkg_to_path(pkg)) n = scdir.count(os.sep) return pjoin(os.sep.join([os.pardir for i in range(n+1)]), cmd.build_lib) @@ -424,7 +425,7 @@ #cmd.append('distutils_libdir=%s' % protect_path(pjoin(self.build_lib, # pdirname(sconscript)))) cmd.append('distutils_libdir=%s' % - protect_path(get_distutils_libdir(self, sconscript))) + protect_path(get_distutils_libdir(self, pkg_name))) if not self._bypass_distutils_cc: cmd.append('cc_opt=%s' % self.scons_compiler) From numpy-svn at scipy.org Mon Sep 8 07:19:57 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 8 Sep 2008 06:19:57 -0500 (CDT) Subject: [Numpy-svn] r5795 - branches/1.2.x/numpy/core/tests Message-ID: <20080908111957.A162B39C021@scipy.org> Author: cdavid Date: 2008-09-08 06:19:47 -0500 (Mon, 08 Sep 2008) New Revision: 5795 Modified: branches/1.2.x/numpy/core/tests/test_print.py Log: Split formatting tests to tag long double ones as known failure on win32. Modified: branches/1.2.x/numpy/core/tests/test_print.py =================================================================== --- branches/1.2.x/numpy/core/tests/test_print.py 2008-09-07 07:19:21 UTC (rev 5794) +++ branches/1.2.x/numpy/core/tests/test_print.py 2008-09-08 11:19:47 UTC (rev 5795) @@ -1,3 +1,5 @@ +import sys + import numpy as np from numpy.testing import * @@ -3,5 +5,5 @@ class TestPrint(TestCase): - def test_float_types(self) : + def _test_float_type(self, type): """ Check formatting. @@ -11,11 +13,23 @@ python float precision. """ - for t in [np.float, np.double, np.longdouble] : - for x in [0, 1,-1, 1e10, 1e20] : - assert_equal(str(t(x)), str(float(x))) + for x in [0, 1,-1, 1e10, 1e20] : + assert_equal(str(type(x)), str(float(x))) - def test_complex_types(self) : + def test_float(self) : + self._test_float_type(np.float) + + def test_double(self) : + self._test_float_type(np.double) + + # Not really failure on win32, but with mingw. Get this information this + # information is more than I want to do. + @dec.knownfailureif(sys.platform == 'win32', + "long double print is known to fail on windows") + def test_longdouble(self) : + self._test_float_type(np.longdouble) + + def _test_complex_type(self, type) : """Check formatting. This is only for the str function, and only for simple types. @@ -23,12 +37,24 @@ python float precision. """ - for t in [np.cfloat, np.cdouble, np.clongdouble] : - for x in [0, 1,-1, 1e10, 1e20] : - assert_equal(str(t(x)), str(complex(x))) - assert_equal(str(t(x*1j)), str(complex(x*1j))) - assert_equal(str(t(x + x*1j)), str(complex(x + x*1j))) + for x in [0, 1,-1, 1e10, 1e20] : + assert_equal(str(type(x)), str(complex(x))) + assert_equal(str(type(x*1j)), str(complex(x*1j))) + assert_equal(str(type(x + x*1j)), str(complex(x + x*1j))) + def test_complex_float(self) : + self._test_complex_type(np.cfloat) + def test_complex_double(self) : + self._test_complex_type(np.cdouble) + + # Not really failure on win32, but with mingw. Get this information this + # information is more than I want to do. + @dec.knownfailureif(sys.platform == 'win32', + "complex long double print is known to fail on windows") + def test_complex_longdouble(self) : + self._test_complex_type(np.clongdouble) + + if __name__ == "__main__": run_module_suite() From numpy-svn at scipy.org Tue Sep 9 06:55:34 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 9 Sep 2008 05:55:34 -0500 (CDT) Subject: [Numpy-svn] r5796 - trunk/numpy/f2py Message-ID: <20080909105534.BA5DC39C018@scipy.org> Author: pearu Date: 2008-09-09 05:55:30 -0500 (Tue, 09 Sep 2008) New Revision: 5796 Modified: trunk/numpy/f2py/crackfortran.py Log: Fix typo. Modified: trunk/numpy/f2py/crackfortran.py =================================================================== --- trunk/numpy/f2py/crackfortran.py 2008-09-08 11:19:47 UTC (rev 5795) +++ trunk/numpy/f2py/crackfortran.py 2008-09-09 10:55:30 UTC (rev 5796) @@ -327,7 +327,7 @@ if rl[:4].lower()=='f2py': # f2py directive l = l + 4*' ' r=commentline.match(rl[4:]) - if r: l=l+r('line') + if r: l=l+r.group('line') else: l = l + rl[4:] if l.strip()=='': # Skip empty line cont=0 From numpy-svn at scipy.org Tue Sep 9 09:38:50 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 9 Sep 2008 08:38:50 -0500 (CDT) Subject: [Numpy-svn] r5797 - in trunk/numpy/lib: . tests Message-ID: <20080909133850.2F15E39C23D@scipy.org> Author: stefan Date: 2008-09-09 08:38:34 -0500 (Tue, 09 Sep 2008) New Revision: 5797 Modified: trunk/numpy/lib/io.py trunk/numpy/lib/tests/test_io.py Log: FIX: Loadtxt raises on empty input (closes #908). Modified: trunk/numpy/lib/io.py =================================================================== --- trunk/numpy/lib/io.py 2008-09-09 10:55:30 UTC (rev 5796) +++ trunk/numpy/lib/io.py 2008-09-09 13:38:34 UTC (rev 5797) @@ -312,10 +312,10 @@ """ user_converters = converters - - if usecols is not None: - usecols = list(usecols) - + + if usecols is not None: + usecols = list(usecols) + if _string_like(fname): if fname.endswith('.gz'): import gzip @@ -361,6 +361,8 @@ first_vals = None while not first_vals: first_line = fh.readline() + if first_line == '': # EOF reached + raise IOError('End-of-file reached before encountering data.') first_vals = split_line(first_line) N = len(usecols or first_vals) Modified: trunk/numpy/lib/tests/test_io.py =================================================================== --- trunk/numpy/lib/tests/test_io.py 2008-09-09 10:55:30 UTC (rev 5796) +++ trunk/numpy/lib/tests/test_io.py 2008-09-09 13:38:34 UTC (rev 5797) @@ -140,7 +140,6 @@ y = np.loadtxt(d, dtype=mydescriptor) assert_array_equal(y, b) - def test_array(self): c = StringIO.StringIO() c.write('1 2\n3 4') @@ -188,7 +187,7 @@ 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') @@ -230,7 +229,7 @@ x = np.loadtxt(c, dtype=float, usecols=(1,2)) assert_array_equal(x, a[:,1:]) - # Testing with arrays instead of tuples. + # 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:]) @@ -255,6 +254,9 @@ 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) class Testfromregex(TestCase): def test_record(self): From numpy-svn at scipy.org Tue Sep 9 10:03:24 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 9 Sep 2008 09:03:24 -0500 (CDT) Subject: [Numpy-svn] r5798 - in branches/1.1.x/numpy/lib: . tests Message-ID: <20080909140324.5484539C23D@scipy.org> Author: stefan Date: 2008-09-09 09:03:08 -0500 (Tue, 09 Sep 2008) New Revision: 5798 Modified: branches/1.1.x/numpy/lib/io.py branches/1.1.x/numpy/lib/tests/test_io.py Log: Backport bugfix for #908 made on mainline in r5797. Modified: branches/1.1.x/numpy/lib/io.py =================================================================== --- branches/1.1.x/numpy/lib/io.py 2008-09-09 13:38:34 UTC (rev 5797) +++ branches/1.1.x/numpy/lib/io.py 2008-09-09 14:03:08 UTC (rev 5798) @@ -275,6 +275,8 @@ SeeAlso: scipy.io.loadmat to read and write matfiles. """ user_converters = converters + if usecols is not None: + usecols = list(usecols) if _string_like(fname): if fname.endswith('.gz'): @@ -321,6 +323,8 @@ first_vals = None while not first_vals: first_line = fh.readline() + if first_line == '': # EOF reached + raise IOError('End-of-file reached before encountering data.') first_vals = split_line(first_line) N = len(usecols or first_vals) Modified: branches/1.1.x/numpy/lib/tests/test_io.py =================================================================== --- branches/1.1.x/numpy/lib/tests/test_io.py 2008-09-09 13:38:34 UTC (rev 5797) +++ branches/1.1.x/numpy/lib/tests/test_io.py 2008-09-09 14:03:08 UTC (rev 5798) @@ -82,7 +82,6 @@ y = np.loadtxt(d, dtype=mydescriptor) assert_array_equal(y, b) - def test_array(self): c = StringIO.StringIO() c.write('1 2\n3 4') @@ -163,6 +162,9 @@ x = np.loadtxt(c, dtype=float, usecols=(1,2)) assert_array_equal(x, a[:,1:]) + def test_empty_file(self): + c = StringIO.StringIO() + assert_raises(IOError, np.loadtxt, c) class Testfromregex(NumpyTestCase): def test_record(self): From numpy-svn at scipy.org Tue Sep 9 13:48:54 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 9 Sep 2008 12:48:54 -0500 (CDT) Subject: [Numpy-svn] r5799 - in trunk/numpy: core/tests fft/tests lib lib/tests ma/tests testing Message-ID: <20080909174854.CD9FA39C23D@scipy.org> Author: alan.mcintyre Date: 2008-09-09 12:48:47 -0500 (Tue, 09 Sep 2008) New Revision: 5799 Modified: trunk/numpy/core/tests/test_regression.py trunk/numpy/core/tests/test_scalarmath.py trunk/numpy/core/tests/test_umath.py trunk/numpy/fft/tests/test_fftpack.py trunk/numpy/fft/tests/test_helper.py trunk/numpy/lib/arraysetops.py trunk/numpy/lib/tests/test__datasource.py trunk/numpy/lib/tests/test_function_base.py trunk/numpy/ma/tests/test_old_ma.py trunk/numpy/ma/tests/test_subclassing.py trunk/numpy/testing/utils.py Log: Removed unused imports. Modified: trunk/numpy/core/tests/test_regression.py =================================================================== --- trunk/numpy/core/tests/test_regression.py 2008-09-09 14:03:08 UTC (rev 5798) +++ trunk/numpy/core/tests/test_regression.py 2008-09-09 17:48:47 UTC (rev 5799) @@ -87,7 +87,6 @@ def test_char_dump(self,level=rlevel): """Ticket #50""" - import tempfile f = StringIO() ca = np.char.array(np.arange(1000,1010),itemsize=4) ca.dump(f) Modified: trunk/numpy/core/tests/test_scalarmath.py =================================================================== --- trunk/numpy/core/tests/test_scalarmath.py 2008-09-09 14:03:08 UTC (rev 5798) +++ trunk/numpy/core/tests/test_scalarmath.py 2008-09-09 17:48:47 UTC (rev 5799) @@ -1,5 +1,4 @@ from numpy.testing import * -import numpy.core.umath as ncu import numpy as np types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc, @@ -77,7 +76,6 @@ class TestRepr(TestCase): def test_float_repr(self): - from numpy import nan, inf for t in [np.float32, np.float64, np.longdouble]: if t is np.longdouble: # skip it for now. continue Modified: trunk/numpy/core/tests/test_umath.py =================================================================== --- trunk/numpy/core/tests/test_umath.py 2008-09-09 14:03:08 UTC (rev 5798) +++ trunk/numpy/core/tests/test_umath.py 2008-09-09 17:48:47 UTC (rev 5799) @@ -1,8 +1,6 @@ from numpy.testing import * import numpy.core.umath as ncu import numpy as np -import nose -from numpy import inf, nan, pi class TestDivision(TestCase): def test_division_int(self): Modified: trunk/numpy/fft/tests/test_fftpack.py =================================================================== --- trunk/numpy/fft/tests/test_fftpack.py 2008-09-09 14:03:08 UTC (rev 5798) +++ trunk/numpy/fft/tests/test_fftpack.py 2008-09-09 17:48:47 UTC (rev 5799) @@ -1,4 +1,3 @@ -import sys from numpy.testing import * import numpy as np Modified: trunk/numpy/fft/tests/test_helper.py =================================================================== --- trunk/numpy/fft/tests/test_helper.py 2008-09-09 14:03:08 UTC (rev 5798) +++ trunk/numpy/fft/tests/test_helper.py 2008-09-09 17:48:47 UTC (rev 5799) @@ -3,7 +3,6 @@ """ Test functions for fftpack.helper module """ -import sys from numpy.testing import * from numpy.fft import fftshift,ifftshift,fftfreq Modified: trunk/numpy/lib/arraysetops.py =================================================================== --- trunk/numpy/lib/arraysetops.py 2008-09-09 14:03:08 UTC (rev 5798) +++ trunk/numpy/lib/arraysetops.py 2008-09-09 17:48:47 UTC (rev 5799) @@ -35,7 +35,6 @@ __all__ = ['ediff1d', 'unique1d', 'intersect1d', 'intersect1d_nu', 'setxor1d', 'setmember1d', 'union1d', 'setdiff1d'] -import time import numpy as np def ediff1d(ary, to_end=None, to_begin=None): Modified: trunk/numpy/lib/tests/test__datasource.py =================================================================== --- trunk/numpy/lib/tests/test__datasource.py 2008-09-09 14:03:08 UTC (rev 5798) +++ trunk/numpy/lib/tests/test__datasource.py 2008-09-09 17:48:47 UTC (rev 5799) @@ -1,7 +1,4 @@ - import os -import sys -import struct from tempfile import mkdtemp, mkstemp, NamedTemporaryFile from shutil import rmtree from urlparse import urlparse Modified: trunk/numpy/lib/tests/test_function_base.py =================================================================== --- trunk/numpy/lib/tests/test_function_base.py 2008-09-09 14:03:08 UTC (rev 5798) +++ trunk/numpy/lib/tests/test_function_base.py 2008-09-09 17:48:47 UTC (rev 5799) @@ -1,4 +1,3 @@ -import sys import warnings from numpy.testing import * Modified: trunk/numpy/ma/tests/test_old_ma.py =================================================================== --- trunk/numpy/ma/tests/test_old_ma.py 2008-09-09 14:03:08 UTC (rev 5798) +++ trunk/numpy/ma/tests/test_old_ma.py 2008-09-09 17:48:47 UTC (rev 5799) @@ -1,5 +1,5 @@ import numpy -import types, time +import types from numpy.ma import * from numpy.core.numerictypes import float32 from numpy.ma.core import umath Modified: trunk/numpy/ma/tests/test_subclassing.py =================================================================== --- trunk/numpy/ma/tests/test_subclassing.py 2008-09-09 14:03:08 UTC (rev 5798) +++ trunk/numpy/ma/tests/test_subclassing.py 2008-09-09 17:48:47 UTC (rev 5799) @@ -11,8 +11,6 @@ __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' import numpy as np -import numpy.core.numeric as numeric - from numpy.testing import * from numpy.ma.testutils import * from numpy.ma.core import * Modified: trunk/numpy/testing/utils.py =================================================================== --- trunk/numpy/testing/utils.py 2008-09-09 14:03:08 UTC (rev 5798) +++ trunk/numpy/testing/utils.py 2008-09-09 17:48:47 UTC (rev 5799) @@ -241,7 +241,6 @@ def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header=''): from numpy.core import asarray, isnan, any - from numpy import isreal, iscomplex x = asarray(x) y = asarray(y) From numpy-svn at scipy.org Tue Sep 9 14:25:18 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 9 Sep 2008 13:25:18 -0500 (CDT) Subject: [Numpy-svn] r5800 - in trunk/numpy/ma: . tests Message-ID: <20080909182518.5123C39C23D@scipy.org> Author: pierregm Date: 2008-09-09 13:25:15 -0500 (Tue, 09 Sep 2008) New Revision: 5800 Modified: trunk/numpy/ma/core.py trunk/numpy/ma/tests/test_core.py Log: * make sure that minimum & maximum actually return a MaskedArray Modified: trunk/numpy/ma/core.py =================================================================== --- trunk/numpy/ma/core.py 2008-09-09 17:48:47 UTC (rev 5799) +++ trunk/numpy/ma/core.py 2008-09-09 18:25:15 UTC (rev 5800) @@ -3231,6 +3231,8 @@ mb = getmaskarray(b) m = logical_or.outer(ma, mb) result = self.ufunc.outer(filled(a), filled(b)) + if not isinstance(result, MaskedArray): + result = result.view(MaskedArray) result._mask = m return result Modified: trunk/numpy/ma/tests/test_core.py =================================================================== --- trunk/numpy/ma/tests/test_core.py 2008-09-09 17:48:47 UTC (rev 5799) +++ trunk/numpy/ma/tests/test_core.py 2008-09-09 18:25:15 UTC (rev 5800) @@ -656,6 +656,23 @@ x[-1,-1] = masked assert_equal(maximum(x), 2) + def test_minimummaximum_func(self): + a = np.ones((2,2)) + aminimum = minimum(a,a) + assert(isinstance(aminimum, MaskedArray)) + assert_equal(aminimum, np.minimum(a,a)) + # + aminimum = minimum.outer(a,a) + assert(isinstance(aminimum, MaskedArray)) + assert_equal(aminimum, np.minimum.outer(a,a)) + # + amaximum = maximum(a,a) + assert(isinstance(amaximum, MaskedArray)) + assert_equal(amaximum, np.maximum(a,a)) + # + amaximum = maximum.outer(a,a) + assert(isinstance(amaximum, MaskedArray)) + assert_equal(amaximum, np.maximum.outer(a,a)) def test_minmax_funcs_with_output(self): "Tests the min/max functions with explicit outputs" From numpy-svn at scipy.org Wed Sep 10 03:54:13 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 10 Sep 2008 02:54:13 -0500 (CDT) Subject: [Numpy-svn] r5801 - tags Message-ID: <20080910075413.66B9B39C02A@scipy.org> Author: jarrod.millman Date: 2008-09-10 02:54:09 -0500 (Wed, 10 Sep 2008) New Revision: 5801 Added: tags/1.2.0rc2/ Log: tag for release candidate Copied: tags/1.2.0rc2 (from rev 5800, branches/1.2.x) From numpy-svn at scipy.org Wed Sep 10 03:56:11 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 10 Sep 2008 02:56:11 -0500 (CDT) Subject: [Numpy-svn] r5802 - tags/1.2.0rc2/numpy Message-ID: <20080910075611.6161E39C02A@scipy.org> Author: jarrod.millman Date: 2008-09-10 02:56:09 -0500 (Wed, 10 Sep 2008) New Revision: 5802 Modified: tags/1.2.0rc2/numpy/version.py Log: updating version info Modified: tags/1.2.0rc2/numpy/version.py =================================================================== --- tags/1.2.0rc2/numpy/version.py 2008-09-10 07:54:09 UTC (rev 5801) +++ tags/1.2.0rc2/numpy/version.py 2008-09-10 07:56:09 UTC (rev 5802) @@ -1,5 +1,5 @@ -version='1.2.0' -release=False +version='1.2.0rc2' +release=True if not release: version += '.dev' From numpy-svn at scipy.org Thu Sep 11 15:54:35 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 11 Sep 2008 14:54:35 -0500 (CDT) Subject: [Numpy-svn] r5803 - in trunk/numpy/ma: . tests Message-ID: <20080911195435.36B8339C02D@scipy.org> Author: pierregm Date: 2008-09-11 14:54:31 -0500 (Thu, 11 Sep 2008) New Revision: 5803 Modified: trunk/numpy/ma/core.py trunk/numpy/ma/tests/test_core.py Log: * fixed view for MaskedArrays w/ flexible dtype Modified: trunk/numpy/ma/core.py =================================================================== --- trunk/numpy/ma/core.py 2008-09-10 07:56:09 UTC (rev 5802) +++ trunk/numpy/ma/core.py 2008-09-11 19:54:31 UTC (rev 5803) @@ -1257,9 +1257,9 @@ copy = True # Careful, cls might not always be MaskedArray... if not isinstance(data, cls) or not subok: - _data = _data.view(cls) + _data = ndarray.view(_data, cls) else: - _data = _data.view(type(data)) + _data = ndarray.view(_data, type(data)) # Backwards compatibility w/ numpy.core.ma ....... if hasattr(data,'_mask') and not isinstance(data, ndarray): _data._mask = data._mask @@ -1374,7 +1374,15 @@ """ # Get main attributes ......... self._update_from(obj) - self._mask = getattr(obj, '_mask', nomask) + if isinstance(obj, ndarray): + odtype = obj.dtype + if odtype.names: + _mask = getattr(obj, '_mask', make_mask_none(obj.shape, odtype)) + else: + _mask = getattr(obj, '_mask', nomask) + else: + _mask = nomask + self._mask = _mask # Finalize the mask ........... if self._mask is not nomask: self._mask.shape = self.shape @@ -1425,6 +1433,24 @@ #.... return result #............................................. + def view(self, dtype=None, type=None): + if dtype is not None: + if type is None: + args = (dtype,) + else: + args = (dtype, type) + elif type is None: + args = () + else: + args = (type,) + output = ndarray.view(self, *args) + if (getattr(output,'_mask', nomask) is not nomask): + mdtype = make_mask_descr(output.dtype) + output._mask = self._mask.view(mdtype, ndarray) + output._mask.shape = output.shape + return output + view.__doc__ = ndarray.view.__doc__ + #............................................. def astype(self, newtype): """Returns a copy of the array cast to newtype.""" newtype = np.dtype(newtype) @@ -1701,7 +1727,7 @@ underlying data. """ - return self.view(self._baseclass) + return ndarray.view(self, self._baseclass) _data = property(fget=_get_data) data = property(fget=_get_data) Modified: trunk/numpy/ma/tests/test_core.py =================================================================== --- trunk/numpy/ma/tests/test_core.py 2008-09-10 07:56:09 UTC (rev 5802) +++ trunk/numpy/ma/tests/test_core.py 2008-09-11 19:54:31 UTC (rev 5803) @@ -2342,6 +2342,34 @@ assert_equal(getmaskarray(test), np.array([(1, 1) , (1, 1), (1, 1)], dtype=[('a', '|b1'), ('b', '|b1')])) + # + def test_view(self): + "Test view w/ flexible dtype" + iterator = zip(np.arange(10), np.random.rand(10)) + data = np.array(iterator) + a = array(iterator, dtype=[('a',float),('b',float)]) + a.mask[0] = (1,0) + controlmask = np.array([1]+19*[0], dtype=bool) + # + test = a.view(float) + assert_equal(test, data.ravel()) + assert_equal(test.mask, controlmask) + # + test = a.view((float,2)) + assert_equal(test, data) + assert_equal(test.mask, controlmask.reshape(-1,2)) + # + test = a.view([('A',float),('B',float)]) + assert_equal(test.mask.dtype.names, ('A', 'B')) + assert_equal(test['A'], a['a']) + assert_equal(test['B'], a['b']) + # + test = a.view(np.ndarray) + assert_equal(test, a._data) + # + test = a.view((float,2), np.matrix) + assert_equal(test, data) + assert(isinstance(test, np.matrix)) ############################################################################### From numpy-svn at scipy.org Fri Sep 12 15:20:29 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 12 Sep 2008 14:20:29 -0500 (CDT) Subject: [Numpy-svn] r5804 - trunk/doc Message-ID: <20080912192029.1A57E39C07C@scipy.org> Author: jarrod.millman Date: 2008-09-12 14:20:26 -0500 (Fri, 12 Sep 2008) New Revision: 5804 Modified: trunk/doc/HOWTO_DOCUMENT.txt Log: FIX: broken links Modified: trunk/doc/HOWTO_DOCUMENT.txt =================================================================== --- trunk/doc/HOWTO_DOCUMENT.txt 2008-09-11 19:54:31 UTC (rev 5803) +++ trunk/doc/HOWTO_DOCUMENT.txt 2008-09-12 19:20:26 UTC (rev 5804) @@ -413,10 +413,10 @@ ---------- `An example -`_ of the +`_ of the format shown here is available. Refer to `How to Build API/Reference Documentation -`_ +`_ on how to use epydoc_ or sphinx_ to construct a manual and web page. This document itself was written in ReStructuredText, and may be converted to From numpy-svn at scipy.org Fri Sep 12 15:23:22 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 12 Sep 2008 14:23:22 -0500 (CDT) Subject: [Numpy-svn] r5805 - trunk/doc Message-ID: <20080912192322.0AB3639C07C@scipy.org> Author: jarrod.millman Date: 2008-09-12 14:23:20 -0500 (Fri, 12 Sep 2008) New Revision: 5805 Modified: trunk/doc/HOWTO_BUILD_DOCS.txt Log: FIX: broken links Modified: trunk/doc/HOWTO_BUILD_DOCS.txt =================================================================== --- trunk/doc/HOWTO_BUILD_DOCS.txt 2008-09-12 19:20:26 UTC (rev 5804) +++ trunk/doc/HOWTO_BUILD_DOCS.txt 2008-09-12 19:23:20 UTC (rev 5805) @@ -50,13 +50,13 @@ Example ------- Here is a short example module, -`plain text `_ +`plain text `_ or `rendered `_ in HTML. To try this yourself, simply download the example.py:: - svn co http://svn.scipy.org/svn/numpy/trunk/numpy/doc/example.py . + svn co http://svn.scipy.org/svn/numpy/trunk/doc/example.py . Then, run epydoc:: From numpy-svn at scipy.org Fri Sep 12 22:53:56 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 12 Sep 2008 21:53:56 -0500 (CDT) Subject: [Numpy-svn] r5806 - trunk/numpy/core Message-ID: <20080913025356.AC8B339C072@scipy.org> Author: alan.mcintyre Date: 2008-09-12 21:53:53 -0500 (Fri, 12 Sep 2008) New Revision: 5806 Modified: trunk/numpy/core/fromnumeric.py trunk/numpy/core/numeric.py Log: Fix failing doctests. Modified: trunk/numpy/core/fromnumeric.py =================================================================== --- trunk/numpy/core/fromnumeric.py 2008-09-12 19:23:20 UTC (rev 5805) +++ trunk/numpy/core/fromnumeric.py 2008-09-13 02:53:53 UTC (rev 5806) @@ -1617,12 +1617,14 @@ >>> x = np.array([1, 2, 3], dtype=np.uint8) >>> np.prod(x).dtype == np.uint + True If `x` is of a signed integer type, then the output type is the default platform integer: >>> x = np.array([1, 2, 3], dtype=np.int8) >>> np.prod(x).dtype == np.int + True """ try: Modified: trunk/numpy/core/numeric.py =================================================================== --- trunk/numpy/core/numeric.py 2008-09-12 19:23:20 UTC (rev 5805) +++ trunk/numpy/core/numeric.py 2008-09-13 02:53:53 UTC (rev 5806) @@ -765,7 +765,7 @@ >>> b = np.arange(24.).reshape(4,3,2) >>> c = np.tensordot(a,b, axes=([1,0],[0,1])) >>> c.shape - (5,2) + (5, 2) >>> c array([[ 4400., 4730.], [ 4532., 4874.], @@ -774,7 +774,7 @@ [ 4928., 5306.]]) >>> # A slower but equivalent way of computing the same... - >>> c = zeros((5,2)) + >>> c = np.zeros((5,2)) >>> for i in range(5): ... for j in range(2): ... for k in range(3): From numpy-svn at scipy.org Fri Sep 12 22:56:35 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 12 Sep 2008 21:56:35 -0500 (CDT) Subject: [Numpy-svn] r5807 - trunk/numpy/distutils/tests Message-ID: <20080913025635.6347339C072@scipy.org> Author: alan.mcintyre Date: 2008-09-12 21:56:33 -0500 (Fri, 12 Sep 2008) New Revision: 5807 Modified: trunk/numpy/distutils/tests/test_misc_util.py Log: Remove unused imports. Modified: trunk/numpy/distutils/tests/test_misc_util.py =================================================================== --- trunk/numpy/distutils/tests/test_misc_util.py 2008-09-13 02:53:53 UTC (rev 5806) +++ trunk/numpy/distutils/tests/test_misc_util.py 2008-09-13 02:56:33 UTC (rev 5807) @@ -1,10 +1,8 @@ #!/usr/bin/env python -import os -import sys from numpy.testing import * from numpy.distutils.misc_util import appendpath, minrelpath, gpaths, rel_path -from os.path import join, sep +from os.path import join, sep, dirname ajoin = lambda *paths: join(*((sep,)+paths)) @@ -35,8 +33,7 @@ class TestMinrelpath(TestCase): def test_1(self): - import os - n = lambda path: path.replace('/',os.path.sep) + n = lambda path: path.replace('/',sep) assert_equal(minrelpath(n('aa/bb')),n('aa/bb')) assert_equal(minrelpath('..'),'..') assert_equal(minrelpath(n('aa/..')),'') @@ -50,11 +47,11 @@ class TestGpaths(TestCase): def test_gpaths(self): - local_path = minrelpath(os.path.join(os.path.dirname(__file__),'..')) + local_path = minrelpath(join(dirname(__file__),'..')) ls = gpaths('command/*.py', local_path) - assert os.path.join(local_path,'command','build_src.py') in ls,`ls` + assert join(local_path,'command','build_src.py') in ls,`ls` f = gpaths('system_info.py', local_path) - assert os.path.join(local_path,'system_info.py')==f[0],`f` + assert join(local_path,'system_info.py')==f[0],`f` if __name__ == "__main__": From numpy-svn at scipy.org Fri Sep 12 23:41:00 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 12 Sep 2008 22:41:00 -0500 (CDT) Subject: [Numpy-svn] r5808 - trunk/numpy/numarray Message-ID: <20080913034100.7FBEF39C072@scipy.org> Author: alan.mcintyre Date: 2008-09-12 22:40:57 -0500 (Fri, 12 Sep 2008) New Revision: 5808 Modified: trunk/numpy/numarray/alter_code2.py trunk/numpy/numarray/functions.py trunk/numpy/numarray/numerictypes.py trunk/numpy/numarray/session.py trunk/numpy/numarray/util.py Log: Removed unused/duplicate imports. Removed repeated members of __all__. Fixed reference to undefined "out" in functions.py:take function. Fixed references to undefined "N" in functions.py. Rewrapped lines to conform to PEP8. Fixed references to undefined FPE_* constants (from numpy) in util.py. Modified: trunk/numpy/numarray/alter_code2.py =================================================================== --- trunk/numpy/numarray/alter_code2.py 2008-09-13 02:56:33 UTC (rev 5807) +++ trunk/numpy/numarray/alter_code2.py 2008-09-13 03:40:57 UTC (rev 5808) @@ -12,12 +12,9 @@ warnings.warn("numpy.numarray.alter_code2 is not working yet.") import sys - import os -import re import glob - def makenewfile(name, filestr): fid = file(name, 'w') fid.write(filestr) Modified: trunk/numpy/numarray/functions.py =================================================================== --- trunk/numpy/numarray/functions.py 2008-09-13 02:56:33 UTC (rev 5807) +++ trunk/numpy/numarray/functions.py 2008-09-13 03:40:57 UTC (rev 5808) @@ -20,13 +20,13 @@ 'any', 'argmax', 'argmin', 'argsort', 'around', 'array_equal', 'array_equiv', 'arrayrange', 'array_str', 'array_repr', 'array2list', 'average', 'choose', 'CLIP', 'RAISE', 'WRAP', - 'clip', 'compress', 'concatenate', 'copy', 'copy_reg', + 'clip', 'compress', 'copy', 'copy_reg', 'diagonal', 'divide_remainder', 'e', 'explicit_type', 'pi', 'flush_caches', 'fromfile', 'os', 'sys', 'STRICT', 'SLOPPY', 'WARN', 'EarlyEOFError', 'SizeMismatchError', 'SizeMismatchWarning', 'FileSeekWarning', 'fromstring', 'fromfunction', 'fromlist', 'getShape', 'getTypeObject', - 'identity', 'indices', 'info', 'innerproduct', 'inputarray', + 'identity', 'info', 'innerproduct', 'inputarray', 'isBigEndian', 'kroneckerproduct', 'lexsort', 'math', 'operator', 'outerproduct', 'put', 'putmask', 'rank', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', @@ -45,9 +45,9 @@ import operator from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate, all,\ - allclose, any, around, argsort, array_equal, array_equiv,\ + allclose, any, argsort, array_equal, array_equiv,\ array_str, array_repr, CLIP, RAISE, WRAP, clip, concatenate, \ - diagonal, e, pi, indices, inner as innerproduct, nonzero, \ + diagonal, e, pi, inner as innerproduct, nonzero, \ outer as outerproduct, kron as kroneckerproduct, lexsort, putmask, rank, \ resize, searchsorted, shape, size, sort, swapaxes, trace, transpose import numpy as np @@ -321,7 +321,7 @@ if type is not None: return type try: - return typefrom(N.array(sequence)) + return typefrom(np.array(sequence)) except: raise TypeError("Can't determine a reasonable type from sequence") @@ -458,7 +458,7 @@ res = work[indices] if outarr is None: return res - out[...] = res + outarr[...] = res return def tensormultiply(a1, a2): @@ -466,9 +466,9 @@ if (a1.shape[-1] != a2.shape[0]): raise ValueError("Unmatched dimensions") shape = a1.shape[:-1] + a2.shape[1:] - return np.reshape(dot(N.reshape(a1, (-1, a1.shape[-1])), - np.reshape(a2, (a2.shape[0],-1))), - shape) + return np.reshape(dot(np.reshape(a1, (-1, a1.shape[-1])), + np.reshape(a2, (a2.shape[0],-1))), + shape) def cumsum(a1, axis=0, out=None, type=None, dim=0): return np.asarray(a1).cumsum(axis,dtype=type,out=out) Modified: trunk/numpy/numarray/numerictypes.py =================================================================== --- trunk/numpy/numarray/numerictypes.py 2008-09-13 02:56:33 UTC (rev 5807) +++ trunk/numpy/numarray/numerictypes.py 2008-09-13 03:40:57 UTC (rev 5808) @@ -54,9 +54,6 @@ #from typeconv import typeConverters as _typeConverters #import numinclude #from _numerictype import _numerictype, typeDict -import types as _types -import copy as _copy -import sys as _sys # Enumeration of numarray type codes typeDict = {} Modified: trunk/numpy/numarray/session.py =================================================================== --- trunk/numpy/numarray/session.py 2008-09-13 02:56:33 UTC (rev 5807) +++ trunk/numpy/numarray/session.py 2008-09-13 03:40:57 UTC (rev 5808) @@ -16,7 +16,6 @@ to keep the test run free of warnings. >>> del _PROXY_ALLOWED ->>> del copy >>> del __builtins__ By default, save() stores every variable in the caller's namespace: @@ -76,7 +75,6 @@ __all__ = ['load', 'save'] -import copy import sys import pickle Modified: trunk/numpy/numarray/util.py =================================================================== --- trunk/numpy/numarray/util.py 2008-09-13 02:56:33 UTC (rev 5807) +++ trunk/numpy/numarray/util.py 2008-09-13 03:40:57 UTC (rev 5808) @@ -1,7 +1,8 @@ -from numpy import geterr +import os +import numpy -__all__ = ['MathDomainError', 'UnderflowError', 'NumOverflowError', 'handleError', - 'get_numarray_include_dirs'] +__all__ = ['MathDomainError', 'UnderflowError', 'NumOverflowError', + 'handleError', 'get_numarray_include_dirs'] class MathDomainError(ArithmeticError): pass class UnderflowError(ArithmeticError): pass @@ -9,31 +10,29 @@ def handleError(errorStatus, sourcemsg): """Take error status and use error mode to handle it.""" - modes = geterr() - if errorStatus & FPE_INVALID: + modes = numpy.geterr() + if errorStatus & numpy.FPE_INVALID: if modes['invalid'] == "warn": print "Warning: Encountered invalid numeric result(s)", sourcemsg if modes['invalid'] == "raise": raise MathDomainError(sourcemsg) - if errorStatus & FPE_DIVIDEBYZERO: + if errorStatus & numpy.FPE_DIVIDEBYZERO: if modes['dividebyzero'] == "warn": print "Warning: Encountered divide by zero(s)", sourcemsg if modes['dividebyzero'] == "raise": raise ZeroDivisionError(sourcemsg) - if errorStatus & FPE_OVERFLOW: + if errorStatus & numpy.FPE_OVERFLOW: if modes['overflow'] == "warn": print "Warning: Encountered overflow(s)", sourcemsg if modes['overflow'] == "raise": raise NumOverflowError(sourcemsg) - if errorStatus & FPE_UNDERFLOW: + if errorStatus & numpy.FPE_UNDERFLOW: if modes['underflow'] == "warn": print "Warning: Encountered underflow(s)", sourcemsg if modes['underflow'] == "raise": raise UnderflowError(sourcemsg) -import os -import numpy def get_numarray_include_dirs(): base = os.path.dirname(numpy.__file__) newdirs = [os.path.join(base, 'numarray')] From numpy-svn at scipy.org Sat Sep 13 02:03:34 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 01:03:34 -0500 (CDT) Subject: [Numpy-svn] r5809 - trunk/numpy/core/include/numpy/fenv Message-ID: <20080913060334.0DF6D39C072@scipy.org> Author: cdavid Date: 2008-09-13 01:03:30 -0500 (Sat, 13 Sep 2008) New Revision: 5809 Modified: trunk/numpy/core/include/numpy/fenv/fenv.h Log: Fix cygwin compilation Recent version of binutils (2.18.50) do not accept 4 bytes operand for some opcodes like fnstsw (which always expected a 2 bytes operand). Replace the type of the argument from unsigned 2 bytes to unsigned 4 bytes unsigned integer. Modified: trunk/numpy/core/include/numpy/fenv/fenv.h =================================================================== --- trunk/numpy/core/include/numpy/fenv/fenv.h 2008-09-13 03:40:57 UTC (rev 5808) +++ trunk/numpy/core/include/numpy/fenv/fenv.h 2008-09-13 06:03:30 UTC (rev 5809) @@ -91,7 +91,7 @@ static __inline int fegetexceptflag(fexcept_t *__flagp, int __excepts) { - int __status; + __uint16_t __status; __fnstsw(&__status); *__flagp = __status & __excepts; @@ -123,7 +123,7 @@ static __inline int fetestexcept(int __excepts) { - int __status; + __uint16_t __status; __fnstsw(&__status); return (__status & __excepts); @@ -187,7 +187,7 @@ static __inline int feupdateenv(const fenv_t *__envp) { - int __status; + __uint16_t __status; __fnstsw(&__status); __fldenv(*__envp); From numpy-svn at scipy.org Sat Sep 13 02:28:25 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 01:28:25 -0500 (CDT) Subject: [Numpy-svn] r5810 - trunk/numpy/tests Message-ID: <20080913062825.A9D5B39C072@scipy.org> Author: cdavid Date: 2008-09-13 01:27:46 -0500 (Sat, 13 Sep 2008) New Revision: 5810 Modified: trunk/numpy/tests/test_ctypeslib.py Log: Tag ctypes load library tests as known failures on cygwin. Modified: trunk/numpy/tests/test_ctypeslib.py =================================================================== --- trunk/numpy/tests/test_ctypeslib.py 2008-09-13 06:03:30 UTC (rev 5809) +++ trunk/numpy/tests/test_ctypeslib.py 2008-09-13 06:27:46 UTC (rev 5810) @@ -1,3 +1,5 @@ +import sys + import numpy as np from numpy.ctypeslib import ndpointer, load_library from numpy.testing import * @@ -3,4 +5,5 @@ class TestLoadLibrary(TestCase): + @dec.knownfailureif(sys.platform=='cygwin', "This test is known to fail on cygwin") def test_basic(self): try: @@ -12,6 +15,7 @@ " (import error was: %s)" % str(e) print msg + @dec.knownfailureif(sys.platform=='cygwin', "This test is known to fail on cygwin") def test_basic2(self): """Regression for #801: load_library with a full library name (including extension) does not work.""" From numpy-svn at scipy.org Sat Sep 13 02:34:29 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 01:34:29 -0500 (CDT) Subject: [Numpy-svn] r5811 - branches/1.1.x/numpy/distutils/fcompiler Message-ID: <20080913063429.2C75539C072@scipy.org> Author: cdavid Date: 2008-09-13 01:34:25 -0500 (Sat, 13 Sep 2008) New Revision: 5811 Modified: branches/1.1.x/numpy/distutils/fcompiler/__init__.py Log: Backport fcompiler debug fix from trunk (5689). Modified: branches/1.1.x/numpy/distutils/fcompiler/__init__.py =================================================================== --- branches/1.1.x/numpy/distutils/fcompiler/__init__.py 2008-09-13 06:27:46 UTC (rev 5810) +++ branches/1.1.x/numpy/distutils/fcompiler/__init__.py 2008-09-13 06:34:25 UTC (rev 5811) @@ -129,7 +129,7 @@ arch = ('flags.arch', 'FARCH', 'arch', flaglist), arch_f77 = ('flags.arch_f77', None, None, flaglist), arch_f90 = ('flags.arch_f90', None, None, flaglist), - debug = ('flags.debug', 'FDEBUG', 'fdebug', None, flaglist), + debug = ('flags.debug', 'FDEBUG', 'fdebug', flaglist), debug_f77 = ('flags.debug_f77', None, None, flaglist), debug_f90 = ('flags.debug_f90', None, None, flaglist), flags = ('self.get_flags', 'FFLAGS', 'fflags', flaglist), From numpy-svn at scipy.org Sat Sep 13 03:05:52 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 02:05:52 -0500 (CDT) Subject: [Numpy-svn] r5812 - in branches/clean_math_config: . doc doc/neps numpy/core numpy/core/include/numpy/fenv numpy/core/src numpy/core/tests numpy/distutils/command numpy/distutils/tests numpy/f2py numpy/fft/tests numpy/lib numpy/lib/tests numpy/ma numpy/ma/tests numpy/numarray numpy/testing numpy/tests Message-ID: <20080913070552.E4A6B39C072@scipy.org> Author: cdavid Date: 2008-09-13 02:04:41 -0500 (Sat, 13 Sep 2008) New Revision: 5812 Added: branches/clean_math_config/doc/neps/datetime-proposal3.rst Removed: branches/clean_math_config/doc/neps/datetime.rst Modified: branches/clean_math_config/ branches/clean_math_config/doc/HOWTO_BUILD_DOCS.txt branches/clean_math_config/doc/HOWTO_DOCUMENT.txt branches/clean_math_config/numpy/core/fromnumeric.py branches/clean_math_config/numpy/core/include/numpy/fenv/fenv.h branches/clean_math_config/numpy/core/numeric.py branches/clean_math_config/numpy/core/src/ufuncobject.c branches/clean_math_config/numpy/core/tests/test_regression.py branches/clean_math_config/numpy/core/tests/test_scalarmath.py branches/clean_math_config/numpy/core/tests/test_umath.py branches/clean_math_config/numpy/distutils/command/scons.py branches/clean_math_config/numpy/distutils/tests/test_misc_util.py branches/clean_math_config/numpy/f2py/crackfortran.py branches/clean_math_config/numpy/fft/tests/test_fftpack.py branches/clean_math_config/numpy/fft/tests/test_helper.py branches/clean_math_config/numpy/lib/arraysetops.py branches/clean_math_config/numpy/lib/io.py branches/clean_math_config/numpy/lib/tests/test__datasource.py branches/clean_math_config/numpy/lib/tests/test_function_base.py branches/clean_math_config/numpy/lib/tests/test_io.py branches/clean_math_config/numpy/ma/core.py branches/clean_math_config/numpy/ma/tests/test_core.py branches/clean_math_config/numpy/ma/tests/test_old_ma.py branches/clean_math_config/numpy/ma/tests/test_subclassing.py branches/clean_math_config/numpy/numarray/alter_code2.py branches/clean_math_config/numpy/numarray/functions.py branches/clean_math_config/numpy/numarray/numerictypes.py branches/clean_math_config/numpy/numarray/session.py branches/clean_math_config/numpy/numarray/util.py branches/clean_math_config/numpy/testing/decorators.py branches/clean_math_config/numpy/testing/noseclasses.py branches/clean_math_config/numpy/testing/nosetester.py branches/clean_math_config/numpy/testing/utils.py branches/clean_math_config/numpy/tests/test_ctypeslib.py Log: Merged revisions 5762-5811 via svnmerge from http://svn.scipy.org/svn/numpy/trunk ........ r5768 | ptvirtan | 2008-09-05 03:04:35 +0900 (Fri, 05 Sep 2008) | 1 line Ufunc docstrings: show the 'out' arguments in a more standard way ........ r5769 | alan.mcintyre | 2008-09-05 03:23:48 +0900 (Fri, 05 Sep 2008) | 4 lines Replaced numpy.testing.decorators.skipknownfailure with knownfailureif, which allows flagging tests as known failures rather than skips. Updated test_umath to use knownfailureif. ........ r5770 | alan.mcintyre | 2008-09-05 06:13:29 +0900 (Fri, 05 Sep 2008) | 2 lines Renamed classes to conform to PEP 8. ........ r5771 | alan.mcintyre | 2008-09-05 07:06:01 +0900 (Fri, 05 Sep 2008) | 2 lines Fix link to example.py. ........ r5772 | alan.mcintyre | 2008-09-05 10:20:09 +0900 (Fri, 05 Sep 2008) | 2 lines Remove debugging code. ........ r5788 | dhuard | 2008-09-05 22:58:00 +0900 (Fri, 05 Sep 2008) | 1 line Applied patch from R. May fixing ticket #905 (loadtxt). Fixed other bug occurring when both usecols and converters are provided. Added related regression tests. ........ r5789 | oliphant | 2008-09-05 23:06:02 +0900 (Fri, 05 Sep 2008) | 1 line Add final date-time proposal. ........ r5791 | pierregm | 2008-09-06 08:38:44 +0900 (Sat, 06 Sep 2008) | 1 line * fixed deepcopy of masked arrays (bug #906) ........ r5793 | cdavid | 2008-09-07 16:16:28 +0900 (Sun, 07 Sep 2008) | 8 lines scons command: fix one more issue related to build dir. The distutils installation directory relative to the scons build directory was not always computed right. The relative position on the fs does not depend on the source directory (in out-of-place builds), but on the package *name* translated to a directly only. ........ r5796 | pearu | 2008-09-09 19:55:30 +0900 (Tue, 09 Sep 2008) | 1 line Fix typo. ........ r5797 | stefan | 2008-09-09 22:38:34 +0900 (Tue, 09 Sep 2008) | 2 lines FIX: Loadtxt raises on empty input (closes #908). ........ r5799 | alan.mcintyre | 2008-09-10 02:48:47 +0900 (Wed, 10 Sep 2008) | 2 lines Removed unused imports. ........ r5800 | pierregm | 2008-09-10 03:25:15 +0900 (Wed, 10 Sep 2008) | 1 line * make sure that minimum & maximum actually return a MaskedArray ........ r5803 | pierregm | 2008-09-12 04:54:31 +0900 (Fri, 12 Sep 2008) | 1 line * fixed view for MaskedArrays w/ flexible dtype ........ r5804 | jarrod.millman | 2008-09-13 04:20:26 +0900 (Sat, 13 Sep 2008) | 2 lines FIX: broken links ........ r5805 | jarrod.millman | 2008-09-13 04:23:20 +0900 (Sat, 13 Sep 2008) | 2 lines FIX: broken links ........ r5806 | alan.mcintyre | 2008-09-13 11:53:53 +0900 (Sat, 13 Sep 2008) | 2 lines Fix failing doctests. ........ r5807 | alan.mcintyre | 2008-09-13 11:56:33 +0900 (Sat, 13 Sep 2008) | 2 lines Remove unused imports. ........ r5808 | alan.mcintyre | 2008-09-13 12:40:57 +0900 (Sat, 13 Sep 2008) | 7 lines Removed unused/duplicate imports. Removed repeated members of __all__. Fixed reference to undefined "out" in functions.py:take function. Fixed references to undefined "N" in functions.py. Rewrapped lines to conform to PEP8. Fixed references to undefined FPE_* constants (from numpy) in util.py. ........ r5809 | cdavid | 2008-09-13 15:03:30 +0900 (Sat, 13 Sep 2008) | 6 lines Fix cygwin compilation Recent version of binutils (2.18.50) do not accept 4 bytes operand for some opcodes like fnstsw (which always expected a 2 bytes operand). Replace the type of the argument from unsigned 2 bytes to unsigned 4 bytes unsigned integer. ........ r5810 | cdavid | 2008-09-13 15:27:46 +0900 (Sat, 13 Sep 2008) | 1 line Tag ctypes load library tests as known failures on cygwin. ........ Property changes on: branches/clean_math_config ___________________________________________________________________ Name: svnmerge-integrated - /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5761 + /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5811 Modified: branches/clean_math_config/doc/HOWTO_BUILD_DOCS.txt =================================================================== --- branches/clean_math_config/doc/HOWTO_BUILD_DOCS.txt 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/doc/HOWTO_BUILD_DOCS.txt 2008-09-13 07:04:41 UTC (rev 5812) @@ -50,13 +50,13 @@ Example ------- Here is a short example module, -`plain text `_ +`plain text `_ or `rendered `_ in HTML. To try this yourself, simply download the example.py:: - svn co http://svn.scipy.org/svn/numpy/trunk/numpy/doc/example.py . + svn co http://svn.scipy.org/svn/numpy/trunk/doc/example.py . Then, run epydoc:: Modified: branches/clean_math_config/doc/HOWTO_DOCUMENT.txt =================================================================== --- branches/clean_math_config/doc/HOWTO_DOCUMENT.txt 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/doc/HOWTO_DOCUMENT.txt 2008-09-13 07:04:41 UTC (rev 5812) @@ -7,7 +7,7 @@ .. Note:: For an accompanying example, see `example.py - `_. + `_. Overview -------- @@ -413,10 +413,10 @@ ---------- `An example -`_ of the +`_ of the format shown here is available. Refer to `How to Build API/Reference Documentation -`_ +`_ on how to use epydoc_ or sphinx_ to construct a manual and web page. This document itself was written in ReStructuredText, and may be converted to Copied: branches/clean_math_config/doc/neps/datetime-proposal3.rst (from rev 5810, trunk/doc/neps/datetime-proposal3.rst) Deleted: branches/clean_math_config/doc/neps/datetime.rst =================================================================== --- branches/clean_math_config/doc/neps/datetime.rst 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/doc/neps/datetime.rst 2008-09-13 07:04:41 UTC (rev 5812) @@ -1,354 +0,0 @@ -==================================================================== - A (second) proposal for implementing some date/time types in NumPy -==================================================================== - -:Author: Francesc Alted i Abad -:Contact: faltet at pytables.com -:Author: Ivan Vilata i Balaguer -:Contact: ivan at selidor.net -:Date: 2008-07-16 - - -Executive summary -================= - -A date/time mark is something very handy to have in many fields where -one has to deal with data sets. While Python has several modules that -define a date/time type (like the integrated ``datetime`` [1]_ or -``mx.DateTime`` [2]_), NumPy has a lack of them. - -In this document, we are proposing the addition of a series of date/time -types to fill this gap. The requirements for the proposed types are -two-folded: 1) they have to be fast to operate with and 2) they have to -be as compatible as possible with the existing ``datetime`` module that -comes with Python. - - -Types proposed -============== - -To start with, it is virtually impossible to come up with a single -date/time type that fills the needs of every case of use. So, after -pondering about different possibilities, we have stick with *two* -different types, namely ``datetime64`` and ``timedelta64`` (these names -are preliminary and can be changed), that can have different resolutions -so as to cover different needs. - -**Important note:** the resolution is conceived here as a metadata that - *complements* a date/time dtype, *without changing the base type*. - -Now it goes a detailed description of the proposed types. - - -``datetime64`` --------------- - -It represents a time that is absolute (i.e. not relative). It is -implemented internally as an ``int64`` type. The internal epoch is -POSIX epoch (see [3]_). - -Resolution -~~~~~~~~~~ - -It accepts different resolutions and for each of these resolutions, it -will support different time spans. The table below describes the -resolutions supported with its corresponding time spans. - -+----------------------+----------------------------------+ -| Resolution | Time span (years) | -+----------------------+----------------------------------+ -| Code | Meaning | | -+======================+==================================+ -| Y | year | [9.2e18 BC, 9.2e18 AC] | -| Q | quarter | [3.0e18 BC, 3.0e18 AC] | -| M | month | [7.6e17 BC, 7.6e17 AC] | -| W | week | [1.7e17 BC, 1.7e17 AC] | -| d | day | [2.5e16 BC, 2.5e16 AC] | -| h | hour | [1.0e15 BC, 1.0e15 AC] | -| m | minute | [1.7e13 BC, 1.7e13 AC] | -| s | second | [ 2.9e9 BC, 2.9e9 AC] | -| ms | millisecond | [ 2.9e6 BC, 2.9e6 AC] | -| us | microsecond | [290301 BC, 294241 AC] | -| ns | nanosecond | [ 1678 AC, 2262 AC] | -+----------------------+----------------------------------+ - -Building a ``datetime64`` dtype -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The proposed way to specify the resolution in the dtype constructor -is: - -Using parameters in the constructor:: - - dtype('datetime64', res="us") # the default res. is microseconds - -Using the long string notation:: - - dtype('datetime64[us]') # equivalent to dtype('datetime64') - -Using the short string notation:: - - dtype('T8[us]') # equivalent to dtype('T8') - -Compatibility issues -~~~~~~~~~~~~~~~~~~~~ - -This will be fully compatible with the ``datetime`` class of the -``datetime`` module of Python only when using a resolution of -microseconds. For other resolutions, the conversion process will -loose precision or will overflow as needed. - - -``timedelta64`` ---------------- - -It represents a time that is relative (i.e. not absolute). It is -implemented internally as an ``int64`` type. - -Resolution -~~~~~~~~~~ - -It accepts different resolutions and for each of these resolutions, it -will support different time spans. The table below describes the -resolutions supported with its corresponding time spans. - -+----------------------+--------------------------+ -| Resolution | Time span | -+----------------------+--------------------------+ -| Code | Meaning | | -+======================+==========================+ -| W | week | +- 1.7e17 years | -| D | day | +- 2.5e16 years | -| h | hour | +- 1.0e15 years | -| m | minute | +- 1.7e13 years | -| s | second | +- 2.9e12 years | -| ms | millisecond | +- 2.9e9 years | -| us | microsecond | +- 2.9e6 years | -| ns | nanosecond | +- 292 years | -| ps | picosecond | +- 106 days | -| fs | femtosecond | +- 2.6 hours | -| as | attosecond | +- 9.2 seconds | -+----------------------+--------------------------+ - -Building a ``timedelta64`` dtype -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The proposed way to specify the resolution in the dtype constructor -is: - -Using parameters in the constructor:: - - dtype('timedelta64', res="us") # the default res. is microseconds - -Using the long string notation:: - - dtype('timedelta64[us]') # equivalent to dtype('datetime64') - -Using the short string notation:: - - dtype('t8[us]') # equivalent to dtype('t8') - -Compatibility issues -~~~~~~~~~~~~~~~~~~~~ - -This will be fully compatible with the ``timedelta`` class of the -``datetime`` module of Python only when using a resolution of -microseconds. For other resolutions, the conversion process will -loose precision or will overflow as needed. - - -Example of use -============== - -Here it is an example of use for the ``datetime64``:: - - In [10]: t = numpy.zeros(5, dtype="datetime64[ms]") - - In [11]: t[0] = datetime.datetime.now() # setter in action - - In [12]: t[0] - Out[12]: '2008-07-16T13:39:25.315' # representation in ISO 8601 format - - In [13]: print t - [2008-07-16T13:39:25.315 1970-01-01T00:00:00.0 - 1970-01-01T00:00:00.0 1970-01-01T00:00:00.0 1970-01-01T00:00:00.0] - - In [14]: t[0].item() # getter in action - Out[14]: datetime.datetime(2008, 7, 16, 13, 39, 25, 315000) - - In [15]: print t.dtype - datetime64[ms] - -And here it goes an example of use for the ``timedelta64``:: - - In [8]: t1 = numpy.zeros(5, dtype="datetime64[s]") - - In [9]: t2 = numpy.ones(5, dtype="datetime64[s]") - - In [10]: t = t2 - t1 - - In [11]: t[0] = 24 # setter in action (setting to 24 seconds) - - In [12]: t[0] - Out[12]: 24 # representation as an int64 - - In [13]: print t - [24 1 1 1 1] - - In [14]: t[0].item() # getter in action - Out[14]: datetime.timedelta(0, 24) - - In [15]: print t.dtype - timedelta64[s] - - -Operating with date/time arrays -=============================== - -``datetime64`` vs ``datetime64`` --------------------------------- - -The only operation allowed between absolute dates is the subtraction:: - - In [10]: numpy.ones(5, "T8") - numpy.zeros(5, "T8") - Out[10]: array([1, 1, 1, 1, 1], dtype=timedelta64[us]) - -But not other operations:: - - In [11]: numpy.ones(5, "T8") + numpy.zeros(5, "T8") - TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'numpy.ndarray' - -``datetime64`` vs ``timedelta64`` ---------------------------------- - -It will be possible to add and subtract relative times from absolute -dates:: - - In [10]: numpy.zeros(5, "T8[Y]") + numpy.ones(5, "t8[Y]") - Out[10]: array([1971, 1971, 1971, 1971, 1971], dtype=datetime64[Y]) - - In [11]: numpy.ones(5, "T8[Y]") - 2 * numpy.ones(5, "t8[Y]") - Out[11]: array([1969, 1969, 1969, 1969, 1969], dtype=datetime64[Y]) - -But not other operations:: - - In [12]: numpy.ones(5, "T8[Y]") * numpy.ones(5, "t8[Y]") - TypeError: unsupported operand type(s) for *: 'numpy.ndarray' and 'numpy.ndarray' - -``timedelta64`` vs anything ---------------------------- - -Finally, it will be possible to operate with relative times as if they -were regular int64 dtypes *as long as* the result can be converted back -into a ``timedelta64``:: - - In [10]: numpy.ones(5, 't8') - Out[10]: array([1, 1, 1, 1, 1], dtype=timedelta64[us]) - - In [11]: (numpy.ones(5, 't8[M]') + 2) ** 3 - Out[11]: array([27, 27, 27, 27, 27], dtype=timedelta64[M]) - -But:: - - In [12]: numpy.ones(5, 't8') + 1j - TypeError: The result cannot be converted into a ``timedelta64`` - - -dtype/resolution conversions -============================ - -For changing the date/time dtype of an existing array, we propose to use -the ``.astype()`` method. This will be mainly useful for changing -resolutions. - -For example, for absolute dates:: - - In[10]: t1 = numpy.zeros(5, dtype="datetime64[s]") - - In[11]: print t1 - [1970-01-01T00:00:00 1970-01-01T00:00:00 1970-01-01T00:00:00 - 1970-01-01T00:00:00 1970-01-01T00:00:00] - - In[12]: print t1.astype('datetime64[d]') - [1970-01-01 1970-01-01 1970-01-01 1970-01-01 1970-01-01] - -For relative times:: - - In[10]: t1 = numpy.ones(5, dtype="timedelta64[s]") - - In[11]: print t1 - [1 1 1 1 1] - - In[12]: print t1.astype('timedelta64[ms]') - [1000 1000 1000 1000 1000] - -Changing directly from/to relative to/from absolute dtypes will not be -supported:: - - In[13]: numpy.zeros(5, dtype="datetime64[s]").astype('timedelta64') - TypeError: data type cannot be converted to the desired type - - -Final considerations -==================== - -Why the ``origin`` metadata disappeared ---------------------------------------- - -During the discussion of the date/time dtypes in the NumPy list, the -idea of having an ``origin`` metadata that complemented the definition -of the absolute ``datetime64`` was initially found to be useful. - -However, after thinking more about this, Ivan and me find that the -combination of an absolute ``datetime64`` with a relative -``timedelta64`` does offer the same functionality while removing the -need for the additional ``origin`` metadata. This is why we have -removed it from this proposal. - - -Resolution and dtype issues ---------------------------- - -The date/time dtype's resolution metadata cannot be used in general as -part of typical dtype usage. For example, in:: - - numpy.zeros(5, dtype=numpy.datetime64) - -we have to found yet a sensible way to pass the resolution. Perhaps the -next would work:: - - numpy.zeros(5, dtype=numpy.datetime64(res='Y')) - -but we are not sure if this would collide with the spirit of the NumPy -dtypes. - -At any rate, one can always do:: - - numpy.zeros(5, dtype=numpy.dtype('datetime64', res='Y')) - -BTW, prior to all of this, one should also elucidate whether:: - - numpy.dtype('datetime64', res='Y') - -or:: - - numpy.dtype('datetime64[Y]') - numpy.dtype('T8[Y]') - -would be a consistent way to instantiate a dtype in NumPy. We do really -think that could be a good way, but we would need to hear the opinion of -the expert. Travis? - - - -.. [1] http://docs.python.org/lib/module-datetime.html -.. [2] http://www.egenix.com/products/python/mxBase/mxDateTime -.. [3] http://en.wikipedia.org/wiki/Unix_time - - -.. Local Variables: -.. mode: rst -.. coding: utf-8 -.. fill-column: 72 -.. End: - Modified: branches/clean_math_config/numpy/core/fromnumeric.py =================================================================== --- branches/clean_math_config/numpy/core/fromnumeric.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/core/fromnumeric.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -1617,12 +1617,14 @@ >>> x = np.array([1, 2, 3], dtype=np.uint8) >>> np.prod(x).dtype == np.uint + True If `x` is of a signed integer type, then the output type is the default platform integer: >>> x = np.array([1, 2, 3], dtype=np.int8) >>> np.prod(x).dtype == np.int + True """ try: Modified: branches/clean_math_config/numpy/core/include/numpy/fenv/fenv.h =================================================================== --- branches/clean_math_config/numpy/core/include/numpy/fenv/fenv.h 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/core/include/numpy/fenv/fenv.h 2008-09-13 07:04:41 UTC (rev 5812) @@ -91,7 +91,7 @@ static __inline int fegetexceptflag(fexcept_t *__flagp, int __excepts) { - int __status; + __uint16_t __status; __fnstsw(&__status); *__flagp = __status & __excepts; @@ -123,7 +123,7 @@ static __inline int fetestexcept(int __excepts) { - int __status; + __uint16_t __status; __fnstsw(&__status); return (__status & __excepts); @@ -187,7 +187,7 @@ static __inline int feupdateenv(const fenv_t *__envp) { - int __status; + __uint16_t __status; __fnstsw(&__status); __fldenv(*__envp); Modified: branches/clean_math_config/numpy/core/numeric.py =================================================================== --- branches/clean_math_config/numpy/core/numeric.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/core/numeric.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -765,7 +765,7 @@ >>> b = np.arange(24.).reshape(4,3,2) >>> c = np.tensordot(a,b, axes=([1,0],[0,1])) >>> c.shape - (5,2) + (5, 2) >>> c array([[ 4400., 4730.], [ 4532., 4874.], @@ -774,7 +774,7 @@ [ 4928., 5306.]]) >>> # A slower but equivalent way of computing the same... - >>> c = zeros((5,2)) + >>> c = np.zeros((5,2)) >>> for i in range(5): ... for j in range(2): ... for k in range(3): Modified: branches/clean_math_config/numpy/core/src/ufuncobject.c =================================================================== --- branches/clean_math_config/numpy/core/src/ufuncobject.c 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/core/src/ufuncobject.c 2008-09-13 07:04:41 UTC (rev 5812) @@ -4046,19 +4046,20 @@ y1,y2,...,yn */ static PyObject * -_makeargs(int num, char *ltr) +_makeargs(int num, char *ltr, int null_if_none) { PyObject *str; int i; switch (num) { case 0: + if (null_if_none) return NULL; return PyString_FromString(""); case 1: return PyString_FromString(ltr); } - str = PyString_FromFormat("%s1,%s2", ltr, ltr); + str = PyString_FromFormat("%s1, %s2", ltr, ltr); for(i = 3; i <= num; ++i) { - PyString_ConcatAndDel(&str, PyString_FromFormat(",%s%d", ltr, i)); + PyString_ConcatAndDel(&str, PyString_FromFormat(", %s%d", ltr, i)); } return str; } @@ -4082,17 +4083,26 @@ /* to automate the first part of it */ /* the doc string shouldn't need the calling convention */ /* construct - y1,y2,,... = name(x1,x2,...) __doc__ + name(x1, x2, ...,[ out1, out2, ...]) + + __doc__ */ PyObject *outargs, *inargs, *doc; - outargs = _makeargs(self->nout, "y"); - inargs = _makeargs(self->nin, "x"); - doc = PyString_FromFormat("%s = %s(%s)\n\n%s", - PyString_AS_STRING(outargs), - self->name, - PyString_AS_STRING(inargs), - self->doc); - Py_DECREF(outargs); + outargs = _makeargs(self->nout, "out", 1); + inargs = _makeargs(self->nin, "x", 0); + if (outargs == NULL) { + doc = PyString_FromFormat("%s(%s)\n\n%s", + self->name, + PyString_AS_STRING(inargs), + self->doc); + } else { + doc = PyString_FromFormat("%s(%s[, %s])\n\n%s", + self->name, + PyString_AS_STRING(inargs), + PyString_AS_STRING(outargs), + self->doc); + Py_DECREF(outargs); + } Py_DECREF(inargs); return doc; } Modified: branches/clean_math_config/numpy/core/tests/test_regression.py =================================================================== --- branches/clean_math_config/numpy/core/tests/test_regression.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/core/tests/test_regression.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -87,7 +87,6 @@ def test_char_dump(self,level=rlevel): """Ticket #50""" - import tempfile f = StringIO() ca = np.char.array(np.arange(1000,1010),itemsize=4) ca.dump(f) Modified: branches/clean_math_config/numpy/core/tests/test_scalarmath.py =================================================================== --- branches/clean_math_config/numpy/core/tests/test_scalarmath.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/core/tests/test_scalarmath.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -1,5 +1,4 @@ from numpy.testing import * -import numpy.core.umath as ncu import numpy as np types = [np.bool_, np.byte, np.ubyte, np.short, np.ushort, np.intc, np.uintc, @@ -77,7 +76,6 @@ class TestRepr(TestCase): def test_float_repr(self): - from numpy import nan, inf for t in [np.float32, np.float64, np.longdouble]: if t is np.longdouble: # skip it for now. continue Modified: branches/clean_math_config/numpy/core/tests/test_umath.py =================================================================== --- branches/clean_math_config/numpy/core/tests/test_umath.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/core/tests/test_umath.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -1,8 +1,6 @@ from numpy.testing import * import numpy.core.umath as ncu import numpy as np -import nose -from numpy import inf, nan, pi class TestDivision(TestCase): def test_division_int(self): @@ -229,6 +227,7 @@ yield _check_branch_cut, np.arccosh, [-2j, 2j, 2], [1, 1, 1j], 1, 1 yield _check_branch_cut, np.arctanh, [-2j, 2j, 0], [1, 1, 1j], 1, 1 + @dec.knownfailureif(True, "These branch cuts are known to fail") def test_branch_cuts_failing(self): # XXX: signed zeros are not OK for sqrt or for the arc* functions yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True @@ -238,7 +237,6 @@ yield _check_branch_cut, np.arcsinh, [-2j, 2j], [-1, 1], -1, 1, True yield _check_branch_cut, np.arccosh, [ -1, 0.5], [1j, 1j], 1, -1, True yield _check_branch_cut, np.arctanh, [ -2, 2], [1j, -1j], 1, -1, True - test_branch_cuts_failing = dec.skipknownfailure(test_branch_cuts_failing) def test_against_cmath(self): import cmath, sys @@ -271,7 +269,7 @@ def test_attributes(self): add = ncu.add assert_equal(add.__name__, 'add') - assert add.__doc__.startswith('y = add(x1,x2)\n\n') + assert add.__doc__.startswith('add(x1, x2[, out])\n\n') self.failUnless(add.ntypes >= 18) # don't fail if types added self.failUnless('ii->i' in add.types) assert_equal(add.nin, 2) Modified: branches/clean_math_config/numpy/distutils/command/scons.py =================================================================== --- branches/clean_math_config/numpy/distutils/command/scons.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/distutils/command/scons.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -44,11 +44,12 @@ from numscons import get_scons_path return get_scons_path() -def get_distutils_libdir(cmd, sconscript_path): +def get_distutils_libdir(cmd, pkg): """Returns the path where distutils install libraries, relatively to the scons build directory.""" from numscons import get_scons_build_dir - scdir = pjoin(get_scons_build_dir(), pdirname(sconscript_path)) + from numscons.core.utils import pkg_to_path + scdir = pjoin(get_scons_build_dir(), pkg_to_path(pkg)) n = scdir.count(os.sep) return pjoin(os.sep.join([os.pardir for i in range(n+1)]), cmd.build_lib) @@ -424,7 +425,7 @@ #cmd.append('distutils_libdir=%s' % protect_path(pjoin(self.build_lib, # pdirname(sconscript)))) cmd.append('distutils_libdir=%s' % - protect_path(get_distutils_libdir(self, sconscript))) + protect_path(get_distutils_libdir(self, pkg_name))) if not self._bypass_distutils_cc: cmd.append('cc_opt=%s' % self.scons_compiler) Modified: branches/clean_math_config/numpy/distutils/tests/test_misc_util.py =================================================================== --- branches/clean_math_config/numpy/distutils/tests/test_misc_util.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/distutils/tests/test_misc_util.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -1,10 +1,8 @@ #!/usr/bin/env python -import os -import sys from numpy.testing import * from numpy.distutils.misc_util import appendpath, minrelpath, gpaths, rel_path -from os.path import join, sep +from os.path import join, sep, dirname ajoin = lambda *paths: join(*((sep,)+paths)) @@ -35,8 +33,7 @@ class TestMinrelpath(TestCase): def test_1(self): - import os - n = lambda path: path.replace('/',os.path.sep) + n = lambda path: path.replace('/',sep) assert_equal(minrelpath(n('aa/bb')),n('aa/bb')) assert_equal(minrelpath('..'),'..') assert_equal(minrelpath(n('aa/..')),'') @@ -50,11 +47,11 @@ class TestGpaths(TestCase): def test_gpaths(self): - local_path = minrelpath(os.path.join(os.path.dirname(__file__),'..')) + local_path = minrelpath(join(dirname(__file__),'..')) ls = gpaths('command/*.py', local_path) - assert os.path.join(local_path,'command','build_src.py') in ls,`ls` + assert join(local_path,'command','build_src.py') in ls,`ls` f = gpaths('system_info.py', local_path) - assert os.path.join(local_path,'system_info.py')==f[0],`f` + assert join(local_path,'system_info.py')==f[0],`f` if __name__ == "__main__": Modified: branches/clean_math_config/numpy/f2py/crackfortran.py =================================================================== --- branches/clean_math_config/numpy/f2py/crackfortran.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/f2py/crackfortran.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -327,7 +327,7 @@ if rl[:4].lower()=='f2py': # f2py directive l = l + 4*' ' r=commentline.match(rl[4:]) - if r: l=l+r('line') + if r: l=l+r.group('line') else: l = l + rl[4:] if l.strip()=='': # Skip empty line cont=0 Modified: branches/clean_math_config/numpy/fft/tests/test_fftpack.py =================================================================== --- branches/clean_math_config/numpy/fft/tests/test_fftpack.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/fft/tests/test_fftpack.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -1,4 +1,3 @@ -import sys from numpy.testing import * import numpy as np Modified: branches/clean_math_config/numpy/fft/tests/test_helper.py =================================================================== --- branches/clean_math_config/numpy/fft/tests/test_helper.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/fft/tests/test_helper.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -3,7 +3,6 @@ """ Test functions for fftpack.helper module """ -import sys from numpy.testing import * from numpy.fft import fftshift,ifftshift,fftfreq Modified: branches/clean_math_config/numpy/lib/arraysetops.py =================================================================== --- branches/clean_math_config/numpy/lib/arraysetops.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/lib/arraysetops.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -35,7 +35,6 @@ __all__ = ['ediff1d', 'unique1d', 'intersect1d', 'intersect1d_nu', 'setxor1d', 'setmember1d', 'union1d', 'setdiff1d'] -import time import numpy as np def ediff1d(ary, to_end=None, to_begin=None): Modified: branches/clean_math_config/numpy/lib/io.py =================================================================== --- branches/clean_math_config/numpy/lib/io.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/lib/io.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -313,6 +313,9 @@ """ user_converters = converters + if usecols is not None: + usecols = list(usecols) + if _string_like(fname): if fname.endswith('.gz'): import gzip @@ -358,6 +361,8 @@ first_vals = None while not first_vals: first_line = fh.readline() + if first_line == '': # EOF reached + raise IOError('End-of-file reached before encountering data.') first_vals = split_line(first_line) N = len(usecols or first_vals) @@ -373,7 +378,7 @@ # By preference, use the converters specified by the user for i, conv in (user_converters or {}).iteritems(): if usecols: - i = usecols.find(i) + i = usecols.index(i) converters[i] = conv # Parse each line, including the first Modified: branches/clean_math_config/numpy/lib/tests/test__datasource.py =================================================================== --- branches/clean_math_config/numpy/lib/tests/test__datasource.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/lib/tests/test__datasource.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -1,7 +1,4 @@ - import os -import sys -import struct from tempfile import mkdtemp, mkstemp, NamedTemporaryFile from shutil import rmtree from urlparse import urlparse Modified: branches/clean_math_config/numpy/lib/tests/test_function_base.py =================================================================== --- branches/clean_math_config/numpy/lib/tests/test_function_base.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/lib/tests/test_function_base.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -1,4 +1,3 @@ -import sys import warnings from numpy.testing import * Modified: branches/clean_math_config/numpy/lib/tests/test_io.py =================================================================== --- branches/clean_math_config/numpy/lib/tests/test_io.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/lib/tests/test_io.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -140,7 +140,6 @@ y = np.loadtxt(d, dtype=mydescriptor) assert_array_equal(y, b) - def test_array(self): c = StringIO.StringIO() c.write('1 2\n3 4') @@ -170,7 +169,6 @@ 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') @@ -180,6 +178,16 @@ 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') @@ -221,6 +229,11 @@ 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 @@ -241,6 +254,9 @@ 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) class Testfromregex(TestCase): def test_record(self): Modified: branches/clean_math_config/numpy/ma/core.py =================================================================== --- branches/clean_math_config/numpy/ma/core.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/ma/core.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -1257,9 +1257,9 @@ copy = True # Careful, cls might not always be MaskedArray... if not isinstance(data, cls) or not subok: - _data = _data.view(cls) + _data = ndarray.view(_data, cls) else: - _data = _data.view(type(data)) + _data = ndarray.view(_data, type(data)) # Backwards compatibility w/ numpy.core.ma ....... if hasattr(data,'_mask') and not isinstance(data, ndarray): _data._mask = data._mask @@ -1374,7 +1374,15 @@ """ # Get main attributes ......... self._update_from(obj) - self._mask = getattr(obj, '_mask', nomask) + if isinstance(obj, ndarray): + odtype = obj.dtype + if odtype.names: + _mask = getattr(obj, '_mask', make_mask_none(obj.shape, odtype)) + else: + _mask = getattr(obj, '_mask', nomask) + else: + _mask = nomask + self._mask = _mask # Finalize the mask ........... if self._mask is not nomask: self._mask.shape = self.shape @@ -1425,6 +1433,24 @@ #.... return result #............................................. + def view(self, dtype=None, type=None): + if dtype is not None: + if type is None: + args = (dtype,) + else: + args = (dtype, type) + elif type is None: + args = () + else: + args = (type,) + output = ndarray.view(self, *args) + if (getattr(output,'_mask', nomask) is not nomask): + mdtype = make_mask_descr(output.dtype) + output._mask = self._mask.view(mdtype, ndarray) + output._mask.shape = output.shape + return output + view.__doc__ = ndarray.view.__doc__ + #............................................. def astype(self, newtype): """Returns a copy of the array cast to newtype.""" newtype = np.dtype(newtype) @@ -1701,7 +1727,7 @@ underlying data. """ - return self.view(self._baseclass) + return ndarray.view(self, self._baseclass) _data = property(fget=_get_data) data = property(fget=_get_data) @@ -3123,6 +3149,14 @@ return (_mareconstruct, (self.__class__, self._baseclass, (0,), 'b', ), self.__getstate__()) + # + def __deepcopy__(self, memo={}): + from copy import deepcopy + copied = MaskedArray.__new__(type(self), self, copy=True) + memo[id(self)] = copied + for (k,v) in self.__dict__.iteritems(): + copied.__dict__[k] = deepcopy(v, memo) + return copied def _mareconstruct(subtype, baseclass, baseshape, basetype,): @@ -3223,6 +3257,8 @@ mb = getmaskarray(b) m = logical_or.outer(ma, mb) result = self.ufunc.outer(filled(a), filled(b)) + if not isinstance(result, MaskedArray): + result = result.view(MaskedArray) result._mask = m return result Modified: branches/clean_math_config/numpy/ma/tests/test_core.py =================================================================== --- branches/clean_math_config/numpy/ma/tests/test_core.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/ma/tests/test_core.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -330,6 +330,24 @@ assert_not_equal(y._mask.ctypes.data, x._mask.ctypes.data) + def test_deepcopy(self): + from copy import deepcopy + a = array([0,1,2], mask=[False,True,False]) + copied = deepcopy(a) + assert_equal(copied.mask, a.mask) + assert_not_equal(id(a._mask), id(copied._mask)) + # + copied[1] = 1 + assert_equal(copied.mask,[0,0,0]) + assert_equal(a.mask, [0,1,0]) + # + copied = deepcopy(a) + assert_equal(copied.mask, a.mask) + copied.mask[1] = False + assert_equal(copied.mask,[0,0,0]) + assert_equal(a.mask, [0,1,0]) + + def test_pickling(self): "Tests pickling" import cPickle @@ -638,6 +656,23 @@ x[-1,-1] = masked assert_equal(maximum(x), 2) + def test_minimummaximum_func(self): + a = np.ones((2,2)) + aminimum = minimum(a,a) + assert(isinstance(aminimum, MaskedArray)) + assert_equal(aminimum, np.minimum(a,a)) + # + aminimum = minimum.outer(a,a) + assert(isinstance(aminimum, MaskedArray)) + assert_equal(aminimum, np.minimum.outer(a,a)) + # + amaximum = maximum(a,a) + assert(isinstance(amaximum, MaskedArray)) + assert_equal(amaximum, np.maximum(a,a)) + # + amaximum = maximum.outer(a,a) + assert(isinstance(amaximum, MaskedArray)) + assert_equal(amaximum, np.maximum.outer(a,a)) def test_minmax_funcs_with_output(self): "Tests the min/max functions with explicit outputs" @@ -2307,6 +2342,34 @@ assert_equal(getmaskarray(test), np.array([(1, 1) , (1, 1), (1, 1)], dtype=[('a', '|b1'), ('b', '|b1')])) + # + def test_view(self): + "Test view w/ flexible dtype" + iterator = zip(np.arange(10), np.random.rand(10)) + data = np.array(iterator) + a = array(iterator, dtype=[('a',float),('b',float)]) + a.mask[0] = (1,0) + controlmask = np.array([1]+19*[0], dtype=bool) + # + test = a.view(float) + assert_equal(test, data.ravel()) + assert_equal(test.mask, controlmask) + # + test = a.view((float,2)) + assert_equal(test, data) + assert_equal(test.mask, controlmask.reshape(-1,2)) + # + test = a.view([('A',float),('B',float)]) + assert_equal(test.mask.dtype.names, ('A', 'B')) + assert_equal(test['A'], a['a']) + assert_equal(test['B'], a['b']) + # + test = a.view(np.ndarray) + assert_equal(test, a._data) + # + test = a.view((float,2), np.matrix) + assert_equal(test, data) + assert(isinstance(test, np.matrix)) ############################################################################### Modified: branches/clean_math_config/numpy/ma/tests/test_old_ma.py =================================================================== --- branches/clean_math_config/numpy/ma/tests/test_old_ma.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/ma/tests/test_old_ma.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -1,5 +1,5 @@ import numpy -import types, time +import types from numpy.ma import * from numpy.core.numerictypes import float32 from numpy.ma.core import umath Modified: branches/clean_math_config/numpy/ma/tests/test_subclassing.py =================================================================== --- branches/clean_math_config/numpy/ma/tests/test_subclassing.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/ma/tests/test_subclassing.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -11,8 +11,6 @@ __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' import numpy as np -import numpy.core.numeric as numeric - from numpy.testing import * from numpy.ma.testutils import * from numpy.ma.core import * Modified: branches/clean_math_config/numpy/numarray/alter_code2.py =================================================================== --- branches/clean_math_config/numpy/numarray/alter_code2.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/numarray/alter_code2.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -12,12 +12,9 @@ warnings.warn("numpy.numarray.alter_code2 is not working yet.") import sys - import os -import re import glob - def makenewfile(name, filestr): fid = file(name, 'w') fid.write(filestr) Modified: branches/clean_math_config/numpy/numarray/functions.py =================================================================== --- branches/clean_math_config/numpy/numarray/functions.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/numarray/functions.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -20,13 +20,13 @@ 'any', 'argmax', 'argmin', 'argsort', 'around', 'array_equal', 'array_equiv', 'arrayrange', 'array_str', 'array_repr', 'array2list', 'average', 'choose', 'CLIP', 'RAISE', 'WRAP', - 'clip', 'compress', 'concatenate', 'copy', 'copy_reg', + 'clip', 'compress', 'copy', 'copy_reg', 'diagonal', 'divide_remainder', 'e', 'explicit_type', 'pi', 'flush_caches', 'fromfile', 'os', 'sys', 'STRICT', 'SLOPPY', 'WARN', 'EarlyEOFError', 'SizeMismatchError', 'SizeMismatchWarning', 'FileSeekWarning', 'fromstring', 'fromfunction', 'fromlist', 'getShape', 'getTypeObject', - 'identity', 'indices', 'info', 'innerproduct', 'inputarray', + 'identity', 'info', 'innerproduct', 'inputarray', 'isBigEndian', 'kroneckerproduct', 'lexsort', 'math', 'operator', 'outerproduct', 'put', 'putmask', 'rank', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', @@ -45,9 +45,9 @@ import operator from numpy import dot as matrixmultiply, dot, vdot, ravel, concatenate, all,\ - allclose, any, around, argsort, array_equal, array_equiv,\ + allclose, any, argsort, array_equal, array_equiv,\ array_str, array_repr, CLIP, RAISE, WRAP, clip, concatenate, \ - diagonal, e, pi, indices, inner as innerproduct, nonzero, \ + diagonal, e, pi, inner as innerproduct, nonzero, \ outer as outerproduct, kron as kroneckerproduct, lexsort, putmask, rank, \ resize, searchsorted, shape, size, sort, swapaxes, trace, transpose import numpy as np @@ -321,7 +321,7 @@ if type is not None: return type try: - return typefrom(N.array(sequence)) + return typefrom(np.array(sequence)) except: raise TypeError("Can't determine a reasonable type from sequence") @@ -458,7 +458,7 @@ res = work[indices] if outarr is None: return res - out[...] = res + outarr[...] = res return def tensormultiply(a1, a2): @@ -466,9 +466,9 @@ if (a1.shape[-1] != a2.shape[0]): raise ValueError("Unmatched dimensions") shape = a1.shape[:-1] + a2.shape[1:] - return np.reshape(dot(N.reshape(a1, (-1, a1.shape[-1])), - np.reshape(a2, (a2.shape[0],-1))), - shape) + return np.reshape(dot(np.reshape(a1, (-1, a1.shape[-1])), + np.reshape(a2, (a2.shape[0],-1))), + shape) def cumsum(a1, axis=0, out=None, type=None, dim=0): return np.asarray(a1).cumsum(axis,dtype=type,out=out) Modified: branches/clean_math_config/numpy/numarray/numerictypes.py =================================================================== --- branches/clean_math_config/numpy/numarray/numerictypes.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/numarray/numerictypes.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -54,9 +54,6 @@ #from typeconv import typeConverters as _typeConverters #import numinclude #from _numerictype import _numerictype, typeDict -import types as _types -import copy as _copy -import sys as _sys # Enumeration of numarray type codes typeDict = {} Modified: branches/clean_math_config/numpy/numarray/session.py =================================================================== --- branches/clean_math_config/numpy/numarray/session.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/numarray/session.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -16,7 +16,6 @@ to keep the test run free of warnings. >>> del _PROXY_ALLOWED ->>> del copy >>> del __builtins__ By default, save() stores every variable in the caller's namespace: @@ -76,7 +75,6 @@ __all__ = ['load', 'save'] -import copy import sys import pickle Modified: branches/clean_math_config/numpy/numarray/util.py =================================================================== --- branches/clean_math_config/numpy/numarray/util.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/numarray/util.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -1,7 +1,8 @@ -from numpy import geterr +import os +import numpy -__all__ = ['MathDomainError', 'UnderflowError', 'NumOverflowError', 'handleError', - 'get_numarray_include_dirs'] +__all__ = ['MathDomainError', 'UnderflowError', 'NumOverflowError', + 'handleError', 'get_numarray_include_dirs'] class MathDomainError(ArithmeticError): pass class UnderflowError(ArithmeticError): pass @@ -9,31 +10,29 @@ def handleError(errorStatus, sourcemsg): """Take error status and use error mode to handle it.""" - modes = geterr() - if errorStatus & FPE_INVALID: + modes = numpy.geterr() + if errorStatus & numpy.FPE_INVALID: if modes['invalid'] == "warn": print "Warning: Encountered invalid numeric result(s)", sourcemsg if modes['invalid'] == "raise": raise MathDomainError(sourcemsg) - if errorStatus & FPE_DIVIDEBYZERO: + if errorStatus & numpy.FPE_DIVIDEBYZERO: if modes['dividebyzero'] == "warn": print "Warning: Encountered divide by zero(s)", sourcemsg if modes['dividebyzero'] == "raise": raise ZeroDivisionError(sourcemsg) - if errorStatus & FPE_OVERFLOW: + if errorStatus & numpy.FPE_OVERFLOW: if modes['overflow'] == "warn": print "Warning: Encountered overflow(s)", sourcemsg if modes['overflow'] == "raise": raise NumOverflowError(sourcemsg) - if errorStatus & FPE_UNDERFLOW: + if errorStatus & numpy.FPE_UNDERFLOW: if modes['underflow'] == "warn": print "Warning: Encountered underflow(s)", sourcemsg if modes['underflow'] == "raise": raise UnderflowError(sourcemsg) -import os -import numpy def get_numarray_include_dirs(): base = os.path.dirname(numpy.__file__) newdirs = [os.path.join(base, 'numarray')] Modified: branches/clean_math_config/numpy/testing/decorators.py =================================================================== --- branches/clean_math_config/numpy/testing/decorators.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/testing/decorators.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -83,12 +83,41 @@ return nose.tools.make_decorator(f)(skipper) return skip_decorator -def skipknownfailure(f): - ''' Decorator to raise SkipTest for test known to fail +def knownfailureif(skip_condition, msg=None): + ''' Make function raise KnownFailureTest exception if skip_condition is true + + Parameters + --------- + skip_condition : bool + Flag to determine whether to mark test as known failure (True) + or not (False) + msg : string + Message to give on raising a KnownFailureTest exception + + Returns + ------- + decorator : function + Decorator, which, when applied to a function, causes SkipTest + to be raised when the skip_condition was True, and the function + to be called normally otherwise. + + Notes + ----- + You will see from the code that we had to further decorate the + decorator with the nose.tools.make_decorator function in order to + transmit function name, and various other metadata. ''' - # Local import to avoid a hard nose dependency and only incur the - # import time overhead at actual test-time. - import nose - def skipper(*args, **kwargs): - raise nose.SkipTest, 'This test is known to fail' - return nose.tools.make_decorator(f)(skipper) + if msg is None: + msg = 'Test skipped due to known failure' + def skip_decorator(f): + # Local import to avoid a hard nose dependency and only incur the + # import time overhead at actual test-time. + import nose + from noseclasses import KnownFailureTest + def skipper(*args, **kwargs): + if skip_condition: + raise KnownFailureTest, msg + else: + return f(*args, **kwargs) + return nose.tools.make_decorator(f)(skipper) + return skip_decorator Modified: branches/clean_math_config/numpy/testing/noseclasses.py =================================================================== --- branches/clean_math_config/numpy/testing/noseclasses.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/testing/noseclasses.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -7,6 +7,7 @@ import doctest from nose.plugins import doctests as npd +from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin from nose.plugins.base import Plugin from nose.util import src, tolist import numpy @@ -16,14 +17,14 @@ _doctest_ignore = ['generate_numpy_api.py', 'scons_support.py', 'setupscons.py', 'setup.py'] -# All the classes in this module begin with 'numpy' to clearly distinguish them -# from the plethora of very similar names from nose/unittest/doctest +# Some of the classes in this module begin with 'Numpy' to clearly distinguish +# them from the plethora of very similar names from nose/unittest/doctest #----------------------------------------------------------------------------- # Modified version of the one in the stdlib, that fixes a python bug (doctests # not found in extension modules, http://bugs.python.org/issue3158) -class numpyDocTestFinder(doctest.DocTestFinder): +class NumpyDocTestFinder(doctest.DocTestFinder): def _from_module(self, module, object): """ @@ -113,7 +114,7 @@ globs, seen) -class numpyDocTestCase(npd.DocTestCase): +class NumpyDocTestCase(npd.DocTestCase): """Proxy for DocTestCase: provides an address() method that returns the correct address for the doctest case. Otherwise acts as a proxy to the test case. To provide hints for address(), @@ -137,7 +138,7 @@ # second-chance checker; if the default comparison doesn't # pass, then see if the expected output string contains flags that # tell us to ignore the output -class numpyOutputChecker(doctest.OutputChecker): +class NumpyOutputChecker(doctest.OutputChecker): def check_output(self, want, got, optionflags): ret = doctest.OutputChecker.check_output(self, want, got, optionflags) @@ -151,7 +152,7 @@ # Subclass nose.plugins.doctests.DocTestCase to work around a bug in # its constructor that blocks non-default arguments from being passed # down into doctest.DocTestCase -class numpyDocTestCase(npd.DocTestCase): +class NumpyDocTestCase(npd.DocTestCase): def __init__(self, test, optionflags=0, setUp=None, tearDown=None, checker=None, obj=None, result_var='_'): self._result_var = result_var @@ -164,7 +165,7 @@ print_state = numpy.get_printoptions() -class numpyDoctest(npd.Doctest): +class NumpyDoctest(npd.Doctest): name = 'numpydoctest' # call nosetests with --with-numpydoctest enabled = True @@ -175,7 +176,7 @@ Plugin.configure(self, options, config) self.doctest_tests = True # self.extension = tolist(options.doctestExtension) - self.finder = numpyDocTestFinder() + self.finder = NumpyDocTestFinder() self.parser = doctest.DocTestParser() # Turn on whitespace normalization, set a minimal execution context @@ -223,15 +224,12 @@ p2 = p[-1] test.globs[p2] = __import__(pkg_name, test.globs, {}, [p2]) - print 'additional import for %s: from %s import %s' % (test.filename, p1, p2) - print ' (%s): %r' % (pkg_name, test.globs[p2]) - # always use whitespace and ellipsis options optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS - yield numpyDocTestCase(test, + yield NumpyDocTestCase(test, optionflags=optionflags, - checker=numpyOutputChecker()) + checker=NumpyOutputChecker()) # Add an afterContext method to nose.plugins.doctests.Doctest in order @@ -246,3 +244,35 @@ if bn in _doctest_ignore: return False return npd.Doctest.wantFile(self, file) + + +class KnownFailureTest(Exception): + '''Raise this exception to mark a test as a known failing test.''' + pass + + +class KnownFailure(ErrorClassPlugin): + '''Plugin that installs a KNOWNFAIL error class for the + KnownFailureClass exception. When KnownFailureTest is raised, + the exception will be logged in the knownfail attribute of the + result, 'K' or 'KNOWNFAIL' (verbose) will be output, and the + exception will not be counted as an error or failure.''' + enabled = True + knownfail = ErrorClass(KnownFailureTest, + label='KNOWNFAIL', + isfailure=False) + + def options(self, parser, env=os.environ): + env_opt = 'NOSE_WITHOUT_KNOWNFAIL' + parser.add_option('--no-knownfail', action='store_true', + dest='noKnownFail', default=env.get(env_opt, False), + help='Disable special handling of KnownFailureTest ' + 'exceptions') + + def configure(self, options, conf): + if not self.can_configure: + return + self.conf = conf + disable = getattr(options, 'noKnownFail', False) + if disable: + self.enabled = False Modified: branches/clean_math_config/numpy/testing/nosetester.py =================================================================== --- branches/clean_math_config/numpy/testing/nosetester.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/testing/nosetester.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -266,8 +266,8 @@ # construct list of plugins, omitting the existing doctest plugin import nose.plugins.builtin - from noseclasses import numpyDoctest - plugins = [numpyDoctest()] + from noseclasses import NumpyDoctest, KnownFailure + plugins = [NumpyDoctest(), KnownFailure()] for p in nose.plugins.builtin.plugins: plug = p() if plug.name == 'doctest': Modified: branches/clean_math_config/numpy/testing/utils.py =================================================================== --- branches/clean_math_config/numpy/testing/utils.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/testing/utils.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -241,7 +241,6 @@ def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header=''): from numpy.core import asarray, isnan, any - from numpy import isreal, iscomplex x = asarray(x) y = asarray(y) Modified: branches/clean_math_config/numpy/tests/test_ctypeslib.py =================================================================== --- branches/clean_math_config/numpy/tests/test_ctypeslib.py 2008-09-13 06:34:25 UTC (rev 5811) +++ branches/clean_math_config/numpy/tests/test_ctypeslib.py 2008-09-13 07:04:41 UTC (rev 5812) @@ -1,3 +1,5 @@ +import sys + import numpy as np from numpy.ctypeslib import ndpointer, load_library from numpy.testing import * @@ -3,4 +5,5 @@ class TestLoadLibrary(TestCase): + @dec.knownfailureif(sys.platform=='cygwin', "This test is known to fail on cygwin") def test_basic(self): try: @@ -12,6 +15,7 @@ " (import error was: %s)" % str(e) print msg + @dec.knownfailureif(sys.platform=='cygwin', "This test is known to fail on cygwin") def test_basic2(self): """Regression for #801: load_library with a full library name (including extension) does not work.""" From numpy-svn at scipy.org Sat Sep 13 03:16:35 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 02:16:35 -0500 (CDT) Subject: [Numpy-svn] r5813 - branches/clean_math_config/numpy/core Message-ID: <20080913071635.E979039C072@scipy.org> Author: cdavid Date: 2008-09-13 02:16:32 -0500 (Sat, 13 Sep 2008) New Revision: 5813 Modified: branches/clean_math_config/numpy/core/setup.py Log: Detect declaration of isnan and co only. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-13 07:04:41 UTC (rev 5812) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-13 07:16:32 UTC (rev 5813) @@ -91,8 +91,14 @@ fns = [f + prec for f in c99_funcs] check_funcs(fns) - # IEEE754 handling - check_funcs(["isnan", "isinf"]) + # Normally, isnan and isinf are macro (C99), but some platforms only have + # func, or both func and macro version. Check for macro only, and define + # replacement ones if not found. + for f in ["isnan", "isinf", "signbit", "isfinite"]: + st = config.check_decl(f, headers = ["math.h"]) + if st: + moredefs.append(name_to_symb("decl_%s" % f)) + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration,dot_join From numpy-svn at scipy.org Sat Sep 13 03:25:55 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 02:25:55 -0500 (CDT) Subject: [Numpy-svn] r5814 - branches/clean_math_config/numpy/core/src Message-ID: <20080913072555.D6E6739C072@scipy.org> Author: cdavid Date: 2008-09-13 02:25:51 -0500 (Sat, 13 Sep 2008) New Revision: 5814 Modified: branches/clean_math_config/numpy/core/src/math_c99.c.src branches/clean_math_config/numpy/core/src/umathmodule.c.src Log: Clean IEEE handling: define them as macro. Modified: branches/clean_math_config/numpy/core/src/math_c99.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-13 07:16:32 UTC (rev 5813) +++ branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-13 07:25:51 UTC (rev 5814) @@ -2,14 +2,16 @@ * vim:syntax=c * A small module to implement missing C99 math capabilities required by numpy * - * Please keep this independant of python as much as possible ! + * Please keep this independant of python ! */ /* - * Basic functions, double version. Some old/weird platforms may not have those - * - * Original code by Konrad Hinsen. + ***************************************************************************** + ** BASIC MATH FUNCTIONS ** + ***************************************************************************** */ + +/* Original code by Konrad Hinsen. */ #ifndef HAVE_EXPM1 double expm1(double x) { @@ -129,6 +131,74 @@ #endif /* + ***************************************************************************** + ** IEEE 754 FPU HANDLING ** + ***************************************************************************** + */ +#if !defined(HAVE_DECL_ISNAN) + # define isnan(x) \ + (sizeof (x) == sizeof (long double) ? isnan_ld (x) \ + : sizeof (x) == sizeof (double) ? isnan_d (x) \ + : isnan_f (x)) +static int isnan_f (float x) +{ + return x != x; +} + +static int isnan_d (double x) +{ + return x != x; +} + +static int isnan_ld (long double x) +{ + return x != x; +} + +#if !defined(HAVE_DECL_ISINF) + # define isinf(x) \ + (sizeof (x) == sizeof (long double) ? isinf_ld (x) \ + : sizeof (x) == sizeof (double) ? isinf_d (x) \ + : isinf_f (x)) + +static int isinf_f (float x) +{ + return isnan (x - x); +} + +static int isinf_d (double x) +{ + return isnan (x - x); +} + +static int isinf_ld (long double x) +{ + return isnan (x - x); +} + +#if !defined(HAVE_DECL_SIGNBIT) + #include "_signbit.c" + # define signbit(x) \ + (sizeof (x) == sizeof (long double) ? signbit_ld (x) \ + : sizeof (x) == sizeof (double) ? signbit_d (x) \ + : signbit_f (x)) + +static int signbit_f (float x) +{ + return signbit_d((double)x); +} + +static int signbit_ld (long double x) +{ + return signbit_d((double)x); +} + +/* Define isfinie if needed */ +#if !defined(HAVE_DECL_ISFINITE) +#define isfinite(x) (!(isinf((x)) || isnan((x)))) +#endif + +/* * if C99 extensions not available then define dummy functions that use the * double versions for * Modified: branches/clean_math_config/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-13 07:16:32 UTC (rev 5813) +++ branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-13 07:25:51 UTC (rev 5814) @@ -17,114 +17,8 @@ #include "config.h" #include -/* - ***************************************************************************** - ** BASIC MATH FUNCTIONS ** - ***************************************************************************** - */ #include "math_c99.c" -/* - ***************************************************************************** - ** IEEE 754 FPU HANDLING ** - ***************************************************************************** - */ - -/* Define isnan, isinf, isfinite, signbit if needed */ -/* Use fpclassify if possible */ -/* isnan, isinf -- - these will use macros and then fpclassify if available before - defaulting to a dumb convert-to-double version... - - isfinite -- define a macro if not already available - signbit -- if macro available use it, otherwise define a function - and a dumb convert-to-double version for other types. -*/ - -#if defined(fpclassify) - -#if !defined(isnan) -#define isnan(x) (fpclassify(x) == FP_NAN) -#endif -#if !defined(isinf) -#define isinf(x) (fpclassify(x) == FP_INFINITE) -#endif - -#else /* check to see if already have a function like this */ - -#if !defined(HAVE_ISNAN) - -#if !defined(isnan) -#include "_isnan.c" -#endif -#endif /* HAVE_ISNAN */ - -#if !defined(HAVE_ISINF) -#if !defined(isinf) -#define isinf(x) (!isnan((x)) && isnan((x)-(x))) -#endif -#endif /* HAVE_ISINF */ - -#endif /* defined(fpclassify) */ - - -/* Define signbit if needed */ -#if !defined(signbit) -#include "_signbit.c" -#endif - -/* Now defined the extended type macros */ - -#if !defined(isnan) - -#if !defined(HAVE_LONGDOUBLE_FUNCS) || !defined(HAVE_ISNAN) -#define isnanl(x) isnan((double)(x)) -#endif - -#if !defined(HAVE_FLOAT_FUNCS) || !defined(HAVE_ISNAN) -#define isnanf(x) isnan((double)(x)) -#endif - -#else /* !defined(isnan) */ - -#define isnanl(x) isnan((x)) -#define isnanf(x) isnan((x)) - -#endif /* !defined(isnan) */ - - -#if !defined(isinf) - -#if !defined(HAVE_LONGDOUBLE_FUNCS) || !defined(HAVE_ISINF) -#define isinfl(x) (!isnanl((x)) && isnanl((x)-(x))) -#endif - -#if !defined(HAVE_FLOAT_FUNCS) || !defined(HAVE_ISINF) -#define isinff(x) (!isnanf((x)) && isnanf((x)-(x))) -#endif - -#else /* !defined(isinf) */ - -#define isinfl(x) isinf((x)) -#define isinff(x) isinf((x)) - -#endif /* !defined(isinf) */ - - -#if !defined(signbit) -#define signbitl(x) ((longdouble) signbit((double)(x))) -#define signbitf(x) ((float) signbit((double) (x))) -#else -#define signbitl(x) signbit((x)) -#define signbitf(x) signbit((x)) -#endif - -#if !defined(isfinite) -#define isfinite(x) (!(isinf((x)) || isnan((x)))) -#endif -#define isfinitef(x) (!(isinff((x)) || isnanf((x)))) -#define isfinitel(x) (!(isinfl((x)) || isnanl((x)))) - float degreesf(float x) { return x * (float)(180.0/M_PI); } @@ -1567,7 +1461,6 @@ #kind=isnan*3, isinf*3, isfinite*3, signbit*3# #TYPE=(FLOAT, DOUBLE, LONGDOUBLE)*4# #typ=(float, double, longdouble)*4# - #c=(f,,l)*4# */ static void @TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) @@ -1576,7 +1469,7 @@ intp is=steps[0], os=steps[1], n=dimensions[0]; char *ip=args[0], *op=args[1]; for(i=0; i Author: cdavid Date: 2008-09-13 02:27:25 -0500 (Sat, 13 Sep 2008) New Revision: 5815 Modified: branches/clean_math_config/numpy/core/src/math_c99.c Log: Update generated math_c99 compat module. Modified: branches/clean_math_config/numpy/core/src/math_c99.c =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-13 07:25:51 UTC (rev 5814) +++ branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-13 07:27:25 UTC (rev 5815) @@ -11,14 +11,16 @@ * vim:syntax=c * A small module to implement missing C99 math capabilities required by numpy * - * Please keep this independant of python as much as possible ! + * Please keep this independant of python ! */ /* - * Basic functions, double version. Some old/weird platforms may not have those - * - * Original code by Konrad Hinsen. + ***************************************************************************** + ** BASIC MATH FUNCTIONS ** + ***************************************************************************** */ + +/* Original code by Konrad Hinsen. */ #ifndef HAVE_EXPM1 double expm1(double x) { @@ -138,6 +140,74 @@ #endif /* + ***************************************************************************** + ** IEEE 754 FPU HANDLING ** + ***************************************************************************** + */ +#if !defined(HAVE_DECL_ISNAN) + # define isnan(x) \ + (sizeof (x) == sizeof (long double) ? isnan_ld (x) \ + : sizeof (x) == sizeof (double) ? isnan_d (x) \ + : isnan_f (x)) +static int isnan_f (float x) +{ + return x != x; +} + +static int isnan_d (double x) +{ + return x != x; +} + +static int isnan_ld (long double x) +{ + return x != x; +} + +#if !defined(HAVE_DECL_ISINF) + # define isinf(x) \ + (sizeof (x) == sizeof (long double) ? isinf_ld (x) \ + : sizeof (x) == sizeof (double) ? isinf_d (x) \ + : isinf_f (x)) + +static int isinf_f (float x) +{ + return isnan (x - x); +} + +static int isinf_d (double x) +{ + return isnan (x - x); +} + +static int isinf_ld (long double x) +{ + return isnan (x - x); +} + +#if !defined(HAVE_DECL_SIGNBIT) + #include "_signbit.c" + # define signbit(x) \ + (sizeof (x) == sizeof (long double) ? signbit_ld (x) \ + : sizeof (x) == sizeof (double) ? signbit_d (x) \ + : signbit_f (x)) + +static int signbit_f (float x) +{ + return signbit_d((double)x); +} + +static int signbit_ld (long double x) +{ + return signbit_d((double)x); +} + +/* Define isfinie if needed */ +#if !defined(HAVE_DECL_ISFINITE) +#define isfinite(x) (!(isinf((x)) || isnan((x)))) +#endif + +/* * if C99 extensions not available then define dummy functions that use the * double versions for * @@ -157,7 +227,7 @@ * One value argument function */ -#line 160 +#line 230 #ifndef HAVE_SINL longdouble sinl(longdouble x) @@ -166,7 +236,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_COSL longdouble cosl(longdouble x) @@ -175,7 +245,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_TANL longdouble tanl(longdouble x) @@ -184,7 +254,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_SINHL longdouble sinhl(longdouble x) @@ -193,7 +263,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_COSHL longdouble coshl(longdouble x) @@ -202,7 +272,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_TANHL longdouble tanhl(longdouble x) @@ -211,7 +281,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_FABSL longdouble fabsl(longdouble x) @@ -220,7 +290,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_FLOORL longdouble floorl(longdouble x) @@ -229,7 +299,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_CEILL longdouble ceill(longdouble x) @@ -238,7 +308,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_RINTL longdouble rintl(longdouble x) @@ -247,7 +317,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_TRUNCL longdouble truncl(longdouble x) @@ -256,7 +326,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_SQRTL longdouble sqrtl(longdouble x) @@ -265,7 +335,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_LOG10L longdouble log10l(longdouble x) @@ -274,7 +344,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_LOGL longdouble logl(longdouble x) @@ -283,7 +353,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_EXPL longdouble expl(longdouble x) @@ -292,7 +362,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_EXPM1L longdouble expm1l(longdouble x) @@ -301,7 +371,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ASINL longdouble asinl(longdouble x) @@ -310,7 +380,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ACOSL longdouble acosl(longdouble x) @@ -319,7 +389,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ATANL longdouble atanl(longdouble x) @@ -328,7 +398,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ASINHL longdouble asinhl(longdouble x) @@ -337,7 +407,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ACOSHL longdouble acoshl(longdouble x) @@ -346,7 +416,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ATANHL longdouble atanhl(longdouble x) @@ -355,7 +425,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_SINF float sinf(float x) @@ -364,7 +434,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_COSF float cosf(float x) @@ -373,7 +443,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_TANF float tanf(float x) @@ -382,7 +452,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_SINHF float sinhf(float x) @@ -391,7 +461,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_COSHF float coshf(float x) @@ -400,7 +470,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_TANHF float tanhf(float x) @@ -409,7 +479,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_FABSF float fabsf(float x) @@ -418,7 +488,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_FLOORF float floorf(float x) @@ -427,7 +497,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_CEILF float ceilf(float x) @@ -436,7 +506,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_RINTF float rintf(float x) @@ -445,7 +515,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_TRUNCF float truncf(float x) @@ -454,7 +524,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_SQRTF float sqrtf(float x) @@ -463,7 +533,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_LOG10F float log10f(float x) @@ -472,7 +542,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_LOGF float logf(float x) @@ -481,7 +551,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_EXPF float expf(float x) @@ -490,7 +560,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_EXPM1F float expm1f(float x) @@ -499,7 +569,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ASINF float asinf(float x) @@ -508,7 +578,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ACOSF float acosf(float x) @@ -517,7 +587,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ATANF float atanf(float x) @@ -526,7 +596,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ASINHF float asinhf(float x) @@ -535,7 +605,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ACOSHF float acoshf(float x) @@ -544,7 +614,7 @@ } #endif -#line 160 +#line 230 #ifndef HAVE_ATANHF float atanhf(float x) @@ -558,7 +628,7 @@ * Two values arguments function */ -#line 182 +#line 252 #ifndef HAVE_ATAN2L longdouble atan2l(longdouble x, longdouble y) { @@ -566,7 +636,7 @@ } #endif -#line 182 +#line 252 #ifndef HAVE_HYPOTL longdouble hypotl(longdouble x, longdouble y) { @@ -574,7 +644,7 @@ } #endif -#line 182 +#line 252 #ifndef HAVE_POWL longdouble powl(longdouble x, longdouble y) { @@ -582,7 +652,7 @@ } #endif -#line 182 +#line 252 #ifndef HAVE_FMODL longdouble fmodl(longdouble x, longdouble y) { @@ -590,7 +660,7 @@ } #endif -#line 182 +#line 252 #ifndef HAVE_ATAN2F float atan2f(float x, float y) { @@ -598,7 +668,7 @@ } #endif -#line 182 +#line 252 #ifndef HAVE_HYPOTF float hypotf(float x, float y) { @@ -606,7 +676,7 @@ } #endif -#line 182 +#line 252 #ifndef HAVE_POWF float powf(float x, float y) { @@ -614,7 +684,7 @@ } #endif -#line 182 +#line 252 #ifndef HAVE_FMODF float fmodf(float x, float y) { @@ -627,7 +697,7 @@ * One value - one pointer argument function */ -#line 202 +#line 272 #ifndef HAVE_MODFL longdouble modfl(longdouble x, longdouble *iptr) { @@ -639,7 +709,7 @@ } #endif -#line 202 +#line 272 #ifndef HAVE_MODFF float modff(float x, float *iptr) { From numpy-svn at scipy.org Sat Sep 13 03:28:11 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 02:28:11 -0500 (CDT) Subject: [Numpy-svn] r5816 - branches/clean_math_config/numpy/core/src Message-ID: <20080913072811.7C0BD39C072@scipy.org> Author: cdavid Date: 2008-09-13 02:28:08 -0500 (Sat, 13 Sep 2008) New Revision: 5816 Modified: branches/clean_math_config/numpy/core/src/math_c99.c.src Log: Remove trailing spaces. Modified: branches/clean_math_config/numpy/core/src/math_c99.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-13 07:27:25 UTC (rev 5815) +++ branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-13 07:28:08 UTC (rev 5816) @@ -140,39 +140,39 @@ (sizeof (x) == sizeof (long double) ? isnan_ld (x) \ : sizeof (x) == sizeof (double) ? isnan_d (x) \ : isnan_f (x)) -static int isnan_f (float x) -{ - return x != x; +static int isnan_f (float x) +{ + return x != x; } -static int isnan_d (double x) -{ - return x != x; +static int isnan_d (double x) +{ + return x != x; } -static int isnan_ld (long double x) -{ - return x != x; +static int isnan_ld (long double x) +{ + return x != x; } - + #if !defined(HAVE_DECL_ISINF) # define isinf(x) \ (sizeof (x) == sizeof (long double) ? isinf_ld (x) \ : sizeof (x) == sizeof (double) ? isinf_d (x) \ : isinf_f (x)) -static int isinf_f (float x) -{ - return isnan (x - x); +static int isinf_f (float x) +{ + return isnan (x - x); } -static int isinf_d (double x) -{ - return isnan (x - x); +static int isinf_d (double x) +{ + return isnan (x - x); } -static int isinf_ld (long double x) -{ +static int isinf_ld (long double x) +{ return isnan (x - x); } @@ -183,14 +183,14 @@ : sizeof (x) == sizeof (double) ? signbit_d (x) \ : signbit_f (x)) -static int signbit_f (float x) -{ - return signbit_d((double)x); +static int signbit_f (float x) +{ + return signbit_d((double)x); } -static int signbit_ld (long double x) -{ - return signbit_d((double)x); +static int signbit_ld (long double x) +{ + return signbit_d((double)x); } /* Define isfinie if needed */ From numpy-svn at scipy.org Sat Sep 13 03:30:10 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 02:30:10 -0500 (CDT) Subject: [Numpy-svn] r5817 - branches/clean_math_config/numpy/core/src Message-ID: <20080913073010.A680D39C072@scipy.org> Author: cdavid Date: 2008-09-13 02:30:07 -0500 (Sat, 13 Sep 2008) New Revision: 5817 Removed: branches/clean_math_config/numpy/core/src/_isnan.c Log: remove unused _isnan.c Deleted: branches/clean_math_config/numpy/core/src/_isnan.c =================================================================== --- branches/clean_math_config/numpy/core/src/_isnan.c 2008-09-13 07:28:08 UTC (rev 5816) +++ branches/clean_math_config/numpy/core/src/_isnan.c 2008-09-13 07:30:07 UTC (rev 5817) @@ -1,46 +0,0 @@ -/* Adapted from cephes */ - -static int -isnan(double x) -{ - union - { - double d; - unsigned short s[4]; - unsigned int i[2]; - } u; - - u.d = x; - -#if SIZEOF_INT == 4 - -#ifdef WORDS_BIGENDIAN /* defined in pyconfig.h */ - if( ((u.i[0] & 0x7ff00000) == 0x7ff00000) - && (((u.i[0] & 0x000fffff) != 0) || (u.i[1] != 0))) - return 1; -#else - if( ((u.i[1] & 0x7ff00000) == 0x7ff00000) - && (((u.i[1] & 0x000fffff) != 0) || (u.i[0] != 0))) - return 1; -#endif - -#else /* SIZEOF_INT != 4 */ - -#ifdef WORDS_BIGENDIAN - if( (u.s[0] & 0x7ff0) == 0x7ff0) - { - if( ((u.s[0] & 0x000f) | u.s[1] | u.s[2] | u.s[3]) != 0 ) - return 1; - } -#else - if( (u.s[3] & 0x7ff0) == 0x7ff0) - { - if( ((u.s[3] & 0x000f) | u.s[2] | u.s[1] | u.s[0]) != 0 ) - return 1; - } -#endif - -#endif /* SIZEOF_INT */ - - return 0; -} From numpy-svn at scipy.org Sat Sep 13 03:48:32 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 02:48:32 -0500 (CDT) Subject: [Numpy-svn] r5818 - branches/clean_math_config/numpy/core Message-ID: <20080913074832.CC43739C072@scipy.org> Author: cdavid Date: 2008-09-13 02:48:29 -0500 (Sat, 13 Sep 2008) New Revision: 5818 Modified: branches/clean_math_config/numpy/core/setup.py Log: Fix typo in setup.py Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-13 07:30:07 UTC (rev 5817) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-13 07:48:29 UTC (rev 5818) @@ -97,9 +97,9 @@ for f in ["isnan", "isinf", "signbit", "isfinite"]: st = config.check_decl(f, headers = ["math.h"]) if st: - moredefs.append(name_to_symb("decl_%s" % f)) - + moredefs.append(name_to_defsymb("decl_%s" % f)) + def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration,dot_join from numpy.distutils.system_info import get_info, default_lib_dirs From numpy-svn at scipy.org Sat Sep 13 04:08:20 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 03:08:20 -0500 (CDT) Subject: [Numpy-svn] r5819 - branches/clean_math_config/numpy/core Message-ID: <20080913080820.516BC39C072@scipy.org> Author: cdavid Date: 2008-09-13 03:08:16 -0500 (Sat, 13 Sep 2008) New Revision: 5819 Modified: branches/clean_math_config/numpy/core/setup.py Log: Do not depend on _isnan.c. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-13 07:48:29 UTC (rev 5818) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-13 08:08:16 UTC (rev 5819) @@ -319,7 +319,6 @@ join('src','scalartypes.inc.src'), join('src','arraytypes.inc.src'), join('src','_signbit.c'), - join('src','_isnan.c'), join('src','ucsnarrow.c'), join('include','numpy','*object.h'), 'include/numpy/fenv/fenv.c', From numpy-svn at scipy.org Sat Sep 13 04:09:08 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 03:09:08 -0500 (CDT) Subject: [Numpy-svn] r5820 - branches/clean_math_config/numpy/core/src Message-ID: <20080913080908.B7C5239C072@scipy.org> Author: cdavid Date: 2008-09-13 03:09:02 -0500 (Sat, 13 Sep 2008) New Revision: 5820 Modified: branches/clean_math_config/numpy/core/src/_signbit.c branches/clean_math_config/numpy/core/src/math_c99.c branches/clean_math_config/numpy/core/src/math_c99.c.src Log: Rename signbit replacement to signbit_d to avoid clash between macro and function. Modified: branches/clean_math_config/numpy/core/src/_signbit.c =================================================================== --- branches/clean_math_config/numpy/core/src/_signbit.c 2008-09-13 08:08:16 UTC (rev 5819) +++ branches/clean_math_config/numpy/core/src/_signbit.c 2008-09-13 08:09:02 UTC (rev 5820) @@ -1,7 +1,7 @@ /* Adapted from cephes */ static int -signbit(double x) +signbit_d(double x) { union { Modified: branches/clean_math_config/numpy/core/src/math_c99.c =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-13 08:08:16 UTC (rev 5819) +++ branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-13 08:09:02 UTC (rev 5820) @@ -149,41 +149,43 @@ (sizeof (x) == sizeof (long double) ? isnan_ld (x) \ : sizeof (x) == sizeof (double) ? isnan_d (x) \ : isnan_f (x)) -static int isnan_f (float x) -{ - return x != x; +static int isnan_f (float x) +{ + return x != x; } -static int isnan_d (double x) -{ - return x != x; +static int isnan_d (double x) +{ + return x != x; } -static int isnan_ld (long double x) -{ - return x != x; +static int isnan_ld (long double x) +{ + return x != x; } - +#endif + #if !defined(HAVE_DECL_ISINF) # define isinf(x) \ (sizeof (x) == sizeof (long double) ? isinf_ld (x) \ : sizeof (x) == sizeof (double) ? isinf_d (x) \ : isinf_f (x)) -static int isinf_f (float x) -{ - return isnan (x - x); +static int isinf_f (float x) +{ + return isnan (x - x); } -static int isinf_d (double x) -{ - return isnan (x - x); +static int isinf_d (double x) +{ + return isnan (x - x); } -static int isinf_ld (long double x) -{ +static int isinf_ld (long double x) +{ return isnan (x - x); } +#endif #if !defined(HAVE_DECL_SIGNBIT) #include "_signbit.c" @@ -192,15 +194,16 @@ : sizeof (x) == sizeof (double) ? signbit_d (x) \ : signbit_f (x)) -static int signbit_f (float x) -{ - return signbit_d((double)x); +static int signbit_f (float x) +{ + return signbit_d((double)x); } -static int signbit_ld (long double x) -{ - return signbit_d((double)x); +static int signbit_ld (long double x) +{ + return signbit_d((double)x); } +#endif /* Define isfinie if needed */ #if !defined(HAVE_DECL_ISFINITE) @@ -227,7 +230,7 @@ * One value argument function */ -#line 230 +#line 233 #ifndef HAVE_SINL longdouble sinl(longdouble x) @@ -236,7 +239,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_COSL longdouble cosl(longdouble x) @@ -245,7 +248,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_TANL longdouble tanl(longdouble x) @@ -254,7 +257,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_SINHL longdouble sinhl(longdouble x) @@ -263,7 +266,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_COSHL longdouble coshl(longdouble x) @@ -272,7 +275,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_TANHL longdouble tanhl(longdouble x) @@ -281,7 +284,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_FABSL longdouble fabsl(longdouble x) @@ -290,7 +293,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_FLOORL longdouble floorl(longdouble x) @@ -299,7 +302,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_CEILL longdouble ceill(longdouble x) @@ -308,7 +311,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_RINTL longdouble rintl(longdouble x) @@ -317,7 +320,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_TRUNCL longdouble truncl(longdouble x) @@ -326,7 +329,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_SQRTL longdouble sqrtl(longdouble x) @@ -335,7 +338,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_LOG10L longdouble log10l(longdouble x) @@ -344,7 +347,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_LOGL longdouble logl(longdouble x) @@ -353,7 +356,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_EXPL longdouble expl(longdouble x) @@ -362,7 +365,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_EXPM1L longdouble expm1l(longdouble x) @@ -371,7 +374,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ASINL longdouble asinl(longdouble x) @@ -380,7 +383,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ACOSL longdouble acosl(longdouble x) @@ -389,7 +392,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ATANL longdouble atanl(longdouble x) @@ -398,7 +401,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ASINHL longdouble asinhl(longdouble x) @@ -407,7 +410,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ACOSHL longdouble acoshl(longdouble x) @@ -416,7 +419,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ATANHL longdouble atanhl(longdouble x) @@ -425,7 +428,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_SINF float sinf(float x) @@ -434,7 +437,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_COSF float cosf(float x) @@ -443,7 +446,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_TANF float tanf(float x) @@ -452,7 +455,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_SINHF float sinhf(float x) @@ -461,7 +464,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_COSHF float coshf(float x) @@ -470,7 +473,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_TANHF float tanhf(float x) @@ -479,7 +482,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_FABSF float fabsf(float x) @@ -488,7 +491,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_FLOORF float floorf(float x) @@ -497,7 +500,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_CEILF float ceilf(float x) @@ -506,7 +509,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_RINTF float rintf(float x) @@ -515,7 +518,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_TRUNCF float truncf(float x) @@ -524,7 +527,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_SQRTF float sqrtf(float x) @@ -533,7 +536,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_LOG10F float log10f(float x) @@ -542,7 +545,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_LOGF float logf(float x) @@ -551,7 +554,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_EXPF float expf(float x) @@ -560,7 +563,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_EXPM1F float expm1f(float x) @@ -569,7 +572,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ASINF float asinf(float x) @@ -578,7 +581,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ACOSF float acosf(float x) @@ -587,7 +590,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ATANF float atanf(float x) @@ -596,7 +599,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ASINHF float asinhf(float x) @@ -605,7 +608,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ACOSHF float acoshf(float x) @@ -614,7 +617,7 @@ } #endif -#line 230 +#line 233 #ifndef HAVE_ATANHF float atanhf(float x) @@ -628,7 +631,7 @@ * Two values arguments function */ -#line 252 +#line 255 #ifndef HAVE_ATAN2L longdouble atan2l(longdouble x, longdouble y) { @@ -636,7 +639,7 @@ } #endif -#line 252 +#line 255 #ifndef HAVE_HYPOTL longdouble hypotl(longdouble x, longdouble y) { @@ -644,7 +647,7 @@ } #endif -#line 252 +#line 255 #ifndef HAVE_POWL longdouble powl(longdouble x, longdouble y) { @@ -652,7 +655,7 @@ } #endif -#line 252 +#line 255 #ifndef HAVE_FMODL longdouble fmodl(longdouble x, longdouble y) { @@ -660,7 +663,7 @@ } #endif -#line 252 +#line 255 #ifndef HAVE_ATAN2F float atan2f(float x, float y) { @@ -668,7 +671,7 @@ } #endif -#line 252 +#line 255 #ifndef HAVE_HYPOTF float hypotf(float x, float y) { @@ -676,7 +679,7 @@ } #endif -#line 252 +#line 255 #ifndef HAVE_POWF float powf(float x, float y) { @@ -684,7 +687,7 @@ } #endif -#line 252 +#line 255 #ifndef HAVE_FMODF float fmodf(float x, float y) { @@ -697,7 +700,7 @@ * One value - one pointer argument function */ -#line 272 +#line 275 #ifndef HAVE_MODFL longdouble modfl(longdouble x, longdouble *iptr) { @@ -709,7 +712,7 @@ } #endif -#line 272 +#line 275 #ifndef HAVE_MODFF float modff(float x, float *iptr) { Modified: branches/clean_math_config/numpy/core/src/math_c99.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-13 08:08:16 UTC (rev 5819) +++ branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-13 08:09:02 UTC (rev 5820) @@ -154,6 +154,7 @@ { return x != x; } +#endif #if !defined(HAVE_DECL_ISINF) # define isinf(x) \ @@ -175,6 +176,7 @@ { return isnan (x - x); } +#endif #if !defined(HAVE_DECL_SIGNBIT) #include "_signbit.c" @@ -192,6 +194,7 @@ { return signbit_d((double)x); } +#endif /* Define isfinie if needed */ #if !defined(HAVE_DECL_ISFINITE) From numpy-svn at scipy.org Sat Sep 13 14:05:02 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 13:05:02 -0500 (CDT) Subject: [Numpy-svn] r5821 - in trunk/numpy/ma: . tests Message-ID: <20080913180502.A23A839C072@scipy.org> Author: alan.mcintyre Date: 2008-09-13 13:04:57 -0500 (Sat, 13 Sep 2008) New Revision: 5821 Modified: trunk/numpy/ma/bench.py trunk/numpy/ma/core.py trunk/numpy/ma/mrecords.py trunk/numpy/ma/tests/test_mrecords.py trunk/numpy/ma/testutils.py trunk/numpy/ma/timer_comparison.py Log: Removed unused imports. Standardize NumPy import as "import numpy as np". Modified: trunk/numpy/ma/bench.py =================================================================== --- trunk/numpy/ma/bench.py 2008-09-13 08:09:02 UTC (rev 5820) +++ trunk/numpy/ma/bench.py 2008-09-13 18:04:57 UTC (rev 5821) @@ -6,9 +6,9 @@ #ip = IPython.ipapi.get() #from IPython import ipmagic import numpy -from numpy import ma -from numpy.ma import filled -from numpy.ma.testutils import assert_equal +#from numpy import ma +#from numpy.ma import filled +#from numpy.ma.testutils import assert_equal #####--------------------------------------------------------------------------- Modified: trunk/numpy/ma/core.py =================================================================== --- trunk/numpy/ma/core.py 2008-09-13 08:09:02 UTC (rev 5820) +++ trunk/numpy/ma/core.py 2008-09-13 18:04:57 UTC (rev 5821) @@ -57,17 +57,14 @@ 'var', 'where', 'zeros'] -import sys -import types import cPickle import operator import numpy as np -from numpy import ndarray, typecodes, amax, amin, iscomplexobj,\ - bool_, complex_, float_, int_, object_, str_ +from numpy import ndarray, amax, amin, iscomplexobj, bool_, complex_, float_,\ + int_, object_ from numpy import array as narray - import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy import expand_dims as n_expand_dims Modified: trunk/numpy/ma/mrecords.py =================================================================== --- trunk/numpy/ma/mrecords.py 2008-09-13 08:09:02 UTC (rev 5820) +++ trunk/numpy/ma/mrecords.py 2008-09-13 18:04:57 UTC (rev 5821) @@ -16,23 +16,21 @@ __author__ = "Pierre GF Gerard-Marchant" import sys -import types import numpy as np -from numpy import bool_, complex_, float_, int_, str_, object_, dtype, \ - chararray, ndarray, recarray, record, array as narray +from numpy import bool_, dtype, \ + ndarray, recarray, array as narray import numpy.core.numerictypes as ntypes -from numpy.core.records import find_duplicate, format_parser from numpy.core.records import fromarrays as recfromarrays, \ - fromrecords as recfromrecords + fromrecords as recfromrecords _byteorderconv = np.core.records._byteorderconv _typestr = ntypes._typestr import numpy.ma as ma from numpy.ma import MAError, MaskedArray, masked, nomask, masked_array,\ - make_mask, mask_or, getdata, getmask, getmaskarray, filled, \ - default_fill_value, masked_print_option + getdata, getmaskarray, filled + _check_fill_value = ma.core._check_fill_value import warnings Modified: trunk/numpy/ma/tests/test_mrecords.py =================================================================== --- trunk/numpy/ma/tests/test_mrecords.py 2008-09-13 08:09:02 UTC (rev 5820) +++ trunk/numpy/ma/tests/test_mrecords.py 2008-09-13 18:04:57 UTC (rev 5821) @@ -8,23 +8,19 @@ __revision__ = "$Revision: 3473 $" __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' -import types - import numpy as np from numpy import recarray from numpy.core.records import fromrecords as recfromrecords, \ - fromarrays as recfromarrays + fromarrays as recfromarrays import numpy.ma.testutils from numpy.ma.testutils import * import numpy.ma as ma -from numpy.ma import masked, nomask, getdata, getmaskarray +from numpy.ma import masked, nomask -import numpy.ma.mrecords -reload(numpy.ma.mrecords) -from numpy.ma.mrecords import MaskedRecords, mrecarray,\ - fromarrays, fromtextfile, fromrecords, addfield +from numpy.ma.mrecords import MaskedRecords, mrecarray, fromarrays, \ + fromtextfile, fromrecords, addfield #.............................................................................. class TestMRecords(TestCase): @@ -432,7 +428,6 @@ 'strings',4,-1e-10,,,1 """ import os - from datetime import datetime import tempfile (tmp_fd,tmp_fl) = tempfile.mkstemp() os.write(tmp_fd, fcontent) Modified: trunk/numpy/ma/testutils.py =================================================================== --- trunk/numpy/ma/testutils.py 2008-09-13 08:09:02 UTC (rev 5820) +++ trunk/numpy/ma/testutils.py 2008-09-13 18:04:57 UTC (rev 5821) @@ -16,12 +16,10 @@ from numpy import ndarray, float_ import numpy.core.umath as umath from numpy.testing import * -from numpy.testing.utils import build_err_msg, rand import numpy.testing.utils as utils -import core -from core import mask_or, getmask, getmaskarray, masked_array, nomask, masked -from core import fix_invalid, filled, equal, less +from core import mask_or, getmask, masked_array, nomask, masked, filled, \ + equal, less #------------------------------------------------------------------------------ def approx (a, b, fill_value=True, rtol=1.e-5, atol=1.e-8): Modified: trunk/numpy/ma/timer_comparison.py =================================================================== --- trunk/numpy/ma/timer_comparison.py 2008-09-13 08:09:02 UTC (rev 5820) +++ trunk/numpy/ma/timer_comparison.py 2008-09-13 18:04:57 UTC (rev 5821) @@ -1,17 +1,15 @@ - import timeit -import numpy -from numpy import int_, float_, bool_ -import numpy.core.fromnumeric as fromnumeric +import numpy as np +from numpy import float_ +import np.core.fromnumeric as fromnumeric -from numpy.testing.utils import build_err_msg, rand +from np.testing.utils import build_err_msg +np.seterr(all='ignore') -numpy.seterr(all='ignore') +pi = np.pi -pi = numpy.pi - class moduletester: #----------------------------------- def __init__(self, module): @@ -61,15 +59,15 @@ y = self.filled(self.masked_array(yf, mask=m), fill_value) if (x.dtype.char != "O"): x = x.astype(float_) - if isinstance(x, numpy.ndarray) and x.size > 1: - x[numpy.isnan(x)] = 0 - elif numpy.isnan(x): + if isinstance(x, np.ndarray) and x.size > 1: + x[np.isnan(x)] = 0 + elif np.isnan(x): x = 0 if (y.dtype.char != "O"): y = y.astype(float_) - if isinstance(y, numpy.ndarray) and y.size > 1: - y[numpy.isnan(y)] = 0 - elif numpy.isnan(y): + if isinstance(y, np.ndarray) and y.size > 1: + y[np.isnan(y)] = 0 + elif np.isnan(y): y = 0 try: cond = (x.shape==() or y.shape==()) or x.shape == y.shape @@ -110,23 +108,23 @@ #---------------------------------- def test_0(self): "Tests creation" - x = numpy.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) + x = np.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] xm = self.masked_array(x, mask=m) xm[0] #---------------------------------- def test_1(self): "Tests creation" - x = numpy.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) - y = numpy.array([5.,0.,3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) + x = np.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) + y = np.array([5.,0.,3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) a10 = 10. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0 ,0, 1] xm = self.masked_array(x, mask=m1) ym = self.masked_array(y, mask=m2) - z = numpy.array([-.5, 0., .5, .8]) + z = np.array([-.5, 0., .5, .8]) zm = self.masked_array(z, mask=[0,1,0,0]) - xf = numpy.where(m1, 1.e+20, x) + xf = np.where(m1, 1.e+20, x) xm.set_fill_value(1.e+20) #..... assert((xm-ym).filled(0).any()) @@ -146,13 +144,13 @@ #---------------------------------- def test_2(self): "Tests conversions and indexing" - x1 = numpy.array([1,2,4,3]) + x1 = np.array([1,2,4,3]) x2 = self.array(x1, mask=[1,0,0,0]) x3 = self.array(x1, mask=[0,1,0,1]) x4 = self.array(x1) # test conversion to strings junk, garbage = str(x2), repr(x2) -# assert_equal(numpy.sort(x1), self.sort(x2, fill_value=0)) +# assert_equal(np.sort(x1), self.sort(x2, fill_value=0)) # tests of indexing assert type(x2[1]) is type(x1[1]) assert x1[1] == x2[1] @@ -178,12 +176,12 @@ x4[:] = self.masked_array([1,2,3,4],[0,1,1,0]) # assert self.allequal(self.getmask(x4), self.array([0,1,1,0])) # assert self.allequal(x4, self.array([1,2,3,4])) - x1 = numpy.arange(5)*1.0 + x1 = np.arange(5)*1.0 x2 = self.masked_values(x1, 3.0) # assert self.allequal(x1,x2) # assert self.allequal(self.array([0,0,0,1,0], self.MaskType), x2.mask) x1 = self.array([1,'hello',2,3],object) - x2 = numpy.array([1,'hello',2,3],object) + x2 = np.array([1,'hello',2,3],object) s1 = x1[1] s2 = x2[1] assert x1[1:1].shape == (0,) @@ -216,15 +214,15 @@ def test_4(self): "Test of take, transpose, inner, outer products" x = self.arange(24) - y = numpy.arange(24) + y = np.arange(24) x[5:6] = self.masked x = x.reshape(2,3,4) y = y.reshape(2,3,4) - assert self.allequal(numpy.transpose(y,(2,0,1)), self.transpose(x,(2,0,1))) - assert self.allequal(numpy.take(y, (2,0,1), 1), self.take(x, (2,0,1), 1)) - assert self.allequal(numpy.inner(self.filled(x,0), self.filled(y,0)), + assert self.allequal(np.transpose(y,(2,0,1)), self.transpose(x,(2,0,1))) + assert self.allequal(np.take(y, (2,0,1), 1), self.take(x, (2,0,1), 1)) + assert self.allequal(np.inner(self.filled(x,0), self.filled(y,0)), self.inner(x, y)) - assert self.allequal(numpy.outer(self.filled(x,0), self.filled(y,0)), + assert self.allequal(np.outer(self.filled(x,0), self.filled(y,0)), self.outer(x, y)) y = self.array(['abc', 1, 'def', 2, 3], object) y[2] = self.masked @@ -396,8 +394,8 @@ self.assert_array_equal(self.average(x, axis=0), 2.5) self.assert_array_equal(self.average(x, axis=0, weights=w1), 2.5) y = self.array([self.arange(6), 2.0*self.arange(6)]) - self.assert_array_equal(self.average(y, None), numpy.add.reduce(numpy.arange(6))*3./12.) - self.assert_array_equal(self.average(y, axis=0), numpy.arange(6) * 3./2.) + self.assert_array_equal(self.average(y, None), np.add.reduce(np.arange(6))*3./12.) + self.assert_array_equal(self.average(y, axis=0), np.arange(6) * 3./2.) self.assert_array_equal(self.average(y, axis=1), [self.average(x,axis=0), self.average(x,axis=0) * 2.0]) self.assert_array_equal(self.average(y, None, weights=w2), 20./6.) self.assert_array_equal(self.average(y, axis=0, weights=w2), [0.,1.,2.,3.,4.,10.]) @@ -420,7 +418,7 @@ #------------------------ def test_A(self): x = self.arange(24) - y = numpy.arange(24) + y = np.arange(24) x[5:6] = self.masked x = x.reshape(2,3,4) @@ -431,10 +429,10 @@ setup_base = "from __main__ import moduletester \n"\ "import numpy\n" \ "tester = moduletester(module)\n" -# setup_new = "import numpy.ma.core_ini as module\n"+setup_base - setup_cur = "import numpy.ma.core as module\n"+setup_base -# setup_alt = "import numpy.ma.core_alt as module\n"+setup_base -# setup_tmp = "import numpy.ma.core_tmp as module\n"+setup_base +# setup_new = "import np.ma.core_ini as module\n"+setup_base + setup_cur = "import np.ma.core as module\n"+setup_base +# setup_alt = "import np.ma.core_alt as module\n"+setup_base +# setup_tmp = "import np.ma.core_tmp as module\n"+setup_base (nrepeat, nloop) = (10, 10) @@ -445,10 +443,10 @@ cur = timeit.Timer(func, setup_cur).repeat(nrepeat, nloop*10) # alt = timeit.Timer(func, setup_alt).repeat(nrepeat, nloop*10) # tmp = timeit.Timer(func, setup_tmp).repeat(nrepeat, nloop*10) -# new = numpy.sort(new) - cur = numpy.sort(cur) -# alt = numpy.sort(alt) -# tmp = numpy.sort(tmp) +# new = np.sort(new) + cur = np.sort(cur) +# alt = np.sort(alt) +# tmp = np.sort(tmp) print "#%i" % i +50*'.' print eval("moduletester.test_%i.__doc__" % i) # print "core_ini : %.3f - %.3f" % (new[0], new[1]) From numpy-svn at scipy.org Sat Sep 13 14:10:51 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 13:10:51 -0500 (CDT) Subject: [Numpy-svn] r5822 - trunk/numpy/oldnumeric Message-ID: <20080913181051.CE3ED39C072@scipy.org> Author: alan.mcintyre Date: 2008-09-13 13:10:48 -0500 (Sat, 13 Sep 2008) New Revision: 5822 Modified: trunk/numpy/oldnumeric/arrayfns.py trunk/numpy/oldnumeric/compat.py trunk/numpy/oldnumeric/mlab.py trunk/numpy/oldnumeric/rng.py Log: Rewrapped __all__ definition to conform to PEP8. Standardize NumPy import as "import numpy as np". Removed unused imports. Fixed undefined reference to ndarray (should be np.ndarray). Fixed undefined references to exp (should be math.exp). Modified: trunk/numpy/oldnumeric/arrayfns.py =================================================================== --- trunk/numpy/oldnumeric/arrayfns.py 2008-09-13 18:04:57 UTC (rev 5821) +++ trunk/numpy/oldnumeric/arrayfns.py 2008-09-13 18:10:48 UTC (rev 5822) @@ -1,10 +1,11 @@ """Backward compatible with arrayfns from Numeric """ -__all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask', 'histogram', 'index_sort', - 'interp', 'nz', 'reverse', 'span', 'to_corners', 'zmin_zmax'] +__all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask', + 'histogram', 'index_sort', 'interp', 'nz', 'reverse', 'span', + 'to_corners', 'zmin_zmax'] -import numpy as nx +import numpy as np from numpy import asarray class error(Exception): @@ -14,7 +15,7 @@ indices = asarray(indices) if indices.ndim != 1: raise ValueError, "index array must be 1-d" - if not isinstance(vals1, ndarray): + if not isinstance(vals1, np.ndarray): raise TypeError, "vals1 must be an ndarray" vals1 = asarray(vals1) vals2 = asarray(vals2) @@ -31,7 +32,7 @@ def interp(y, x, z, typ=None): """y(z) interpolated by treating y(x) as piecewise function """ - res = numpy.interp(z, x, y) + res = np.interp(z, x, y) if typ is None or typ == 'd': return res if typ == 'f': @@ -40,17 +41,17 @@ raise error, "incompatible typecode" def nz(x): - x = asarray(x,dtype=nx.ubyte) + x = asarray(x,dtype=np.ubyte) if x.ndim != 1: raise TypeError, "intput must have 1 dimension." - indxs = nx.flatnonzero(x != 0) + indxs = np.flatnonzero(x != 0) return indxs[-1].item()+1 def reverse(x, n): x = asarray(x,dtype='d') if x.ndim != 2: raise ValueError, "input must be 2-d" - y = nx.empty_like(x) + y = np.empty_like(x) if n == 0: y[...] = x[::-1,:] elif n == 1: @@ -58,11 +59,11 @@ return y def span(lo, hi, num, d2=0): - x = linspace(lo, hi, num) + x = np.linspace(lo, hi, num) if d2 <= 0: return x else: - ret = empty((d2,num),x.dtype) + ret = np.empty((d2,num),x.dtype) ret[...] = x return ret @@ -71,15 +72,15 @@ ireg = asarray(ireg, dtype=int) if z.shape != ireg.shape or z.ndim != 2: raise ValueError, "z and ireg must be the same shape and 2-d" - ix, iy = nx.nonzero(ireg) + ix, iy = np.nonzero(ireg) # Now, add more indices x1m = ix - 1 y1m = iy-1 i1 = x1m>=0 i2 = y1m>=0 i3 = i1 & i2 - nix = nx.r_[ix, x1m[i1], x1m[i1], ix[i2] ] - niy = nx.r_[iy, iy[i1], y1m[i3], y1m[i2]] + nix = np.r_[ix, x1m[i1], x1m[i1], ix[i2] ] + niy = np.r_[iy, iy[i1], y1m[i3], y1m[i2]] # remove any negative indices zres = z[nix,niy] return zres.min().item(), zres.max().item() Modified: trunk/numpy/oldnumeric/compat.py =================================================================== --- trunk/numpy/oldnumeric/compat.py 2008-09-13 18:04:57 UTC (rev 5821) +++ trunk/numpy/oldnumeric/compat.py 2008-09-13 18:10:48 UTC (rev 5822) @@ -12,7 +12,7 @@ import numpy.core.multiarray as multiarray import numpy.core.umath as um -from numpy.core.numeric import array, correlate +from numpy.core.numeric import array import functions import sys Modified: trunk/numpy/oldnumeric/mlab.py =================================================================== --- trunk/numpy/oldnumeric/mlab.py 2008-09-13 18:04:57 UTC (rev 5821) +++ trunk/numpy/oldnumeric/mlab.py 2008-09-13 18:10:48 UTC (rev 5822) @@ -1,6 +1,10 @@ # This module is for compatibility only. All functions are defined elsewhere. -__all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', 'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc', 'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean'] +__all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', + 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', + 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', + 'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc', + 'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean'] import numpy.oldnumeric.linear_algebra as LinearAlgebra import numpy.oldnumeric.random_array as RandomArray @@ -12,7 +16,7 @@ from numpy.linalg import eig, svd from numpy.random import rand, randn -import numpy as nn +import numpy as np from typeconv import convtypecode @@ -22,7 +26,7 @@ """ dtype = convtypecode(typecode, dtype) if M is None: M = N - m = nn.equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) + m = np.equal(np.subtract.outer(np.arange(N), np.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) @@ -32,7 +36,7 @@ """ dtype = convtypecode(typecode, dtype) if M is None: M = N - m = nn.greater_equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) + m = np.greater_equal(np.subtract.outer(np.arange(N), np.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) Modified: trunk/numpy/oldnumeric/rng.py =================================================================== --- trunk/numpy/oldnumeric/rng.py 2008-09-13 18:04:57 UTC (rev 5821) +++ trunk/numpy/oldnumeric/rng.py 2008-09-13 18:10:48 UTC (rev 5822) @@ -4,9 +4,9 @@ # It is for backwards compatibility only. -__all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution','NormalDistribution', - 'UniformDistribution', 'error', 'default_distribution', 'random_sample', 'ranf', - 'standard_generator'] +__all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution', + 'NormalDistribution', 'UniformDistribution', 'error', 'ranf', + 'default_distribution', 'random_sample', 'standard_generator'] import numpy.random.mtrand as mt import math @@ -44,7 +44,7 @@ return 0.0 else: lambda_ = self._args[0] - return lambda_*exp(-lambda_*x) + return lambda_*math.exp(-lambda_*x) class LogNormalDistribution(Distribution): def __init__(self, m, s): @@ -61,7 +61,7 @@ def density(x): m,s = self._args y = (math.log(x)-self._mn)/self._sn - return self._fac*exp(-0.5*y*y)/x + return self._fac*math.exp(-0.5*y*y)/x class NormalDistribution(Distribution): @@ -76,7 +76,7 @@ def density(x): m,s = self._args y = (x-m)/s - return self._fac*exp(-0.5*y*y) + return self._fac*math.exp(-0.5*y*y) class UniformDistribution(Distribution): def __init__(self, a, b): From numpy-svn at scipy.org Sat Sep 13 14:15:40 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 13:15:40 -0500 (CDT) Subject: [Numpy-svn] r5823 - trunk/numpy/testing Message-ID: <20080913181540.C9A4039C072@scipy.org> Author: alan.mcintyre Date: 2008-09-13 13:15:38 -0500 (Sat, 13 Sep 2008) New Revision: 5823 Modified: trunk/numpy/testing/noseclasses.py Log: Removed unused imports. Fixed undefined reference to "getpackage" (from nose.util). Modified: trunk/numpy/testing/noseclasses.py =================================================================== --- trunk/numpy/testing/noseclasses.py 2008-09-13 18:10:48 UTC (rev 5822) +++ trunk/numpy/testing/noseclasses.py 2008-09-13 18:15:38 UTC (rev 5823) @@ -9,7 +9,7 @@ from nose.plugins import doctests as npd from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin from nose.plugins.base import Plugin -from nose.util import src, tolist +from nose.util import src, getpackage import numpy from nosetester import get_package_name import inspect @@ -79,10 +79,11 @@ # doctests in extension modules. # Local shorthands - from inspect import isroutine, isclass, ismodule + from inspect import isroutine, isclass, ismodule, isfunction, \ + ismethod # Look for tests in a module's contained objects. - if inspect.ismodule(obj) and self._recurse: + if ismodule(obj) and self._recurse: for valname, val in obj.__dict__.items(): valname1 = '%s.%s' % (name, valname) if ( (isroutine(val) or isclass(val)) @@ -93,7 +94,7 @@ # Look for tests in a class's contained objects. - if inspect.isclass(obj) and self._recurse: + if isclass(obj) and self._recurse: #print 'RECURSE into class:',obj # dbg for valname, val in obj.__dict__.items(): #valname1 = '%s.%s' % (name, valname) # dbg @@ -105,9 +106,8 @@ val = getattr(obj, valname).im_func # Recurse to methods, properties, and nested classes. - if ((inspect.isfunction(val) or inspect.isclass(val) or - inspect.ismethod(val) or - isinstance(val, property)) and + if ((isfunction(val) or isclass(val) or + ismethod(val) or isinstance(val, property)) and self._from_module(module, val)): valname = '%s.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, @@ -175,7 +175,6 @@ def configure(self, options, config): Plugin.configure(self, options, config) self.doctest_tests = True -# self.extension = tolist(options.doctestExtension) self.finder = NumpyDocTestFinder() self.parser = doctest.DocTestParser() From numpy-svn at scipy.org Sat Sep 13 17:17:11 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 13 Sep 2008 16:17:11 -0500 (CDT) Subject: [Numpy-svn] r5824 - in trunk/numpy/ma: . tests Message-ID: <20080913211711.34E1E39C072@scipy.org> Author: pierregm Date: 2008-09-13 16:17:09 -0500 (Sat, 13 Sep 2008) New Revision: 5824 Modified: trunk/numpy/ma/core.py trunk/numpy/ma/tests/test_core.py Log: MaskedArray.__new__ : make sure that we inherit the _hardmask from data (if any) instead of reverting to default. Modified: trunk/numpy/ma/core.py =================================================================== --- trunk/numpy/ma/core.py 2008-09-13 18:15:38 UTC (rev 5823) +++ trunk/numpy/ma/core.py 2008-09-13 21:17:09 UTC (rev 5824) @@ -1234,7 +1234,7 @@ def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, - keep_mask=True, hard_mask=False, flag=None, shrink=True, + keep_mask=True, hard_mask=None, flag=None, shrink=True, **options): """Create a new masked array from scratch. @@ -1338,7 +1338,10 @@ if fill_value is not None: _data._fill_value = _check_fill_value(fill_value, _data.dtype) # Process extra options .. - _data._hardmask = hard_mask + if hard_mask is None: + _data._hardmask = getattr(data, '_hardmask', False) + else: + _data._hardmask = hard_mask _data._baseclass = _baseclass return _data # Modified: trunk/numpy/ma/tests/test_core.py =================================================================== --- trunk/numpy/ma/tests/test_core.py 2008-09-13 18:15:38 UTC (rev 5823) +++ trunk/numpy/ma/tests/test_core.py 2008-09-13 21:17:09 UTC (rev 5824) @@ -173,10 +173,12 @@ def test_asarray(self): (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d xm.fill_value = -9999 + xm._hardmask = True xmm = asarray(xm) assert_equal(xmm._data, xm._data) assert_equal(xmm._mask, xm._mask) assert_equal(xmm.fill_value, xm.fill_value) + assert_equal(xmm._hardmask, xm._hardmask) def test_fix_invalid(self): "Checks fix_invalid." From numpy-svn at scipy.org Mon Sep 15 05:57:28 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 15 Sep 2008 04:57:28 -0500 (CDT) Subject: [Numpy-svn] r5825 - branches/1.1.x/numpy/lib/tests Message-ID: <20080915095728.313C139C05F@scipy.org> Author: stefan Date: 2008-09-15 04:57:10 -0500 (Mon, 15 Sep 2008) New Revision: 5825 Modified: branches/1.1.x/numpy/lib/tests/test_io.py Log: Fix test failure (closes #821). Modified: branches/1.1.x/numpy/lib/tests/test_io.py =================================================================== --- branches/1.1.x/numpy/lib/tests/test_io.py 2008-09-13 21:17:09 UTC (rev 5824) +++ branches/1.1.x/numpy/lib/tests/test_io.py 2008-09-15 09:57:10 UTC (rev 5825) @@ -164,7 +164,12 @@ def test_empty_file(self): c = StringIO.StringIO() - assert_raises(IOError, np.loadtxt, c) + try: + np.loadtxt(c) + except IOError: + return + else: + raise RuntimeError("Empty file should raise IOError.") class Testfromregex(NumpyTestCase): def test_record(self): From numpy-svn at scipy.org Wed Sep 17 23:29:59 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 17 Sep 2008 22:29:59 -0500 (CDT) Subject: [Numpy-svn] r5826 - trunk/doc Message-ID: <20080918032959.49B8539C10E@scipy.org> Author: alan.mcintyre Date: 2008-09-17 22:29:56 -0500 (Wed, 17 Sep 2008) New Revision: 5826 Modified: trunk/doc/TESTS.txt Log: Added documentation for doctests and using the skipif and knownfailureif decorators. Fixed indentation on the last sample snippet in the "__init__.py and setup.py" section. Modified: trunk/doc/TESTS.txt =================================================================== --- trunk/doc/TESTS.txt 2008-09-15 09:57:10 UTC (rev 5825) +++ trunk/doc/TESTS.txt 2008-09-18 03:29:56 UTC (rev 5826) @@ -150,6 +150,19 @@ Note that 'check_even' is not itself a test (no 'test' in the name), but 'test_evens' is a generator that returns a series of tests, using 'check_even', across a range of inputs. Nice. +Doctests +-------- + +Doctests are a convenient way of documenting the behavior a function and allowing that behavior to be tested at the same time. The output of an interactive Python session can be included in the docstring of a function, and the test framework can run the example and compare the actual output to the expected output. + +The doctests can be run by adding the ``doctests`` argument to the ``test()`` call; for example, to run all tests (including doctests) for numpy.lib:: + +>>> import numpy as np +>>> np.lib.test(doctests=True) + +The doctests are run as if they are in a fresh Python instance which has executed ``import numpy as np`` (tests that are part of the SciPy package also have an implicit ``import scipy as sp``). + + ``tests/`` ---------- @@ -188,13 +201,12 @@ >>> import scipy >>> scipy.xxx.test() -Also, when invoking the entire SciPy test suite, your tests will be found and run: +Also, when invoking the entire SciPy test suite, your tests will be found and run:: >>> import scipy >>> scipy.test() # your tests are included and run automatically! - Tips & Tricks ''''''''''''' @@ -230,9 +242,29 @@ In this case, we wanted to test solving a linear algebra problem using matrices of several data types, using ``linalg.solve`` and ``linalg.inv``. The common test cases (for single-precision, double-precision, etc. matrices) are collected in ``LinalgTestCase``. Note that ``LinalgTestCase`` is not descended from ``TestCase``--if it were, then nose would attempt to run ``LinalgTestCase.test_single`` and ``LinalgTestCase.test_double``, which would fail because ``LinalgTestCase`` has no ``do`` method. Since ``TestSolve`` and ``TestInv`` inherit from ``LinalgTestCase`` and ``TestCase``, nose will run ``test_single`` and ``test_double`` for each class. +Known failures & skipping tests +------------------------------- +Sometimes you might want to skip a test or mark it as a known failure, such as when the test suite is being written before the code it's meant to test, or if a test only fails on a particular architecture. The decorators from numpy.testing.dec can be used to do this. +To skip a test, simply use ``skipif``:: + from numpy.testing import * + @dec.skipif(SkipMyTest, "Skipping this test because...") + def test_something(foo): + ... +The test is marked as skipped if ``SkipMyTest`` evaluates to nonzero, and the message in verbose test output is the second argument given to ``skipif``. Similarly, a test can be marked as a known failure by using ``knownfailureif``:: + from numpy.testing import * + + @dec.knownfailureif(MyTestFails, "This test is known to fail because...") + def test_something_else(foo): + ... + +Of course, a test can be unconditionally skipped or marked as a known failure by passing ``True`` as the first argument to ``skipif`` or ``knownfailureif``, respectively. + +A total of the number of skipped and known failing tests is displayed at the end of the test run. Skipped tests are marked as ``'S'`` in the test results (or ``'SKIPPED'`` for ``verbosity > 1``), and known failing tests are marked as ``'K'`` (or ``'KNOWN'`` if ``verbosity > 1``). + + From numpy-svn at scipy.org Wed Sep 17 23:33:21 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 17 Sep 2008 22:33:21 -0500 (CDT) Subject: [Numpy-svn] r5827 - trunk/numpy/linalg Message-ID: <20080918033321.EA35139C10E@scipy.org> Author: alan.mcintyre Date: 2008-09-17 22:33:15 -0500 (Wed, 17 Sep 2008) New Revision: 5827 Modified: trunk/numpy/linalg/linalg.py Log: Rewrapped __all__ to conform with PEP8. Removed unused imports. Modified: trunk/numpy/linalg/linalg.py =================================================================== --- trunk/numpy/linalg/linalg.py 2008-09-18 03:29:56 UTC (rev 5826) +++ trunk/numpy/linalg/linalg.py 2008-09-18 03:33:15 UTC (rev 5827) @@ -9,16 +9,9 @@ zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr. """ -__all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', - 'inv', 'cholesky', - 'eigvals', - 'eigvalsh', 'pinv', - 'det', 'svd', - 'eig', 'eigh','lstsq', 'norm', - 'qr', - 'cond', - 'LinAlgError' - ] +__all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv', + 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'det', 'svd', + 'eig', 'eigh','lstsq', 'norm', 'qr', 'cond', 'LinAlgError'] from numpy.core import array, asarray, zeros, empty, transpose, \ intc, single, double, csingle, cdouble, inexact, complexfloating, \ @@ -27,7 +20,7 @@ isfinite, size from numpy.lib import triu from numpy.linalg import lapack_lite -from numpy.core.defmatrix import matrix_power, matrix +from numpy.core.defmatrix import matrix_power fortran_int = intc From numpy-svn at scipy.org Wed Sep 17 23:34:00 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 17 Sep 2008 22:34:00 -0500 (CDT) Subject: [Numpy-svn] r5828 - trunk/numpy/lib Message-ID: <20080918033400.0457B39C10E@scipy.org> Author: alan.mcintyre Date: 2008-09-17 22:33:58 -0500 (Wed, 17 Sep 2008) New Revision: 5828 Modified: trunk/numpy/lib/index_tricks.py trunk/numpy/lib/twodim_base.py trunk/numpy/lib/utils.py Log: Removed unused imports. Modified: trunk/numpy/lib/index_tricks.py =================================================================== --- trunk/numpy/lib/index_tricks.py 2008-09-18 03:33:15 UTC (rev 5827) +++ trunk/numpy/lib/index_tricks.py 2008-09-18 03:33:58 UTC (rev 5828) @@ -7,7 +7,7 @@ import sys import numpy.core.numeric as _nx -from numpy.core.numeric import asarray, ScalarType, array, dtype +from numpy.core.numeric import asarray, ScalarType, array from numpy.core.numerictypes import find_common_type import math Modified: trunk/numpy/lib/twodim_base.py =================================================================== --- trunk/numpy/lib/twodim_base.py 2008-09-18 03:33:15 UTC (rev 5827) +++ trunk/numpy/lib/twodim_base.py 2008-09-18 03:33:58 UTC (rev 5828) @@ -6,7 +6,7 @@ 'tril','vander','histogram2d'] from numpy.core.numeric import asanyarray, equal, subtract, arange, \ - zeros, arange, greater_equal, multiply, ones, asarray + zeros, greater_equal, multiply, ones, asarray def fliplr(m): """ Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2008-09-18 03:33:15 UTC (rev 5827) +++ trunk/numpy/lib/utils.py 2008-09-18 03:33:58 UTC (rev 5828) @@ -4,9 +4,7 @@ import types import re -from numpy.core.numerictypes import obj2sctype, generic, issubclass_, \ - issubsctype, issubdtype -from numpy.core.multiarray import dtype as _dtype +from numpy.core.numerictypes import issubclass_, issubsctype, issubdtype from numpy.core import product, ndarray __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', From numpy-svn at scipy.org Wed Sep 17 23:46:00 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 17 Sep 2008 22:46:00 -0500 (CDT) Subject: [Numpy-svn] r5829 - in trunk/numpy/f2py: . doc Message-ID: <20080918034600.BBA1B39C10E@scipy.org> Author: alan.mcintyre Date: 2008-09-17 22:45:53 -0500 (Wed, 17 Sep 2008) New Revision: 5829 Modified: trunk/numpy/f2py/auxfuncs.py trunk/numpy/f2py/cb_rules.py trunk/numpy/f2py/cfuncs.py trunk/numpy/f2py/common_rules.py trunk/numpy/f2py/crackfortran.py trunk/numpy/f2py/doc/collectinput.py trunk/numpy/f2py/f2py2e.py trunk/numpy/f2py/f2py_testing.py trunk/numpy/f2py/f90mod_rules.py trunk/numpy/f2py/func2subr.py trunk/numpy/f2py/use_rules.py Log: Removed unused/redundant imports. PEP8 conformance (only one import per line). Modified: trunk/numpy/f2py/auxfuncs.py =================================================================== --- trunk/numpy/f2py/auxfuncs.py 2008-09-18 03:33:58 UTC (rev 5828) +++ trunk/numpy/f2py/auxfuncs.py 2008-09-18 03:45:53 UTC (rev 5829) @@ -20,9 +20,7 @@ import pprint import sys -import time import types -import os import cfuncs Modified: trunk/numpy/f2py/cb_rules.py =================================================================== --- trunk/numpy/f2py/cb_rules.py 2008-09-18 03:33:58 UTC (rev 5828) +++ trunk/numpy/f2py/cb_rules.py 2008-09-18 03:45:53 UTC (rev 5829) @@ -21,16 +21,13 @@ import pprint import sys -import time import types -import copy errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint from auxfuncs import * import capi_maps -#from capi_maps import * import cfuncs ################## Rules for callback function ############## Modified: trunk/numpy/f2py/cfuncs.py =================================================================== --- trunk/numpy/f2py/cfuncs.py 2008-09-18 03:33:58 UTC (rev 5828) +++ trunk/numpy/f2py/cfuncs.py 2008-09-18 03:45:53 UTC (rev 5829) @@ -19,7 +19,9 @@ import __version__ f2py_version = __version__.version -import types,sys,copy,os +import types +import sys +import copy errmess=sys.stderr.write ##################### Definitions ################## Modified: trunk/numpy/f2py/common_rules.py =================================================================== --- trunk/numpy/f2py/common_rules.py 2008-09-18 03:33:58 UTC (rev 5828) +++ trunk/numpy/f2py/common_rules.py 2008-09-18 03:45:53 UTC (rev 5829) @@ -20,16 +20,12 @@ import pprint import sys -import time -import types -import copy errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint from auxfuncs import * import capi_maps -import cfuncs import func2subr from crackfortran import rmbadname ############## Modified: trunk/numpy/f2py/crackfortran.py =================================================================== --- trunk/numpy/f2py/crackfortran.py 2008-09-18 03:33:58 UTC (rev 5828) +++ trunk/numpy/f2py/crackfortran.py 2008-09-18 03:45:53 UTC (rev 5829) @@ -15,7 +15,6 @@ __version__ = "$Revision: 1.177 $"[10:-1] import __version__ -import string f2py_version = __version__.version """ Modified: trunk/numpy/f2py/doc/collectinput.py =================================================================== --- trunk/numpy/f2py/doc/collectinput.py 2008-09-18 03:33:58 UTC (rev 5828) +++ trunk/numpy/f2py/doc/collectinput.py 2008-09-18 03:45:53 UTC (rev 5829) @@ -23,7 +23,6 @@ stdoutflag=0 import sys -import os import fileinput import re import commands Modified: trunk/numpy/f2py/f2py2e.py =================================================================== --- trunk/numpy/f2py/f2py2e.py 2008-09-18 03:33:58 UTC (rev 5828) +++ trunk/numpy/f2py/f2py2e.py 2008-09-18 03:45:53 UTC (rev 5829) @@ -21,7 +21,6 @@ import sys import os import pprint -import shutil import types import re errmess=sys.stderr.write @@ -31,11 +30,8 @@ import crackfortran import rules import cb_rules -import common_rules import auxfuncs import cfuncs -import capi_maps -import func2subr import f90mod_rules outmess = auxfuncs.outmess @@ -395,7 +391,7 @@ """ Do it all in one call! """ - import tempfile,os,shutil + import tempfile i = sys.argv.index('-c') del sys.argv[i] @@ -547,6 +543,7 @@ setup(ext_modules = [ext]) if remove_build_dir and os.path.exists(build_dir): + import shutil outmess('Removing build directory %s\n'%(build_dir)) shutil.rmtree(build_dir) Modified: trunk/numpy/f2py/f2py_testing.py =================================================================== --- trunk/numpy/f2py/f2py_testing.py 2008-09-18 03:33:58 UTC (rev 5828) +++ trunk/numpy/f2py/f2py_testing.py 2008-09-18 03:45:53 UTC (rev 5829) @@ -1,4 +1,5 @@ -import os,sys,re,time +import sys +import re from numpy.testing.utils import jiffies, memusage Modified: trunk/numpy/f2py/f90mod_rules.py =================================================================== --- trunk/numpy/f2py/f90mod_rules.py 2008-09-18 03:33:58 UTC (rev 5828) +++ trunk/numpy/f2py/f90mod_rules.py 2008-09-18 03:45:53 UTC (rev 5829) @@ -17,11 +17,8 @@ f2py_version='See `f2py -v`' -import copy import pprint import sys -import time -import types errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint @@ -29,7 +26,6 @@ from auxfuncs import * import numpy as np import capi_maps -import cfuncs import rules import func2subr from crackfortran import undo_rmbadname, undo_rmbadname1 Modified: trunk/numpy/f2py/func2subr.py =================================================================== --- trunk/numpy/f2py/func2subr.py 2008-09-18 03:33:58 UTC (rev 5828) +++ trunk/numpy/f2py/func2subr.py 2008-09-18 03:45:53 UTC (rev 5829) @@ -20,9 +20,6 @@ import pprint import copy import sys -import time -import types -import copy errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint Modified: trunk/numpy/f2py/use_rules.py =================================================================== --- trunk/numpy/f2py/use_rules.py 2008-09-18 03:33:58 UTC (rev 5828) +++ trunk/numpy/f2py/use_rules.py 2008-09-18 03:45:53 UTC (rev 5829) @@ -21,16 +21,11 @@ import pprint import sys -import time -import types -import copy errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint from auxfuncs import * -import capi_maps -import cfuncs ############## usemodule_rules={ From numpy-svn at scipy.org Wed Sep 17 23:57:49 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 17 Sep 2008 22:57:49 -0500 (CDT) Subject: [Numpy-svn] r5830 - trunk/numpy Message-ID: <20080918035749.7A44939C10E@scipy.org> Author: alan.mcintyre Date: 2008-09-17 22:57:47 -0500 (Wed, 17 Sep 2008) New Revision: 5830 Modified: trunk/numpy/_import_tools.py Log: Removed redundant import. Modified: trunk/numpy/_import_tools.py =================================================================== --- trunk/numpy/_import_tools.py 2008-09-18 03:45:53 UTC (rev 5829) +++ trunk/numpy/_import_tools.py 2008-09-18 03:57:47 UTC (rev 5830) @@ -1,7 +1,5 @@ - import os import sys -import imp __all__ = ['PackageLoader'] From numpy-svn at scipy.org Thu Sep 18 13:51:58 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 18 Sep 2008 12:51:58 -0500 (CDT) Subject: [Numpy-svn] r5831 - in trunk/numpy/ma: . tests Message-ID: <20080918175158.1DE0D39C085@scipy.org> Author: pierregm Date: 2008-09-18 12:51:55 -0500 (Thu, 18 Sep 2008) New Revision: 5831 Modified: trunk/numpy/ma/extras.py trunk/numpy/ma/tests/test_extras.py Log: median : fixed a bug in _median1D (there shouldn't have been an axis) Modified: trunk/numpy/ma/extras.py =================================================================== --- trunk/numpy/ma/extras.py 2008-09-18 03:57:47 UTC (rev 5830) +++ trunk/numpy/ma/extras.py 2008-09-18 17:51:55 UTC (rev 5831) @@ -415,7 +415,7 @@ """ def _median1D(data): - counts = filled(count(data, axis),0) + counts = filled(count(data),0) (idx, rmd) = divmod(counts, 2) if rmd: choice = slice(idx, idx+1) Modified: trunk/numpy/ma/tests/test_extras.py =================================================================== --- trunk/numpy/ma/tests/test_extras.py 2008-09-18 03:57:47 UTC (rev 5830) +++ trunk/numpy/ma/tests/test_extras.py 2008-09-18 17:51:55 UTC (rev 5831) @@ -11,7 +11,7 @@ __revision__ = "$Revision: 3473 $" __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' -import numpy +import numpy as np from numpy.testing import TestCase, run_module_suite from numpy.ma.testutils import * from numpy.ma.core import * @@ -332,25 +332,36 @@ def test_2d(self): "Tests median w/ 2D" (n,p) = (101,30) - x = masked_array(numpy.linspace(-1.,1.,n),) + x = masked_array(np.linspace(-1.,1.,n),) x[:10] = x[-10:] = masked - z = masked_array(numpy.empty((n,p), dtype=numpy.float_)) + z = masked_array(np.empty((n,p), dtype=float)) z[:,0] = x[:] - idx = numpy.arange(len(x)) + idx = np.arange(len(x)) for i in range(1,p): - numpy.random.shuffle(idx) + np.random.shuffle(idx) z[:,i] = x[idx] assert_equal(median(z[:,0]), 0) - assert_equal(median(z), numpy.zeros((p,))) + assert_equal(median(z), 0) + assert_equal(median(z, axis=0), np.zeros(p)) + assert_equal(median(z.T, axis=1), np.zeros(p)) # + def test_2d_waxis(self): + "Tests median w/ 2D arrays and different axis." + x = masked_array(np.arange(30).reshape(10,3)) + x[:3] = x[-3:] = masked + assert_equal(median(x), 14.5) + assert_equal(median(x, axis=0), [13.5,14.5,15.5]) + assert_equal(median(x,axis=1), [0,0,0,10,13,16,19,0,0,0]) + assert_equal(median(x,axis=1).mask, [1,1,1,0,0,0,0,1,1,1]) + # def test_3d(self): "Tests median w/ 3D" - x = numpy.ma.arange(24).reshape(3,4,2) + x = np.ma.arange(24).reshape(3,4,2) x[x%3==0] = masked assert_equal(median(x,0), [[12,9],[6,15],[12,9],[18,15]]) x.shape = (4,3,2) assert_equal(median(x,0),[[99,10],[11,99],[13,14]]) - x = numpy.ma.arange(24).reshape(4,3,2) + x = np.ma.arange(24).reshape(4,3,2) x[x%5==0] = masked assert_equal(median(x,0), [[12,10],[8,9],[16,17]]) @@ -483,9 +494,9 @@ def test_polyfit(self): "Tests polyfit" # On ndarrays - x = numpy.random.rand(10) - y = numpy.random.rand(20).reshape(-1,2) - assert_almost_equal(polyfit(x,y,3),numpy.polyfit(x,y,3)) + x = np.random.rand(10) + y = np.random.rand(20).reshape(-1,2) + assert_almost_equal(polyfit(x,y,3),np.polyfit(x,y,3)) # ON 1D maskedarrays x = x.view(MaskedArray) x[0] = masked @@ -493,17 +504,17 @@ y[0,0] = y[-1,-1] = masked # (C,R,K,S,D) = polyfit(x,y[:,0],3,full=True) - (c,r,k,s,d) = numpy.polyfit(x[1:], y[1:,0].compressed(), 3, full=True) + (c,r,k,s,d) = np.polyfit(x[1:], y[1:,0].compressed(), 3, full=True) for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)): assert_almost_equal(a, a_) # (C,R,K,S,D) = polyfit(x,y[:,-1],3,full=True) - (c,r,k,s,d) = numpy.polyfit(x[1:-1], y[1:-1,-1], 3, full=True) + (c,r,k,s,d) = np.polyfit(x[1:-1], y[1:-1,-1], 3, full=True) for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)): assert_almost_equal(a, a_) # (C,R,K,S,D) = polyfit(x,y,3,full=True) - (c,r,k,s,d) = numpy.polyfit(x[1:-1], y[1:-1,:], 3, full=True) + (c,r,k,s,d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True) for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)): assert_almost_equal(a, a_) From numpy-svn at scipy.org Thu Sep 18 14:54:07 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 18 Sep 2008 13:54:07 -0500 (CDT) Subject: [Numpy-svn] r5832 - trunk/doc Message-ID: <20080918185407.15ECE39C021@scipy.org> Author: jarrod.millman Date: 2008-09-18 13:53:53 -0500 (Thu, 18 Sep 2008) New Revision: 5832 Modified: trunk/doc/TESTS.txt Log: ReSTified an URL Modified: trunk/doc/TESTS.txt =================================================================== --- trunk/doc/TESTS.txt 2008-09-18 17:51:55 UTC (rev 5831) +++ trunk/doc/TESTS.txt 2008-09-18 18:53:53 UTC (rev 5832) @@ -58,7 +58,7 @@ run_module_suite() -Note that all classes that are inherited from ``TestCase`` class, are picked up by the test runner. For more detailed information on defining test classes see the official documentation for the [http://docs.python.org/lib/module-unittest.html Python Unit testing framework]. +Note that all classes that are inherited from ``TestCase`` class, are picked up by the test runner. For more detailed information on defining test classes see the official documentation for the `Python Unit testing framework `__. Using test functions with nose ------------------------------ From numpy-svn at scipy.org Thu Sep 18 17:48:58 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 18 Sep 2008 16:48:58 -0500 (CDT) Subject: [Numpy-svn] r5833 - trunk/numpy/distutils/command Message-ID: <20080918214858.5C32B39C021@scipy.org> Author: rkern Date: 2008-09-18 16:48:57 -0500 (Thu, 18 Sep 2008) New Revision: 5833 Modified: trunk/numpy/distutils/command/install.py Log: BUG: Override setuptools' install.run() method to correctly allow 'python setup.py install' to work. Modified: trunk/numpy/distutils/command/install.py =================================================================== --- trunk/numpy/distutils/command/install.py 2008-09-18 18:53:53 UTC (rev 5832) +++ trunk/numpy/distutils/command/install.py 2008-09-18 21:48:57 UTC (rev 5833) @@ -1,8 +1,10 @@ import sys if 'setuptools' in sys.modules: import setuptools.command.install as old_install_mod + have_setuptools = True else: import distutils.command.install as old_install_mod + have_setuptools = False old_install = old_install_mod.install from distutils.file_util import write_file @@ -12,8 +14,41 @@ old_install.finalize_options(self) self.install_lib = self.install_libbase + def setuptools_run(self): + """ The setuptools version of the .run() method. + + We must pull in the entire code so we can override the level used in the + _getframe() call since we wrap this call by one more level. + """ + # Explicit request for old-style install? Just do it + if self.old_and_unmanageable or self.single_version_externally_managed: + return old_install_mod._install.run(self) + + # Attempt to detect whether we were called from setup() or by another + # command. If we were called by setup(), our caller will be the + # 'run_command' method in 'distutils.dist', and *its* caller will be + # the 'run_commands' method. If we were called any other way, our + # immediate caller *might* be 'run_command', but it won't have been + # called by 'run_commands'. This is slightly kludgy, but seems to + # work. + # + caller = sys._getframe(3) + caller_module = caller.f_globals.get('__name__','') + caller_name = caller.f_code.co_name + + if caller_module != 'distutils.dist' or caller_name!='run_commands': + # We weren't called from the command line or setup(), so we + # should run in backward-compatibility mode to support bdist_* + # commands. + old_install_mod._install.run(self) + else: + self.do_egg_install() + def run(self): - r = old_install.run(self) + if not have_setuptools: + r = old_install.run(self) + else: + r = self.setuptools_run() if self.record: # bdist_rpm fails when INSTALLED_FILES contains # paths with spaces. Such paths must be enclosed From numpy-svn at scipy.org Thu Sep 18 23:33:42 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 18 Sep 2008 22:33:42 -0500 (CDT) Subject: [Numpy-svn] r5834 - trunk/numpy/core Message-ID: <20080919033342.8731C39C164@scipy.org> Author: pierregm Date: 2008-09-18 22:33:40 -0500 (Thu, 18 Sep 2008) New Revision: 5834 Modified: trunk/numpy/core/records.py Log: * fixing view to recognize dtype and type parameters, for consistency with regular ndarrays. Modified: trunk/numpy/core/records.py =================================================================== --- trunk/numpy/core/records.py 2008-09-18 21:48:57 UTC (rev 5833) +++ trunk/numpy/core/records.py 2008-09-19 03:33:40 UTC (rev 5834) @@ -448,17 +448,23 @@ else: return self.setfield(val, *res) - def view(self, obj): - try: - if issubclass(obj, ndarray): - return ndarray.view(self, obj) - except TypeError: - pass - dtype = sb.dtype(obj) - if dtype.fields is None: - return self.__array__().view(dtype) - return ndarray.view(self, obj) + def view(self, dtype=None, type=None): + if dtype is None: + return ndarray.view(self, type) + elif type is None: + try: + if issubclass(dtype, ndarray): + return ndarray.view(self, dtype) + except TypeError: + pass + dtype = sb.dtype(dtype) + if dtype.fields is None: + return self.__array__().view(dtype) + return ndarray.view(self, dtype) + else: + return ndarray.view(self, dtype, type) + def fromarrays(arrayList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None): """ create a record array from a (flat) list of arrays From numpy-svn at scipy.org Fri Sep 19 15:43:09 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Fri, 19 Sep 2008 14:43:09 -0500 (CDT) Subject: [Numpy-svn] r5835 - in trunk/numpy/ma: . tests Message-ID: <20080919194309.88BA439C1EC@scipy.org> Author: pierregm Date: 2008-09-19 14:43:05 -0500 (Fri, 19 Sep 2008) New Revision: 5835 Modified: trunk/numpy/ma/core.py trunk/numpy/ma/mrecords.py trunk/numpy/ma/tests/test_core.py trunk/numpy/ma/tests/test_mrecords.py Log: core: * add dtype to the repr of masked arrays w/ flexible type * prevent __getitem__ to return masked on flexible-type masked array * make sure __str__ returns something sensible for flexible dtype w/ masked fields * simplify the count method mrecords: * fixed a pb with fromrecords when the number of fields cannot be determined from the first element. Modified: trunk/numpy/ma/core.py =================================================================== --- trunk/numpy/ma/core.py 2008-09-19 03:33:40 UTC (rev 5834) +++ trunk/numpy/ma/core.py 2008-09-19 19:43:05 UTC (rev 5835) @@ -1479,15 +1479,22 @@ # if getmask(indx) is not nomask: # msg = "Masked arrays must be filled before they can be used as indices!" # raise IndexError, msg - dout = ndarray.__getitem__(self.view(ndarray), indx) + dout = ndarray.__getitem__(ndarray.view(self,ndarray), indx) # We could directly use ndarray.__getitem__ on self... # But then we would have to modify __array_finalize__ to prevent the # mask of being reshaped if it hasn't been set up properly yet... # So it's easier to stick to the current version _mask = self._mask if not getattr(dout,'ndim', False): + # A record ................ + if isinstance(dout, np.void): + mask = _mask[indx] + if mask.view((bool,len(mask.dtype))).any(): + dout = masked_array(dout, mask=mask) + else: + return dout # Just a scalar............ - if _mask is not nomask and _mask[indx]: + elif _mask is not nomask and _mask[indx]: return masked else: # Force dout to MA ........ @@ -1896,7 +1903,15 @@ res = self._data else: if m.shape == (): - if m: + if m.dtype.names: + m = m.view((bool, len(m.dtype))) + if m.any(): + r = np.array(self._data.tolist(), dtype=object) + np.putmask(r, m, f) + return str(tuple(r)) + else: + return str(self._data) + elif m: return str(f) else: return str(self._data) @@ -1933,21 +1948,31 @@ mask = %(mask)s, fill_value=%(fill)s) """ + with_mask_flx = """\ +masked_%(name)s(data = + %(data)s, + mask = + %(mask)s, + fill_value=%(fill)s, + dtype=%(dtype)s) +""" + with_mask1_flx = """\ +masked_%(name)s(data = %(data)s, + mask = %(mask)s, + fill_value=%(fill)s + dtype=%(dtype)s) +""" n = len(self.shape) name = repr(self._data).split('(')[0] - if n <= 1: - return with_mask1 % { - 'name': name, - 'data': str(self), - 'mask': str(self._mask), - 'fill': str(self.fill_value), - } - return with_mask % { - 'name': name, - 'data': str(self), - 'mask': str(self._mask), - 'fill': str(self.fill_value), - } + parameters = dict(name=name, data=str(self), mask=str(self._mask), + fill=str(self.fill_value), dtype=str(self.dtype)) + if self.dtype.names: + if n<= 1: + return with_mask1_flx % parameters + return with_mask_flx % parameters + elif n <= 1: + return with_mask1 % parameters + return with_mask % parameters #............................................ def __add__(self, other): "Add other to self, and return a new masked array." @@ -3509,6 +3534,8 @@ return data def count(a, axis = None): + if isinstance(a, MaskedArray): + return a.count(axis) return masked_array(a, copy=False).count(axis) count.__doc__ = MaskedArray.count.__doc__ Modified: trunk/numpy/ma/mrecords.py =================================================================== --- trunk/numpy/ma/mrecords.py 2008-09-19 03:33:40 UTC (rev 5834) +++ trunk/numpy/ma/mrecords.py 2008-09-19 19:43:05 UTC (rev 5835) @@ -151,10 +151,9 @@ return self #...................................................... def __array_finalize__(self,obj): - MaskedArray._update_from(self,obj) # Make sure we have a _fieldmask by default .. - _fieldmask = getattr(obj, '_fieldmask', None) - if _fieldmask is None: + _mask = getattr(obj, '_mask', None) + if _mask is None: objmask = getattr(obj, '_mask', nomask) _dtype = ndarray.__getattribute__(self,'dtype') if objmask is nomask: @@ -163,15 +162,15 @@ mdescr = ma.make_mask_descr(_dtype) _mask = narray([tuple([m]*len(mdescr)) for m in objmask], dtype=mdescr).view(recarray) - else: - _mask = _fieldmask # Update some of the attributes - _locdict = self.__dict__ - if _locdict['_baseclass'] == ndarray: - _locdict['_baseclass'] = recarray - _locdict.update(_mask=_mask, _fieldmask=_mask) + _dict = self.__dict__ + _dict.update(_mask=_mask, _fieldmask=_mask) + self._update_from(obj) + if _dict['_baseclass'] == ndarray: + _dict['_baseclass'] = recarray return + def _getdata(self): "Returns the data as a recarray." return ndarray.view(self,recarray) @@ -248,7 +247,6 @@ # Get the list of names ...... fielddict = ndarray.__getattribute__(self,'dtype').fields or {} # Check the attribute -##### _localdict = self.__dict__ if attr not in fielddict: return ret if newattr: # We just added this one @@ -282,8 +280,8 @@ """Returns all the fields sharing the same fieldname base. The fieldname base is either `_data` or `_mask`.""" _localdict = self.__dict__ - _mask = _localdict['_fieldmask'] - _data = self._data + _mask = ndarray.__getattribute__(self,'_mask') + _data = ndarray.view(self, _localdict['_baseclass']) # We want a field ........ if isinstance(indx, basestring): #!!!: Make sure _sharedmask is True to propagate back to _fieldmask @@ -471,7 +469,7 @@ dtype=dtype, shape=shape, formats=formats, names=names, titles=titles, aligned=aligned, byteorder=byteorder).view(mrecarray) - _array._fieldmask.flat = zip(*masklist) + _array._mask.flat = zip(*masklist) if fill_value is not None: _array.fill_value = fill_value return _array @@ -505,13 +503,17 @@ mask : {nomask, sequence}, optional. External mask to apply on the data. -*Notes*: + Notes + ----- Lists of tuples should be preferred over lists of lists for faster processing. """ # Grab the initial _fieldmask, if needed: _fieldmask = getattr(reclist, '_fieldmask', None) # Get the list of records..... - nfields = len(reclist[0]) + try: + nfields = len(reclist[0]) + except TypeError: + nfields = len(reclist[0].dtype) if isinstance(reclist, ndarray): # Make sure we don't have some hidden mask if isinstance(reclist,MaskedArray): @@ -654,7 +656,7 @@ set to 'fi', where `i` is the number of existing fields. """ _data = mrecord._data - _mask = mrecord._fieldmask + _mask = mrecord._mask if newfieldname is None or newfieldname in reserved_fields: newfieldname = 'f%i' % len(_data.dtype) newfield = ma.array(newfield) Modified: trunk/numpy/ma/tests/test_core.py =================================================================== --- trunk/numpy/ma/tests/test_core.py 2008-09-19 03:33:40 UTC (rev 5834) +++ trunk/numpy/ma/tests/test_core.py 2008-09-19 19:43:05 UTC (rev 5835) @@ -2372,8 +2372,24 @@ test = a.view((float,2), np.matrix) assert_equal(test, data) assert(isinstance(test, np.matrix)) + # + def test_getitem(self): + ndtype = [('a',float), ('b',float)] + a = array(zip(np.random.rand(10),np.arange(10)), dtype=ndtype) + a.mask = np.array(zip([0,0,0,0,0,0,0,0,1,1], + [1,0,0,0,0,0,0,0,1,0]), + dtype=[('a',bool),('b',bool)]) + # No mask + assert(isinstance(a[1], np.void)) + # One element masked + assert(isinstance(a[0], MaskedArray)) + assert_equal_records(a[0]._data, a._data[0]) + assert_equal_records(a[0]._mask, a._mask[0]) + # All element masked + assert(isinstance(a[-2], MaskedArray)) + assert_equal_records(a[-2]._data, a._data[-2]) + assert_equal_records(a[-2]._mask, a._mask[-2]) - ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": Modified: trunk/numpy/ma/tests/test_mrecords.py =================================================================== --- trunk/numpy/ma/tests/test_mrecords.py 2008-09-19 03:33:40 UTC (rev 5834) +++ trunk/numpy/ma/tests/test_mrecords.py 2008-09-19 19:43:05 UTC (rev 5835) @@ -203,8 +203,8 @@ # def test_set_elements(self): base = self.base.copy() - mbase = base.view(mrecarray) # Set an element to mask ..................... + mbase = base.view(mrecarray).copy() mbase[-2] = masked assert_equal(mbase._fieldmask.tolist(), np.array([(0,0,0),(1,1,1),(0,0,0),(1,1,1),(1,1,1)], From numpy-svn at scipy.org Sat Sep 20 04:22:32 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 03:22:32 -0500 (CDT) Subject: [Numpy-svn] r5836 - branches/clean_math_config/numpy/core Message-ID: <20080920082232.6CDD339C088@scipy.org> Author: cdavid Date: 2008-09-20 03:22:25 -0500 (Sat, 20 Sep 2008) New Revision: 5836 Modified: branches/clean_math_config/numpy/core/setup.py Log: Include Python.h before math.h for declaration tests in mathlib. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-19 19:43:05 UTC (rev 5835) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-20 08:22:25 UTC (rev 5836) @@ -94,8 +94,10 @@ # Normally, isnan and isinf are macro (C99), but some platforms only have # func, or both func and macro version. Check for macro only, and define # replacement ones if not found. + # Note: including Python.h is necessary because it modifies some math.h + # definitions for f in ["isnan", "isinf", "signbit", "isfinite"]: - st = config.check_decl(f, headers = ["math.h"]) + st = config.check_decl(f, headers = ["Python.h", "math.h"]) if st: moredefs.append(name_to_defsymb("decl_%s" % f)) From numpy-svn at scipy.org Sat Sep 20 04:47:32 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 03:47:32 -0500 (CDT) Subject: [Numpy-svn] r5837 - in branches/clean_math_config/numpy/core: . src Message-ID: <20080920084732.69EF739C088@scipy.org> Author: cdavid Date: 2008-09-20 03:47:19 -0500 (Sat, 20 Sep 2008) New Revision: 5837 Added: branches/clean_math_config/numpy/core/src/math_c99.inc.src Removed: branches/clean_math_config/numpy/core/src/math_c99.c branches/clean_math_config/numpy/core/src/math_c99.c.src Modified: branches/clean_math_config/numpy/core/setup.py branches/clean_math_config/numpy/core/src/umathmodule.c.src Log: Remove the generated math_c99.c file from svn; generate it automatically from setup.py. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-20 08:22:25 UTC (rev 5836) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-20 08:47:19 UTC (rev 5837) @@ -354,10 +354,10 @@ generate_ufunc_api, join('src','scalartypes.inc.src'), join('src','arraytypes.inc.src'), + join('src','math_c99.inc.src'), ], depends = [join('src','ufuncobject.c'), generate_umath_py, - join('src','math_c99.c'), join(codegen_dir,'generate_ufunc_api.py'), ]+deps, ) Deleted: branches/clean_math_config/numpy/core/src/math_c99.c =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-20 08:22:25 UTC (rev 5836) +++ branches/clean_math_config/numpy/core/src/math_c99.c 2008-09-20 08:47:19 UTC (rev 5837) @@ -1,727 +0,0 @@ - -/* - ***************************************************************************** - ** This file was autogenerated from a template DO NOT EDIT!!!! ** - ** Changes should be made to the original source (.src) file ** - ***************************************************************************** - */ - -#line 1 -/* - * vim:syntax=c - * A small module to implement missing C99 math capabilities required by numpy - * - * Please keep this independant of python ! - */ - -/* - ***************************************************************************** - ** BASIC MATH FUNCTIONS ** - ***************************************************************************** - */ - -/* Original code by Konrad Hinsen. */ -#ifndef HAVE_EXPM1 -double expm1(double x) -{ - double u = exp(x); - if (u == 1.0) { - return x; - } else if (u-1.0 == -1.0) { - return -1; - } else { - return (u-1.0) * x/log(u); - } -} -#endif - -#ifndef HAVE_LOG1P -double log1p(double x) -{ - double u = 1. + x; - if (u == 1.0) { - return x; - } else { - return log(u) * x / (u-1.); - } -} -#endif - -#ifndef HAVE_HYPOT -double hypot(double x, double y) -{ - double yx; - - x = fabs(x); - y = fabs(y); - if (x < y) { - double temp = x; - x = y; - y = temp; - } - if (x == 0.) - return 0.; - else { - yx = y/x; - return x*sqrt(1.+yx*yx); - } -} -#endif - -#ifndef HAVE_ACOSH -double acosh(double x) -{ - return 2*log(sqrt((x+1.0)/2)+sqrt((x-1.0)/2)); -} -#endif - -#ifndef HAVE_ASINH -double asinh(double xx) -{ - double x, d; - int sign; - if (xx < 0.0) { - sign = -1; - x = -xx; - } - else { - sign = 1; - x = xx; - } - if (x > 1e8) { - d = x; - } else { - d = sqrt(x*x + 1); - } - return sign*log1p(x*(1.0 + x/(d+1))); -} -#endif - -#ifndef HAVE_ATANH -static double atanh(double x) -{ - return 0.5*log1p(2.0*x/(1.0-x)); -} -#endif - -#ifndef HAVE_RINT -double rint(double x) -{ - double y, r; - - y = floor(x); - r = x - y; - - if (r > 0.5) goto rndup; - - /* Round to nearest even */ - if (r==0.5) { - r = y - 2.0*floor(0.5*y); - if (r==1.0) { - rndup: - y+=1.0; - } - } - return y; -} -#endif - -#ifndef HAVE_TRUNC -double trunc(double x) -{ - if (x < 0) { - return ceil(x); - } - else { - return floor(x); - } - -} -#endif - -/* - ***************************************************************************** - ** IEEE 754 FPU HANDLING ** - ***************************************************************************** - */ -#if !defined(HAVE_DECL_ISNAN) - # define isnan(x) \ - (sizeof (x) == sizeof (long double) ? isnan_ld (x) \ - : sizeof (x) == sizeof (double) ? isnan_d (x) \ - : isnan_f (x)) -static int isnan_f (float x) -{ - return x != x; -} - -static int isnan_d (double x) -{ - return x != x; -} - -static int isnan_ld (long double x) -{ - return x != x; -} -#endif - -#if !defined(HAVE_DECL_ISINF) - # define isinf(x) \ - (sizeof (x) == sizeof (long double) ? isinf_ld (x) \ - : sizeof (x) == sizeof (double) ? isinf_d (x) \ - : isinf_f (x)) - -static int isinf_f (float x) -{ - return isnan (x - x); -} - -static int isinf_d (double x) -{ - return isnan (x - x); -} - -static int isinf_ld (long double x) -{ - return isnan (x - x); -} -#endif - -#if !defined(HAVE_DECL_SIGNBIT) - #include "_signbit.c" - # define signbit(x) \ - (sizeof (x) == sizeof (long double) ? signbit_ld (x) \ - : sizeof (x) == sizeof (double) ? signbit_d (x) \ - : signbit_f (x)) - -static int signbit_f (float x) -{ - return signbit_d((double)x); -} - -static int signbit_ld (long double x) -{ - return signbit_d((double)x); -} -#endif - -/* Define isfinie if needed */ -#if !defined(HAVE_DECL_ISFINITE) -#define isfinite(x) (!(isinf((x)) || isnan((x)))) -#endif - -/* - * if C99 extensions not available then define dummy functions that use the - * double versions for - * - * sin, cos, tan - * sinh, cosh, tanh, - * fabs, floor, ceil, rint, trunc - * sqrt, log10, log, exp, expm1 - * asin, acos, atan, - * asinh, acosh, atanh - * - * hypot, atan2, pow, fmod, modf - * - * We assume the above are always available in their double versions. - */ - -/* - * One value argument function - */ - -#line 233 - -#ifndef HAVE_SINL -longdouble sinl(longdouble x) -{ - return (longdouble) sin((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_COSL -longdouble cosl(longdouble x) -{ - return (longdouble) cos((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_TANL -longdouble tanl(longdouble x) -{ - return (longdouble) tan((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_SINHL -longdouble sinhl(longdouble x) -{ - return (longdouble) sinh((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_COSHL -longdouble coshl(longdouble x) -{ - return (longdouble) cosh((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_TANHL -longdouble tanhl(longdouble x) -{ - return (longdouble) tanh((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_FABSL -longdouble fabsl(longdouble x) -{ - return (longdouble) fabs((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_FLOORL -longdouble floorl(longdouble x) -{ - return (longdouble) floor((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_CEILL -longdouble ceill(longdouble x) -{ - return (longdouble) ceil((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_RINTL -longdouble rintl(longdouble x) -{ - return (longdouble) rint((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_TRUNCL -longdouble truncl(longdouble x) -{ - return (longdouble) trunc((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_SQRTL -longdouble sqrtl(longdouble x) -{ - return (longdouble) sqrt((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_LOG10L -longdouble log10l(longdouble x) -{ - return (longdouble) log10((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_LOGL -longdouble logl(longdouble x) -{ - return (longdouble) log((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_EXPL -longdouble expl(longdouble x) -{ - return (longdouble) exp((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_EXPM1L -longdouble expm1l(longdouble x) -{ - return (longdouble) expm1((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ASINL -longdouble asinl(longdouble x) -{ - return (longdouble) asin((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ACOSL -longdouble acosl(longdouble x) -{ - return (longdouble) acos((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ATANL -longdouble atanl(longdouble x) -{ - return (longdouble) atan((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ASINHL -longdouble asinhl(longdouble x) -{ - return (longdouble) asinh((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ACOSHL -longdouble acoshl(longdouble x) -{ - return (longdouble) acosh((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ATANHL -longdouble atanhl(longdouble x) -{ - return (longdouble) atanh((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_SINF -float sinf(float x) -{ - return (float) sin((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_COSF -float cosf(float x) -{ - return (float) cos((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_TANF -float tanf(float x) -{ - return (float) tan((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_SINHF -float sinhf(float x) -{ - return (float) sinh((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_COSHF -float coshf(float x) -{ - return (float) cosh((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_TANHF -float tanhf(float x) -{ - return (float) tanh((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_FABSF -float fabsf(float x) -{ - return (float) fabs((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_FLOORF -float floorf(float x) -{ - return (float) floor((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_CEILF -float ceilf(float x) -{ - return (float) ceil((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_RINTF -float rintf(float x) -{ - return (float) rint((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_TRUNCF -float truncf(float x) -{ - return (float) trunc((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_SQRTF -float sqrtf(float x) -{ - return (float) sqrt((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_LOG10F -float log10f(float x) -{ - return (float) log10((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_LOGF -float logf(float x) -{ - return (float) log((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_EXPF -float expf(float x) -{ - return (float) exp((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_EXPM1F -float expm1f(float x) -{ - return (float) expm1((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ASINF -float asinf(float x) -{ - return (float) asin((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ACOSF -float acosf(float x) -{ - return (float) acos((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ATANF -float atanf(float x) -{ - return (float) atan((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ASINHF -float asinhf(float x) -{ - return (float) asinh((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ACOSHF -float acoshf(float x) -{ - return (float) acosh((double)x); -} -#endif - -#line 233 - -#ifndef HAVE_ATANHF -float atanhf(float x) -{ - return (float) atanh((double)x); -} -#endif - - -/* - * Two values arguments function - */ - -#line 255 -#ifndef HAVE_ATAN2L -longdouble atan2l(longdouble x, longdouble y) -{ - return (longdouble) atan2((double)x, (double) y); -} -#endif - -#line 255 -#ifndef HAVE_HYPOTL -longdouble hypotl(longdouble x, longdouble y) -{ - return (longdouble) hypot((double)x, (double) y); -} -#endif - -#line 255 -#ifndef HAVE_POWL -longdouble powl(longdouble x, longdouble y) -{ - return (longdouble) pow((double)x, (double) y); -} -#endif - -#line 255 -#ifndef HAVE_FMODL -longdouble fmodl(longdouble x, longdouble y) -{ - return (longdouble) fmod((double)x, (double) y); -} -#endif - -#line 255 -#ifndef HAVE_ATAN2F -float atan2f(float x, float y) -{ - return (float) atan2((double)x, (double) y); -} -#endif - -#line 255 -#ifndef HAVE_HYPOTF -float hypotf(float x, float y) -{ - return (float) hypot((double)x, (double) y); -} -#endif - -#line 255 -#ifndef HAVE_POWF -float powf(float x, float y) -{ - return (float) pow((double)x, (double) y); -} -#endif - -#line 255 -#ifndef HAVE_FMODF -float fmodf(float x, float y) -{ - return (float) fmod((double)x, (double) y); -} -#endif - - -/* - * One value - one pointer argument function - */ - -#line 275 -#ifndef HAVE_MODFL -longdouble modfl(longdouble x, longdouble *iptr) -{ - double nx, niptr, y; - nx = (double) x; - y = modf(nx, &niptr); - *iptr = (longdouble) niptr; - return (longdouble) y; -} -#endif - -#line 275 -#ifndef HAVE_MODFF -float modff(float x, float *iptr) -{ - double nx, niptr, y; - nx = (double) x; - y = modf(nx, &niptr); - *iptr = (float) niptr; - return (float) y; -} -#endif - - Deleted: branches/clean_math_config/numpy/core/src/math_c99.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-20 08:22:25 UTC (rev 5836) +++ branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-20 08:47:19 UTC (rev 5837) @@ -1,285 +0,0 @@ -/* - * vim:syntax=c - * A small module to implement missing C99 math capabilities required by numpy - * - * Please keep this independant of python ! - */ - -/* - ***************************************************************************** - ** BASIC MATH FUNCTIONS ** - ***************************************************************************** - */ - -/* Original code by Konrad Hinsen. */ -#ifndef HAVE_EXPM1 -double expm1(double x) -{ - double u = exp(x); - if (u == 1.0) { - return x; - } else if (u-1.0 == -1.0) { - return -1; - } else { - return (u-1.0) * x/log(u); - } -} -#endif - -#ifndef HAVE_LOG1P -double log1p(double x) -{ - double u = 1. + x; - if (u == 1.0) { - return x; - } else { - return log(u) * x / (u-1.); - } -} -#endif - -#ifndef HAVE_HYPOT -double hypot(double x, double y) -{ - double yx; - - x = fabs(x); - y = fabs(y); - if (x < y) { - double temp = x; - x = y; - y = temp; - } - if (x == 0.) - return 0.; - else { - yx = y/x; - return x*sqrt(1.+yx*yx); - } -} -#endif - -#ifndef HAVE_ACOSH -double acosh(double x) -{ - return 2*log(sqrt((x+1.0)/2)+sqrt((x-1.0)/2)); -} -#endif - -#ifndef HAVE_ASINH -double asinh(double xx) -{ - double x, d; - int sign; - if (xx < 0.0) { - sign = -1; - x = -xx; - } - else { - sign = 1; - x = xx; - } - if (x > 1e8) { - d = x; - } else { - d = sqrt(x*x + 1); - } - return sign*log1p(x*(1.0 + x/(d+1))); -} -#endif - -#ifndef HAVE_ATANH -static double atanh(double x) -{ - return 0.5*log1p(2.0*x/(1.0-x)); -} -#endif - -#ifndef HAVE_RINT -double rint(double x) -{ - double y, r; - - y = floor(x); - r = x - y; - - if (r > 0.5) goto rndup; - - /* Round to nearest even */ - if (r==0.5) { - r = y - 2.0*floor(0.5*y); - if (r==1.0) { - rndup: - y+=1.0; - } - } - return y; -} -#endif - -#ifndef HAVE_TRUNC -double trunc(double x) -{ - if (x < 0) { - return ceil(x); - } - else { - return floor(x); - } - -} -#endif - -/* - ***************************************************************************** - ** IEEE 754 FPU HANDLING ** - ***************************************************************************** - */ -#if !defined(HAVE_DECL_ISNAN) - # define isnan(x) \ - (sizeof (x) == sizeof (long double) ? isnan_ld (x) \ - : sizeof (x) == sizeof (double) ? isnan_d (x) \ - : isnan_f (x)) -static int isnan_f (float x) -{ - return x != x; -} - -static int isnan_d (double x) -{ - return x != x; -} - -static int isnan_ld (long double x) -{ - return x != x; -} -#endif - -#if !defined(HAVE_DECL_ISINF) - # define isinf(x) \ - (sizeof (x) == sizeof (long double) ? isinf_ld (x) \ - : sizeof (x) == sizeof (double) ? isinf_d (x) \ - : isinf_f (x)) - -static int isinf_f (float x) -{ - return isnan (x - x); -} - -static int isinf_d (double x) -{ - return isnan (x - x); -} - -static int isinf_ld (long double x) -{ - return isnan (x - x); -} -#endif - -#if !defined(HAVE_DECL_SIGNBIT) - #include "_signbit.c" - # define signbit(x) \ - (sizeof (x) == sizeof (long double) ? signbit_ld (x) \ - : sizeof (x) == sizeof (double) ? signbit_d (x) \ - : signbit_f (x)) - -static int signbit_f (float x) -{ - return signbit_d((double)x); -} - -static int signbit_ld (long double x) -{ - return signbit_d((double)x); -} -#endif - -/* Define isfinie if needed */ -#if !defined(HAVE_DECL_ISFINITE) -#define isfinite(x) (!(isinf((x)) || isnan((x)))) -#endif - -/* - * if C99 extensions not available then define dummy functions that use the - * double versions for - * - * sin, cos, tan - * sinh, cosh, tanh, - * fabs, floor, ceil, rint, trunc - * sqrt, log10, log, exp, expm1 - * asin, acos, atan, - * asinh, acosh, atanh - * - * hypot, atan2, pow, fmod, modf - * - * We assume the above are always available in their double versions. - */ - -/* - * One value argument function - */ - -/**begin repeat - - #kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,rint,trunc,sqrt,log10,log,exp,expm1,asin,acos,atan,asinh,acosh,atanh)*2# - #KIND=(SIN,COS,TAN,SINH,COSH,TANH,FABS,FLOOR,CEIL,RINT,TRUNC,SQRT,LOG10,LOG,EXP,EXPM1,ASIN,ACOS,ATAN,ASINH,ACOSH,ATANH)*2# - #typ=longdouble*22, float*22# - #c=l*22,f*22# - #C=L*22,F*22# - #TYPE=LONGDOUBLE*22, FLOAT*22# -*/ - -#ifndef HAVE_ at KIND@@C@ - at typ@ @kind@@c@(@typ@ x) -{ - return (@typ@) @kind@((double)x); -} -#endif -/**end repeat**/ - -/* - * Two values arguments function - */ - -/**begin repeat - - #kind=(atan2,hypot,pow,fmod)*2# - #KIND=(ATAN2,HYPOT,POW,FMOD)*2# - #typ=longdouble*4, float*4# - #c=l*4,f*4# - #C=L*4,F*4# - #TYPE=LONGDOUBLE*4,FLOAT*4# -*/ -#ifndef HAVE_ at KIND@@C@ - at typ@ @kind@@c@(@typ@ x, @typ@ y) -{ - return (@typ@) @kind@((double)x, (double) y); -} -#endif -/**end repeat**/ - -/* - * One value - one pointer argument function - */ - -/**begin repeat - #kind=modf*2# - #KIND=MODF*2# - #c=l,f# - #C=L,F# - #typ=longdouble, float# - #TYPE=LONGDOUBLE, FLOAT# -*/ -#ifndef HAVE_ at KIND@@C@ - at typ@ modf at c@(@typ@ x, @typ@ *iptr) -{ - double nx, niptr, y; - nx = (double) x; - y = modf(nx, &niptr); - *iptr = (@typ@) niptr; - return (@typ@) y; -} -#endif -/**end repeat**/ Copied: branches/clean_math_config/numpy/core/src/math_c99.inc.src (from rev 5836, branches/clean_math_config/numpy/core/src/math_c99.c.src) =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.c.src 2008-09-20 08:22:25 UTC (rev 5836) +++ branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 08:47:19 UTC (rev 5837) @@ -0,0 +1,285 @@ +/* + * vim:syntax=c + * A small module to implement missing C99 math capabilities required by numpy + * + * Please keep this independant of python ! + */ + +/* + ***************************************************************************** + ** BASIC MATH FUNCTIONS ** + ***************************************************************************** + */ + +/* Original code by Konrad Hinsen. */ +#ifndef HAVE_EXPM1 +double expm1(double x) +{ + double u = exp(x); + if (u == 1.0) { + return x; + } else if (u-1.0 == -1.0) { + return -1; + } else { + return (u-1.0) * x/log(u); + } +} +#endif + +#ifndef HAVE_LOG1P +double log1p(double x) +{ + double u = 1. + x; + if (u == 1.0) { + return x; + } else { + return log(u) * x / (u-1.); + } +} +#endif + +#ifndef HAVE_HYPOT +double hypot(double x, double y) +{ + double yx; + + x = fabs(x); + y = fabs(y); + if (x < y) { + double temp = x; + x = y; + y = temp; + } + if (x == 0.) + return 0.; + else { + yx = y/x; + return x*sqrt(1.+yx*yx); + } +} +#endif + +#ifndef HAVE_ACOSH +double acosh(double x) +{ + return 2*log(sqrt((x+1.0)/2)+sqrt((x-1.0)/2)); +} +#endif + +#ifndef HAVE_ASINH +double asinh(double xx) +{ + double x, d; + int sign; + if (xx < 0.0) { + sign = -1; + x = -xx; + } + else { + sign = 1; + x = xx; + } + if (x > 1e8) { + d = x; + } else { + d = sqrt(x*x + 1); + } + return sign*log1p(x*(1.0 + x/(d+1))); +} +#endif + +#ifndef HAVE_ATANH +static double atanh(double x) +{ + return 0.5*log1p(2.0*x/(1.0-x)); +} +#endif + +#ifndef HAVE_RINT +double rint(double x) +{ + double y, r; + + y = floor(x); + r = x - y; + + if (r > 0.5) goto rndup; + + /* Round to nearest even */ + if (r==0.5) { + r = y - 2.0*floor(0.5*y); + if (r==1.0) { + rndup: + y+=1.0; + } + } + return y; +} +#endif + +#ifndef HAVE_TRUNC +double trunc(double x) +{ + if (x < 0) { + return ceil(x); + } + else { + return floor(x); + } + +} +#endif + +/* + ***************************************************************************** + ** IEEE 754 FPU HANDLING ** + ***************************************************************************** + */ +#if !defined(HAVE_DECL_ISNAN) + # define isnan(x) \ + (sizeof (x) == sizeof (long double) ? isnan_ld (x) \ + : sizeof (x) == sizeof (double) ? isnan_d (x) \ + : isnan_f (x)) +static int isnan_f (float x) +{ + return x != x; +} + +static int isnan_d (double x) +{ + return x != x; +} + +static int isnan_ld (long double x) +{ + return x != x; +} +#endif + +#if !defined(HAVE_DECL_ISINF) + # define isinf(x) \ + (sizeof (x) == sizeof (long double) ? isinf_ld (x) \ + : sizeof (x) == sizeof (double) ? isinf_d (x) \ + : isinf_f (x)) + +static int isinf_f (float x) +{ + return isnan (x - x); +} + +static int isinf_d (double x) +{ + return isnan (x - x); +} + +static int isinf_ld (long double x) +{ + return isnan (x - x); +} +#endif + +#if !defined(HAVE_DECL_SIGNBIT) + #include "_signbit.c" + # define signbit(x) \ + (sizeof (x) == sizeof (long double) ? signbit_ld (x) \ + : sizeof (x) == sizeof (double) ? signbit_d (x) \ + : signbit_f (x)) + +static int signbit_f (float x) +{ + return signbit_d((double)x); +} + +static int signbit_ld (long double x) +{ + return signbit_d((double)x); +} +#endif + +/* Define isfinie if needed */ +#if !defined(HAVE_DECL_ISFINITE) +#define isfinite(x) (!(isinf((x)) || isnan((x)))) +#endif + +/* + * if C99 extensions not available then define dummy functions that use the + * double versions for + * + * sin, cos, tan + * sinh, cosh, tanh, + * fabs, floor, ceil, rint, trunc + * sqrt, log10, log, exp, expm1 + * asin, acos, atan, + * asinh, acosh, atanh + * + * hypot, atan2, pow, fmod, modf + * + * We assume the above are always available in their double versions. + */ + +/* + * One value argument function + */ + +/**begin repeat + + #kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,rint,trunc,sqrt,log10,log,exp,expm1,asin,acos,atan,asinh,acosh,atanh)*2# + #KIND=(SIN,COS,TAN,SINH,COSH,TANH,FABS,FLOOR,CEIL,RINT,TRUNC,SQRT,LOG10,LOG,EXP,EXPM1,ASIN,ACOS,ATAN,ASINH,ACOSH,ATANH)*2# + #typ=longdouble*22, float*22# + #c=l*22,f*22# + #C=L*22,F*22# + #TYPE=LONGDOUBLE*22, FLOAT*22# +*/ + +#ifndef HAVE_ at KIND@@C@ + at typ@ @kind@@c@(@typ@ x) +{ + return (@typ@) @kind@((double)x); +} +#endif +/**end repeat**/ + +/* + * Two values arguments function + */ + +/**begin repeat + + #kind=(atan2,hypot,pow,fmod)*2# + #KIND=(ATAN2,HYPOT,POW,FMOD)*2# + #typ=longdouble*4, float*4# + #c=l*4,f*4# + #C=L*4,F*4# + #TYPE=LONGDOUBLE*4,FLOAT*4# +*/ +#ifndef HAVE_ at KIND@@C@ + at typ@ @kind@@c@(@typ@ x, @typ@ y) +{ + return (@typ@) @kind@((double)x, (double) y); +} +#endif +/**end repeat**/ + +/* + * One value - one pointer argument function + */ + +/**begin repeat + #kind=modf*2# + #KIND=MODF*2# + #c=l,f# + #C=L,F# + #typ=longdouble, float# + #TYPE=LONGDOUBLE, FLOAT# +*/ +#ifndef HAVE_ at KIND@@C@ + at typ@ modf at c@(@typ@ x, @typ@ *iptr) +{ + double nx, niptr, y; + nx = (double) x; + y = modf(nx, &niptr); + *iptr = (@typ@) niptr; + return (@typ@) y; +} +#endif +/**end repeat**/ Modified: branches/clean_math_config/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-20 08:22:25 UTC (rev 5836) +++ branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-20 08:47:19 UTC (rev 5837) @@ -17,7 +17,7 @@ #include "config.h" #include -#include "math_c99.c" +#include "math_c99.inc" float degreesf(float x) { return x * (float)(180.0/M_PI); From numpy-svn at scipy.org Sat Sep 20 05:48:06 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 04:48:06 -0500 (CDT) Subject: [Numpy-svn] r5838 - branches/clean_math_config/numpy/core Message-ID: <20080920094806.044D039C088@scipy.org> Author: cdavid Date: 2008-09-20 04:48:01 -0500 (Sat, 20 Sep 2008) New Revision: 5838 Modified: branches/clean_math_config/numpy/core/setup.py Log: Test for MSVC, because we will need to special case for this F***** compiler once again. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-20 08:47:19 UTC (rev 5837) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-20 09:48:01 UTC (rev 5838) @@ -63,6 +63,8 @@ def name_to_defsymb(name): return "HAVE_%s" % name.upper() + use_msvc = config.check_decl("_MSC_VER") + # Mandatory functions: if not found, fail the build mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", From numpy-svn at scipy.org Sat Sep 20 06:05:57 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 05:05:57 -0500 (CDT) Subject: [Numpy-svn] r5839 - branches/clean_math_config/numpy/core Message-ID: <20080920100557.AD88C39C088@scipy.org> Author: cdavid Date: 2008-09-20 05:05:52 -0500 (Sat, 20 Sep 2008) New Revision: 5839 Modified: branches/clean_math_config/numpy/core/setup.py Log: Assume mandatory funcs available with MSVC. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-20 09:48:01 UTC (rev 5838) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-20 10:05:52 UTC (rev 5839) @@ -66,9 +66,17 @@ use_msvc = config.check_decl("_MSC_VER") # Mandatory functions: if not found, fail the build - mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", - "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", - "acos", "atan", "fmod", 'modf', 'frexp', 'ldexp'] + if use_msvc: + # MSVC use intrisincs functions when build with e.g. /Ox, and this + # breaks tests. Fixing the tests is not trivial, so we assume the + # intrisincs functions are available. + # Functions which have intrisinces: sin, cos, tan, sin, cosh, tanh, + # fabs, sqrt, log10, log, exp, asin, acos, atan, fmod + mandatory_funcs = ["floor", "ceil", 'modf', 'frexp', 'ldexp'] + else: + mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", + "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", + "acos", "atan", "fmod", 'modf', 'frexp', 'ldexp'] if not check_funcs_once(mandatory_funcs): raise SystemError("One of the required function to build numpy is not" From numpy-svn at scipy.org Sat Sep 20 06:19:04 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 05:19:04 -0500 (CDT) Subject: [Numpy-svn] r5840 - branches/clean_math_config/numpy/core Message-ID: <20080920101904.F18D639C088@scipy.org> Author: cdavid Date: 2008-09-20 05:18:59 -0500 (Sat, 20 Sep 2008) New Revision: 5840 Modified: branches/clean_math_config/numpy/core/setup.py Log: Fix typo in CPP define. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-20 10:05:52 UTC (rev 5839) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-20 10:18:59 UTC (rev 5840) @@ -200,7 +200,7 @@ #endif #ifdef HAVE_EXPF -#define HAVE_FUNCS_FUNCS +#define HAVE_FLOAT_FUNCS #endif """) target_f.close() From numpy-svn at scipy.org Sat Sep 20 06:49:08 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 05:49:08 -0500 (CDT) Subject: [Numpy-svn] r5841 - branches/clean_math_config/numpy/core/src Message-ID: <20080920104908.B11C739C088@scipy.org> Author: cdavid Date: 2008-09-20 05:49:01 -0500 (Sat, 20 Sep 2008) New Revision: 5841 Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src Log: Undef macro when using replacement functions in math_c99 module. Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 10:18:59 UTC (rev 5840) +++ branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 10:49:01 UTC (rev 5841) @@ -215,6 +215,10 @@ * hypot, atan2, pow, fmod, modf * * We assume the above are always available in their double versions. + * + * NOTE: some facilities may be available as macro only instead of functions. + * For simplicity, we define our own functions and undef the macros. We could + * instead test for the macro, but I am lazy to do that for now. */ /* @@ -232,6 +236,9 @@ */ #ifndef HAVE_ at KIND@@C@ +#ifdef @kind@@c@ +#undef @kind@@c@ +#endif @typ@ @kind@@c@(@typ@ x) { return (@typ@) @kind@((double)x); @@ -253,6 +260,9 @@ #TYPE=LONGDOUBLE*4,FLOAT*4# */ #ifndef HAVE_ at KIND@@C@ +#ifdef @kind@@c@ +#undef @kind@@c@ +#endif @typ@ @kind@@c@(@typ@ x, @typ@ y) { return (@typ@) @kind@((double)x, (double) y); @@ -273,6 +283,9 @@ #TYPE=LONGDOUBLE, FLOAT# */ #ifndef HAVE_ at KIND@@C@ +#ifdef modf at c@ +#undef modf at c@ +#endif @typ@ modf at c@(@typ@ x, @typ@ *iptr) { double nx, niptr, y; From numpy-svn at scipy.org Sat Sep 20 06:51:38 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 05:51:38 -0500 (CDT) Subject: [Numpy-svn] r5842 - branches/clean_math_config/numpy/core/src Message-ID: <20080920105138.C034239C088@scipy.org> Author: cdavid Date: 2008-09-20 05:51:35 -0500 (Sat, 20 Sep 2008) New Revision: 5842 Modified: branches/clean_math_config/numpy/core/src/umathmodule.c.src Log: Forgot to define M_PI if not available. Modified: branches/clean_math_config/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-20 10:49:01 UTC (rev 5841) +++ branches/clean_math_config/numpy/core/src/umathmodule.c.src 2008-09-20 10:51:35 UTC (rev 5842) @@ -17,6 +17,9 @@ #include "config.h" #include +#ifndef M_PI +#define M_PI 3.14159265358979323846264338328 +#endif #include "math_c99.inc" float degreesf(float x) { From numpy-svn at scipy.org Sat Sep 20 06:53:30 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 05:53:30 -0500 (CDT) Subject: [Numpy-svn] r5843 - branches/clean_math_config/numpy/core/src Message-ID: <20080920105330.A5E4039C088@scipy.org> Author: cdavid Date: 2008-09-20 05:53:27 -0500 (Sat, 20 Sep 2008) New Revision: 5843 Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src Log: Forgot to define float/long double version of log1p if not available on the platform. Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 10:51:35 UTC (rev 5842) +++ branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 10:53:27 UTC (rev 5843) @@ -227,12 +227,12 @@ /**begin repeat - #kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,rint,trunc,sqrt,log10,log,exp,expm1,asin,acos,atan,asinh,acosh,atanh)*2# - #KIND=(SIN,COS,TAN,SINH,COSH,TANH,FABS,FLOOR,CEIL,RINT,TRUNC,SQRT,LOG10,LOG,EXP,EXPM1,ASIN,ACOS,ATAN,ASINH,ACOSH,ATANH)*2# - #typ=longdouble*22, float*22# - #c=l*22,f*22# - #C=L*22,F*22# - #TYPE=LONGDOUBLE*22, FLOAT*22# + #kind=(sin,cos,tan,sinh,cosh,tanh,fabs,floor,ceil,rint,trunc,sqrt,log10,log,exp,expm1,asin,acos,atan,asinh,acosh,atanh,log1p)*2# + #KIND=(SIN,COS,TAN,SINH,COSH,TANH,FABS,FLOOR,CEIL,RINT,TRUNC,SQRT,LOG10,LOG,EXP,EXPM1,ASIN,ACOS,ATAN,ASINH,ACOSH,ATANH,LOG1P)*2# + #typ=longdouble*23, float*23# + #c=l*23,f*23# + #C=L*23,F*23# + #TYPE=LONGDOUBLE*23, FLOAT*23# */ #ifndef HAVE_ at KIND@@C@ From numpy-svn at scipy.org Sat Sep 20 07:40:24 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 06:40:24 -0500 (CDT) Subject: [Numpy-svn] r5844 - in branches/clean_math_config: . doc numpy numpy/core numpy/distutils/command numpy/f2py numpy/f2py/doc numpy/lib numpy/linalg numpy/ma numpy/ma/tests numpy/oldnumeric numpy/testing Message-ID: <20080920114024.3ABDE39C27D@scipy.org> Author: cdavid Date: 2008-09-20 06:39:20 -0500 (Sat, 20 Sep 2008) New Revision: 5844 Modified: branches/clean_math_config/ branches/clean_math_config/doc/TESTS.txt branches/clean_math_config/numpy/_import_tools.py branches/clean_math_config/numpy/core/records.py branches/clean_math_config/numpy/distutils/command/install.py branches/clean_math_config/numpy/f2py/auxfuncs.py branches/clean_math_config/numpy/f2py/cb_rules.py branches/clean_math_config/numpy/f2py/cfuncs.py branches/clean_math_config/numpy/f2py/common_rules.py branches/clean_math_config/numpy/f2py/crackfortran.py branches/clean_math_config/numpy/f2py/doc/collectinput.py branches/clean_math_config/numpy/f2py/f2py2e.py branches/clean_math_config/numpy/f2py/f2py_testing.py branches/clean_math_config/numpy/f2py/f90mod_rules.py branches/clean_math_config/numpy/f2py/func2subr.py branches/clean_math_config/numpy/f2py/use_rules.py branches/clean_math_config/numpy/lib/index_tricks.py branches/clean_math_config/numpy/lib/twodim_base.py branches/clean_math_config/numpy/lib/utils.py branches/clean_math_config/numpy/linalg/linalg.py branches/clean_math_config/numpy/ma/bench.py branches/clean_math_config/numpy/ma/core.py branches/clean_math_config/numpy/ma/extras.py branches/clean_math_config/numpy/ma/mrecords.py branches/clean_math_config/numpy/ma/tests/test_core.py branches/clean_math_config/numpy/ma/tests/test_extras.py branches/clean_math_config/numpy/ma/tests/test_mrecords.py branches/clean_math_config/numpy/ma/testutils.py branches/clean_math_config/numpy/ma/timer_comparison.py branches/clean_math_config/numpy/oldnumeric/arrayfns.py branches/clean_math_config/numpy/oldnumeric/compat.py branches/clean_math_config/numpy/oldnumeric/mlab.py branches/clean_math_config/numpy/oldnumeric/rng.py branches/clean_math_config/numpy/testing/noseclasses.py Log: Merged revisions 5812-5843 via svnmerge from http://svn.scipy.org/svn/numpy/trunk ........ r5821 | alan.mcintyre | 2008-09-14 03:04:57 +0900 (Sun, 14 Sep 2008) | 3 lines Removed unused imports. Standardize NumPy import as "import numpy as np". ........ r5822 | alan.mcintyre | 2008-09-14 03:10:48 +0900 (Sun, 14 Sep 2008) | 6 lines Rewrapped __all__ definition to conform to PEP8. Standardize NumPy import as "import numpy as np". Removed unused imports. Fixed undefined reference to ndarray (should be np.ndarray). Fixed undefined references to exp (should be math.exp). ........ r5823 | alan.mcintyre | 2008-09-14 03:15:38 +0900 (Sun, 14 Sep 2008) | 3 lines Removed unused imports. Fixed undefined reference to "getpackage" (from nose.util). ........ r5824 | pierregm | 2008-09-14 06:17:09 +0900 (Sun, 14 Sep 2008) | 1 line MaskedArray.__new__ : make sure that we inherit the _hardmask from data (if any) instead of reverting to default. ........ r5826 | alan.mcintyre | 2008-09-18 12:29:56 +0900 (Thu, 18 Sep 2008) | 4 lines Added documentation for doctests and using the skipif and knownfailureif decorators. Fixed indentation on the last sample snippet in the "__init__.py and setup.py" section. ........ r5827 | alan.mcintyre | 2008-09-18 12:33:15 +0900 (Thu, 18 Sep 2008) | 3 lines Rewrapped __all__ to conform with PEP8. Removed unused imports. ........ r5828 | alan.mcintyre | 2008-09-18 12:33:58 +0900 (Thu, 18 Sep 2008) | 2 lines Removed unused imports. ........ r5829 | alan.mcintyre | 2008-09-18 12:45:53 +0900 (Thu, 18 Sep 2008) | 3 lines Removed unused/redundant imports. PEP8 conformance (only one import per line). ........ r5830 | alan.mcintyre | 2008-09-18 12:57:47 +0900 (Thu, 18 Sep 2008) | 2 lines Removed redundant import. ........ r5831 | pierregm | 2008-09-19 02:51:55 +0900 (Fri, 19 Sep 2008) | 1 line median : fixed a bug in _median1D (there shouldn't have been an axis) ........ r5832 | jarrod.millman | 2008-09-19 03:53:53 +0900 (Fri, 19 Sep 2008) | 2 lines ReSTified an URL ........ r5833 | rkern | 2008-09-19 06:48:57 +0900 (Fri, 19 Sep 2008) | 1 line BUG: Override setuptools' install.run() method to correctly allow 'python setup.py install' to work. ........ r5834 | pierregm | 2008-09-19 12:33:40 +0900 (Fri, 19 Sep 2008) | 1 line * fixing view to recognize dtype and type parameters, for consistency with regular ndarrays. ........ r5835 | pierregm | 2008-09-20 04:43:05 +0900 (Sat, 20 Sep 2008) | 8 lines core: * add dtype to the repr of masked arrays w/ flexible type * prevent __getitem__ to return masked on flexible-type masked array * make sure __str__ returns something sensible for flexible dtype w/ masked fields * simplify the count method mrecords: * fixed a pb with fromrecords when the number of fields cannot be determined from the first element. ........ Property changes on: branches/clean_math_config ___________________________________________________________________ Name: svnmerge-integrated - /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5811 + /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5843 Modified: branches/clean_math_config/doc/TESTS.txt =================================================================== --- branches/clean_math_config/doc/TESTS.txt 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/doc/TESTS.txt 2008-09-20 11:39:20 UTC (rev 5844) @@ -58,7 +58,7 @@ run_module_suite() -Note that all classes that are inherited from ``TestCase`` class, are picked up by the test runner. For more detailed information on defining test classes see the official documentation for the [http://docs.python.org/lib/module-unittest.html Python Unit testing framework]. +Note that all classes that are inherited from ``TestCase`` class, are picked up by the test runner. For more detailed information on defining test classes see the official documentation for the `Python Unit testing framework `__. Using test functions with nose ------------------------------ @@ -150,6 +150,19 @@ Note that 'check_even' is not itself a test (no 'test' in the name), but 'test_evens' is a generator that returns a series of tests, using 'check_even', across a range of inputs. Nice. +Doctests +-------- + +Doctests are a convenient way of documenting the behavior a function and allowing that behavior to be tested at the same time. The output of an interactive Python session can be included in the docstring of a function, and the test framework can run the example and compare the actual output to the expected output. + +The doctests can be run by adding the ``doctests`` argument to the ``test()`` call; for example, to run all tests (including doctests) for numpy.lib:: + +>>> import numpy as np +>>> np.lib.test(doctests=True) + +The doctests are run as if they are in a fresh Python instance which has executed ``import numpy as np`` (tests that are part of the SciPy package also have an implicit ``import scipy as sp``). + + ``tests/`` ---------- @@ -188,13 +201,12 @@ >>> import scipy >>> scipy.xxx.test() -Also, when invoking the entire SciPy test suite, your tests will be found and run: +Also, when invoking the entire SciPy test suite, your tests will be found and run:: >>> import scipy >>> scipy.test() # your tests are included and run automatically! - Tips & Tricks ''''''''''''' @@ -230,9 +242,29 @@ In this case, we wanted to test solving a linear algebra problem using matrices of several data types, using ``linalg.solve`` and ``linalg.inv``. The common test cases (for single-precision, double-precision, etc. matrices) are collected in ``LinalgTestCase``. Note that ``LinalgTestCase`` is not descended from ``TestCase``--if it were, then nose would attempt to run ``LinalgTestCase.test_single`` and ``LinalgTestCase.test_double``, which would fail because ``LinalgTestCase`` has no ``do`` method. Since ``TestSolve`` and ``TestInv`` inherit from ``LinalgTestCase`` and ``TestCase``, nose will run ``test_single`` and ``test_double`` for each class. +Known failures & skipping tests +------------------------------- +Sometimes you might want to skip a test or mark it as a known failure, such as when the test suite is being written before the code it's meant to test, or if a test only fails on a particular architecture. The decorators from numpy.testing.dec can be used to do this. +To skip a test, simply use ``skipif``:: + from numpy.testing import * + @dec.skipif(SkipMyTest, "Skipping this test because...") + def test_something(foo): + ... +The test is marked as skipped if ``SkipMyTest`` evaluates to nonzero, and the message in verbose test output is the second argument given to ``skipif``. Similarly, a test can be marked as a known failure by using ``knownfailureif``:: + from numpy.testing import * + + @dec.knownfailureif(MyTestFails, "This test is known to fail because...") + def test_something_else(foo): + ... + +Of course, a test can be unconditionally skipped or marked as a known failure by passing ``True`` as the first argument to ``skipif`` or ``knownfailureif``, respectively. + +A total of the number of skipped and known failing tests is displayed at the end of the test run. Skipped tests are marked as ``'S'`` in the test results (or ``'SKIPPED'`` for ``verbosity > 1``), and known failing tests are marked as ``'K'`` (or ``'KNOWN'`` if ``verbosity > 1``). + + Modified: branches/clean_math_config/numpy/_import_tools.py =================================================================== --- branches/clean_math_config/numpy/_import_tools.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/_import_tools.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -1,7 +1,5 @@ - import os import sys -import imp __all__ = ['PackageLoader'] Modified: branches/clean_math_config/numpy/core/records.py =================================================================== --- branches/clean_math_config/numpy/core/records.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/core/records.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -448,17 +448,23 @@ else: return self.setfield(val, *res) - def view(self, obj): - try: - if issubclass(obj, ndarray): - return ndarray.view(self, obj) - except TypeError: - pass - dtype = sb.dtype(obj) - if dtype.fields is None: - return self.__array__().view(dtype) - return ndarray.view(self, obj) + def view(self, dtype=None, type=None): + if dtype is None: + return ndarray.view(self, type) + elif type is None: + try: + if issubclass(dtype, ndarray): + return ndarray.view(self, dtype) + except TypeError: + pass + dtype = sb.dtype(dtype) + if dtype.fields is None: + return self.__array__().view(dtype) + return ndarray.view(self, dtype) + else: + return ndarray.view(self, dtype, type) + def fromarrays(arrayList, dtype=None, shape=None, formats=None, names=None, titles=None, aligned=False, byteorder=None): """ create a record array from a (flat) list of arrays Modified: branches/clean_math_config/numpy/distutils/command/install.py =================================================================== --- branches/clean_math_config/numpy/distutils/command/install.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/distutils/command/install.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -1,8 +1,10 @@ import sys if 'setuptools' in sys.modules: import setuptools.command.install as old_install_mod + have_setuptools = True else: import distutils.command.install as old_install_mod + have_setuptools = False old_install = old_install_mod.install from distutils.file_util import write_file @@ -12,8 +14,41 @@ old_install.finalize_options(self) self.install_lib = self.install_libbase + def setuptools_run(self): + """ The setuptools version of the .run() method. + + We must pull in the entire code so we can override the level used in the + _getframe() call since we wrap this call by one more level. + """ + # Explicit request for old-style install? Just do it + if self.old_and_unmanageable or self.single_version_externally_managed: + return old_install_mod._install.run(self) + + # Attempt to detect whether we were called from setup() or by another + # command. If we were called by setup(), our caller will be the + # 'run_command' method in 'distutils.dist', and *its* caller will be + # the 'run_commands' method. If we were called any other way, our + # immediate caller *might* be 'run_command', but it won't have been + # called by 'run_commands'. This is slightly kludgy, but seems to + # work. + # + caller = sys._getframe(3) + caller_module = caller.f_globals.get('__name__','') + caller_name = caller.f_code.co_name + + if caller_module != 'distutils.dist' or caller_name!='run_commands': + # We weren't called from the command line or setup(), so we + # should run in backward-compatibility mode to support bdist_* + # commands. + old_install_mod._install.run(self) + else: + self.do_egg_install() + def run(self): - r = old_install.run(self) + if not have_setuptools: + r = old_install.run(self) + else: + r = self.setuptools_run() if self.record: # bdist_rpm fails when INSTALLED_FILES contains # paths with spaces. Such paths must be enclosed Modified: branches/clean_math_config/numpy/f2py/auxfuncs.py =================================================================== --- branches/clean_math_config/numpy/f2py/auxfuncs.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/f2py/auxfuncs.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -20,9 +20,7 @@ import pprint import sys -import time import types -import os import cfuncs Modified: branches/clean_math_config/numpy/f2py/cb_rules.py =================================================================== --- branches/clean_math_config/numpy/f2py/cb_rules.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/f2py/cb_rules.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -21,16 +21,13 @@ import pprint import sys -import time import types -import copy errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint from auxfuncs import * import capi_maps -#from capi_maps import * import cfuncs ################## Rules for callback function ############## Modified: branches/clean_math_config/numpy/f2py/cfuncs.py =================================================================== --- branches/clean_math_config/numpy/f2py/cfuncs.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/f2py/cfuncs.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -19,7 +19,9 @@ import __version__ f2py_version = __version__.version -import types,sys,copy,os +import types +import sys +import copy errmess=sys.stderr.write ##################### Definitions ################## Modified: branches/clean_math_config/numpy/f2py/common_rules.py =================================================================== --- branches/clean_math_config/numpy/f2py/common_rules.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/f2py/common_rules.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -20,16 +20,12 @@ import pprint import sys -import time -import types -import copy errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint from auxfuncs import * import capi_maps -import cfuncs import func2subr from crackfortran import rmbadname ############## Modified: branches/clean_math_config/numpy/f2py/crackfortran.py =================================================================== --- branches/clean_math_config/numpy/f2py/crackfortran.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/f2py/crackfortran.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -15,7 +15,6 @@ __version__ = "$Revision: 1.177 $"[10:-1] import __version__ -import string f2py_version = __version__.version """ Modified: branches/clean_math_config/numpy/f2py/doc/collectinput.py =================================================================== --- branches/clean_math_config/numpy/f2py/doc/collectinput.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/f2py/doc/collectinput.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -23,7 +23,6 @@ stdoutflag=0 import sys -import os import fileinput import re import commands Modified: branches/clean_math_config/numpy/f2py/f2py2e.py =================================================================== --- branches/clean_math_config/numpy/f2py/f2py2e.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/f2py/f2py2e.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -21,7 +21,6 @@ import sys import os import pprint -import shutil import types import re errmess=sys.stderr.write @@ -31,11 +30,8 @@ import crackfortran import rules import cb_rules -import common_rules import auxfuncs import cfuncs -import capi_maps -import func2subr import f90mod_rules outmess = auxfuncs.outmess @@ -395,7 +391,7 @@ """ Do it all in one call! """ - import tempfile,os,shutil + import tempfile i = sys.argv.index('-c') del sys.argv[i] @@ -547,6 +543,7 @@ setup(ext_modules = [ext]) if remove_build_dir and os.path.exists(build_dir): + import shutil outmess('Removing build directory %s\n'%(build_dir)) shutil.rmtree(build_dir) Modified: branches/clean_math_config/numpy/f2py/f2py_testing.py =================================================================== --- branches/clean_math_config/numpy/f2py/f2py_testing.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/f2py/f2py_testing.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -1,4 +1,5 @@ -import os,sys,re,time +import sys +import re from numpy.testing.utils import jiffies, memusage Modified: branches/clean_math_config/numpy/f2py/f90mod_rules.py =================================================================== --- branches/clean_math_config/numpy/f2py/f90mod_rules.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/f2py/f90mod_rules.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -17,11 +17,8 @@ f2py_version='See `f2py -v`' -import copy import pprint import sys -import time -import types errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint @@ -29,7 +26,6 @@ from auxfuncs import * import numpy as np import capi_maps -import cfuncs import rules import func2subr from crackfortran import undo_rmbadname, undo_rmbadname1 Modified: branches/clean_math_config/numpy/f2py/func2subr.py =================================================================== --- branches/clean_math_config/numpy/f2py/func2subr.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/f2py/func2subr.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -20,9 +20,6 @@ import pprint import copy import sys -import time -import types -import copy errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint Modified: branches/clean_math_config/numpy/f2py/use_rules.py =================================================================== --- branches/clean_math_config/numpy/f2py/use_rules.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/f2py/use_rules.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -21,16 +21,11 @@ import pprint import sys -import time -import types -import copy errmess=sys.stderr.write outmess=sys.stdout.write show=pprint.pprint from auxfuncs import * -import capi_maps -import cfuncs ############## usemodule_rules={ Modified: branches/clean_math_config/numpy/lib/index_tricks.py =================================================================== --- branches/clean_math_config/numpy/lib/index_tricks.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/lib/index_tricks.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -7,7 +7,7 @@ import sys import numpy.core.numeric as _nx -from numpy.core.numeric import asarray, ScalarType, array, dtype +from numpy.core.numeric import asarray, ScalarType, array from numpy.core.numerictypes import find_common_type import math Modified: branches/clean_math_config/numpy/lib/twodim_base.py =================================================================== --- branches/clean_math_config/numpy/lib/twodim_base.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/lib/twodim_base.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -6,7 +6,7 @@ 'tril','vander','histogram2d'] from numpy.core.numeric import asanyarray, equal, subtract, arange, \ - zeros, arange, greater_equal, multiply, ones, asarray + zeros, greater_equal, multiply, ones, asarray def fliplr(m): """ Modified: branches/clean_math_config/numpy/lib/utils.py =================================================================== --- branches/clean_math_config/numpy/lib/utils.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/lib/utils.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -4,9 +4,7 @@ import types import re -from numpy.core.numerictypes import obj2sctype, generic, issubclass_, \ - issubsctype, issubdtype -from numpy.core.multiarray import dtype as _dtype +from numpy.core.numerictypes import issubclass_, issubsctype, issubdtype from numpy.core import product, ndarray __all__ = ['issubclass_', 'get_numpy_include', 'issubsctype', Modified: branches/clean_math_config/numpy/linalg/linalg.py =================================================================== --- branches/clean_math_config/numpy/linalg/linalg.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/linalg/linalg.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -9,16 +9,9 @@ zgetrf, dpotrf, zpotrf, dgeqrf, zgeqrf, zungqr, dorgqr. """ -__all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', - 'inv', 'cholesky', - 'eigvals', - 'eigvalsh', 'pinv', - 'det', 'svd', - 'eig', 'eigh','lstsq', 'norm', - 'qr', - 'cond', - 'LinAlgError' - ] +__all__ = ['matrix_power', 'solve', 'tensorsolve', 'tensorinv', 'inv', + 'cholesky', 'eigvals', 'eigvalsh', 'pinv', 'det', 'svd', + 'eig', 'eigh','lstsq', 'norm', 'qr', 'cond', 'LinAlgError'] from numpy.core import array, asarray, zeros, empty, transpose, \ intc, single, double, csingle, cdouble, inexact, complexfloating, \ @@ -27,7 +20,7 @@ isfinite, size from numpy.lib import triu from numpy.linalg import lapack_lite -from numpy.core.defmatrix import matrix_power, matrix +from numpy.core.defmatrix import matrix_power fortran_int = intc Modified: branches/clean_math_config/numpy/ma/bench.py =================================================================== --- branches/clean_math_config/numpy/ma/bench.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/ma/bench.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -6,9 +6,9 @@ #ip = IPython.ipapi.get() #from IPython import ipmagic import numpy -from numpy import ma -from numpy.ma import filled -from numpy.ma.testutils import assert_equal +#from numpy import ma +#from numpy.ma import filled +#from numpy.ma.testutils import assert_equal #####--------------------------------------------------------------------------- Modified: branches/clean_math_config/numpy/ma/core.py =================================================================== --- branches/clean_math_config/numpy/ma/core.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/ma/core.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -57,17 +57,14 @@ 'var', 'where', 'zeros'] -import sys -import types import cPickle import operator import numpy as np -from numpy import ndarray, typecodes, amax, amin, iscomplexobj,\ - bool_, complex_, float_, int_, object_, str_ +from numpy import ndarray, amax, amin, iscomplexobj, bool_, complex_, float_,\ + int_, object_ from numpy import array as narray - import numpy.core.umath as umath import numpy.core.numerictypes as ntypes from numpy import expand_dims as n_expand_dims @@ -1237,7 +1234,7 @@ def __new__(cls, data=None, mask=nomask, dtype=None, copy=False, subok=True, ndmin=0, fill_value=None, - keep_mask=True, hard_mask=False, flag=None, shrink=True, + keep_mask=True, hard_mask=None, flag=None, shrink=True, **options): """Create a new masked array from scratch. @@ -1341,7 +1338,10 @@ if fill_value is not None: _data._fill_value = _check_fill_value(fill_value, _data.dtype) # Process extra options .. - _data._hardmask = hard_mask + if hard_mask is None: + _data._hardmask = getattr(data, '_hardmask', False) + else: + _data._hardmask = hard_mask _data._baseclass = _baseclass return _data # @@ -1479,15 +1479,22 @@ # if getmask(indx) is not nomask: # msg = "Masked arrays must be filled before they can be used as indices!" # raise IndexError, msg - dout = ndarray.__getitem__(self.view(ndarray), indx) + dout = ndarray.__getitem__(ndarray.view(self,ndarray), indx) # We could directly use ndarray.__getitem__ on self... # But then we would have to modify __array_finalize__ to prevent the # mask of being reshaped if it hasn't been set up properly yet... # So it's easier to stick to the current version _mask = self._mask if not getattr(dout,'ndim', False): + # A record ................ + if isinstance(dout, np.void): + mask = _mask[indx] + if mask.view((bool,len(mask.dtype))).any(): + dout = masked_array(dout, mask=mask) + else: + return dout # Just a scalar............ - if _mask is not nomask and _mask[indx]: + elif _mask is not nomask and _mask[indx]: return masked else: # Force dout to MA ........ @@ -1896,7 +1903,15 @@ res = self._data else: if m.shape == (): - if m: + if m.dtype.names: + m = m.view((bool, len(m.dtype))) + if m.any(): + r = np.array(self._data.tolist(), dtype=object) + np.putmask(r, m, f) + return str(tuple(r)) + else: + return str(self._data) + elif m: return str(f) else: return str(self._data) @@ -1933,21 +1948,31 @@ mask = %(mask)s, fill_value=%(fill)s) """ + with_mask_flx = """\ +masked_%(name)s(data = + %(data)s, + mask = + %(mask)s, + fill_value=%(fill)s, + dtype=%(dtype)s) +""" + with_mask1_flx = """\ +masked_%(name)s(data = %(data)s, + mask = %(mask)s, + fill_value=%(fill)s + dtype=%(dtype)s) +""" n = len(self.shape) name = repr(self._data).split('(')[0] - if n <= 1: - return with_mask1 % { - 'name': name, - 'data': str(self), - 'mask': str(self._mask), - 'fill': str(self.fill_value), - } - return with_mask % { - 'name': name, - 'data': str(self), - 'mask': str(self._mask), - 'fill': str(self.fill_value), - } + parameters = dict(name=name, data=str(self), mask=str(self._mask), + fill=str(self.fill_value), dtype=str(self.dtype)) + if self.dtype.names: + if n<= 1: + return with_mask1_flx % parameters + return with_mask_flx % parameters + elif n <= 1: + return with_mask1 % parameters + return with_mask % parameters #............................................ def __add__(self, other): "Add other to self, and return a new masked array." @@ -3509,6 +3534,8 @@ return data def count(a, axis = None): + if isinstance(a, MaskedArray): + return a.count(axis) return masked_array(a, copy=False).count(axis) count.__doc__ = MaskedArray.count.__doc__ Modified: branches/clean_math_config/numpy/ma/extras.py =================================================================== --- branches/clean_math_config/numpy/ma/extras.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/ma/extras.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -415,7 +415,7 @@ """ def _median1D(data): - counts = filled(count(data, axis),0) + counts = filled(count(data),0) (idx, rmd) = divmod(counts, 2) if rmd: choice = slice(idx, idx+1) Modified: branches/clean_math_config/numpy/ma/mrecords.py =================================================================== --- branches/clean_math_config/numpy/ma/mrecords.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/ma/mrecords.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -16,23 +16,21 @@ __author__ = "Pierre GF Gerard-Marchant" import sys -import types import numpy as np -from numpy import bool_, complex_, float_, int_, str_, object_, dtype, \ - chararray, ndarray, recarray, record, array as narray +from numpy import bool_, dtype, \ + ndarray, recarray, array as narray import numpy.core.numerictypes as ntypes -from numpy.core.records import find_duplicate, format_parser from numpy.core.records import fromarrays as recfromarrays, \ - fromrecords as recfromrecords + fromrecords as recfromrecords _byteorderconv = np.core.records._byteorderconv _typestr = ntypes._typestr import numpy.ma as ma from numpy.ma import MAError, MaskedArray, masked, nomask, masked_array,\ - make_mask, mask_or, getdata, getmask, getmaskarray, filled, \ - default_fill_value, masked_print_option + getdata, getmaskarray, filled + _check_fill_value = ma.core._check_fill_value import warnings @@ -153,10 +151,9 @@ return self #...................................................... def __array_finalize__(self,obj): - MaskedArray._update_from(self,obj) # Make sure we have a _fieldmask by default .. - _fieldmask = getattr(obj, '_fieldmask', None) - if _fieldmask is None: + _mask = getattr(obj, '_mask', None) + if _mask is None: objmask = getattr(obj, '_mask', nomask) _dtype = ndarray.__getattribute__(self,'dtype') if objmask is nomask: @@ -165,15 +162,15 @@ mdescr = ma.make_mask_descr(_dtype) _mask = narray([tuple([m]*len(mdescr)) for m in objmask], dtype=mdescr).view(recarray) - else: - _mask = _fieldmask # Update some of the attributes - _locdict = self.__dict__ - if _locdict['_baseclass'] == ndarray: - _locdict['_baseclass'] = recarray - _locdict.update(_mask=_mask, _fieldmask=_mask) + _dict = self.__dict__ + _dict.update(_mask=_mask, _fieldmask=_mask) + self._update_from(obj) + if _dict['_baseclass'] == ndarray: + _dict['_baseclass'] = recarray return + def _getdata(self): "Returns the data as a recarray." return ndarray.view(self,recarray) @@ -250,7 +247,6 @@ # Get the list of names ...... fielddict = ndarray.__getattribute__(self,'dtype').fields or {} # Check the attribute -##### _localdict = self.__dict__ if attr not in fielddict: return ret if newattr: # We just added this one @@ -284,8 +280,8 @@ """Returns all the fields sharing the same fieldname base. The fieldname base is either `_data` or `_mask`.""" _localdict = self.__dict__ - _mask = _localdict['_fieldmask'] - _data = self._data + _mask = ndarray.__getattribute__(self,'_mask') + _data = ndarray.view(self, _localdict['_baseclass']) # We want a field ........ if isinstance(indx, basestring): #!!!: Make sure _sharedmask is True to propagate back to _fieldmask @@ -473,7 +469,7 @@ dtype=dtype, shape=shape, formats=formats, names=names, titles=titles, aligned=aligned, byteorder=byteorder).view(mrecarray) - _array._fieldmask.flat = zip(*masklist) + _array._mask.flat = zip(*masklist) if fill_value is not None: _array.fill_value = fill_value return _array @@ -507,13 +503,17 @@ mask : {nomask, sequence}, optional. External mask to apply on the data. -*Notes*: + Notes + ----- Lists of tuples should be preferred over lists of lists for faster processing. """ # Grab the initial _fieldmask, if needed: _fieldmask = getattr(reclist, '_fieldmask', None) # Get the list of records..... - nfields = len(reclist[0]) + try: + nfields = len(reclist[0]) + except TypeError: + nfields = len(reclist[0].dtype) if isinstance(reclist, ndarray): # Make sure we don't have some hidden mask if isinstance(reclist,MaskedArray): @@ -656,7 +656,7 @@ set to 'fi', where `i` is the number of existing fields. """ _data = mrecord._data - _mask = mrecord._fieldmask + _mask = mrecord._mask if newfieldname is None or newfieldname in reserved_fields: newfieldname = 'f%i' % len(_data.dtype) newfield = ma.array(newfield) Modified: branches/clean_math_config/numpy/ma/tests/test_core.py =================================================================== --- branches/clean_math_config/numpy/ma/tests/test_core.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/ma/tests/test_core.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -173,10 +173,12 @@ def test_asarray(self): (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d xm.fill_value = -9999 + xm._hardmask = True xmm = asarray(xm) assert_equal(xmm._data, xm._data) assert_equal(xmm._mask, xm._mask) assert_equal(xmm.fill_value, xm.fill_value) + assert_equal(xmm._hardmask, xm._hardmask) def test_fix_invalid(self): "Checks fix_invalid." @@ -2370,8 +2372,24 @@ test = a.view((float,2), np.matrix) assert_equal(test, data) assert(isinstance(test, np.matrix)) + # + def test_getitem(self): + ndtype = [('a',float), ('b',float)] + a = array(zip(np.random.rand(10),np.arange(10)), dtype=ndtype) + a.mask = np.array(zip([0,0,0,0,0,0,0,0,1,1], + [1,0,0,0,0,0,0,0,1,0]), + dtype=[('a',bool),('b',bool)]) + # No mask + assert(isinstance(a[1], np.void)) + # One element masked + assert(isinstance(a[0], MaskedArray)) + assert_equal_records(a[0]._data, a._data[0]) + assert_equal_records(a[0]._mask, a._mask[0]) + # All element masked + assert(isinstance(a[-2], MaskedArray)) + assert_equal_records(a[-2]._data, a._data[-2]) + assert_equal_records(a[-2]._mask, a._mask[-2]) - ############################################################################### #------------------------------------------------------------------------------ if __name__ == "__main__": Modified: branches/clean_math_config/numpy/ma/tests/test_extras.py =================================================================== --- branches/clean_math_config/numpy/ma/tests/test_extras.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/ma/tests/test_extras.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -11,7 +11,7 @@ __revision__ = "$Revision: 3473 $" __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' -import numpy +import numpy as np from numpy.testing import TestCase, run_module_suite from numpy.ma.testutils import * from numpy.ma.core import * @@ -332,25 +332,36 @@ def test_2d(self): "Tests median w/ 2D" (n,p) = (101,30) - x = masked_array(numpy.linspace(-1.,1.,n),) + x = masked_array(np.linspace(-1.,1.,n),) x[:10] = x[-10:] = masked - z = masked_array(numpy.empty((n,p), dtype=numpy.float_)) + z = masked_array(np.empty((n,p), dtype=float)) z[:,0] = x[:] - idx = numpy.arange(len(x)) + idx = np.arange(len(x)) for i in range(1,p): - numpy.random.shuffle(idx) + np.random.shuffle(idx) z[:,i] = x[idx] assert_equal(median(z[:,0]), 0) - assert_equal(median(z), numpy.zeros((p,))) + assert_equal(median(z), 0) + assert_equal(median(z, axis=0), np.zeros(p)) + assert_equal(median(z.T, axis=1), np.zeros(p)) # + def test_2d_waxis(self): + "Tests median w/ 2D arrays and different axis." + x = masked_array(np.arange(30).reshape(10,3)) + x[:3] = x[-3:] = masked + assert_equal(median(x), 14.5) + assert_equal(median(x, axis=0), [13.5,14.5,15.5]) + assert_equal(median(x,axis=1), [0,0,0,10,13,16,19,0,0,0]) + assert_equal(median(x,axis=1).mask, [1,1,1,0,0,0,0,1,1,1]) + # def test_3d(self): "Tests median w/ 3D" - x = numpy.ma.arange(24).reshape(3,4,2) + x = np.ma.arange(24).reshape(3,4,2) x[x%3==0] = masked assert_equal(median(x,0), [[12,9],[6,15],[12,9],[18,15]]) x.shape = (4,3,2) assert_equal(median(x,0),[[99,10],[11,99],[13,14]]) - x = numpy.ma.arange(24).reshape(4,3,2) + x = np.ma.arange(24).reshape(4,3,2) x[x%5==0] = masked assert_equal(median(x,0), [[12,10],[8,9],[16,17]]) @@ -483,9 +494,9 @@ def test_polyfit(self): "Tests polyfit" # On ndarrays - x = numpy.random.rand(10) - y = numpy.random.rand(20).reshape(-1,2) - assert_almost_equal(polyfit(x,y,3),numpy.polyfit(x,y,3)) + x = np.random.rand(10) + y = np.random.rand(20).reshape(-1,2) + assert_almost_equal(polyfit(x,y,3),np.polyfit(x,y,3)) # ON 1D maskedarrays x = x.view(MaskedArray) x[0] = masked @@ -493,17 +504,17 @@ y[0,0] = y[-1,-1] = masked # (C,R,K,S,D) = polyfit(x,y[:,0],3,full=True) - (c,r,k,s,d) = numpy.polyfit(x[1:], y[1:,0].compressed(), 3, full=True) + (c,r,k,s,d) = np.polyfit(x[1:], y[1:,0].compressed(), 3, full=True) for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)): assert_almost_equal(a, a_) # (C,R,K,S,D) = polyfit(x,y[:,-1],3,full=True) - (c,r,k,s,d) = numpy.polyfit(x[1:-1], y[1:-1,-1], 3, full=True) + (c,r,k,s,d) = np.polyfit(x[1:-1], y[1:-1,-1], 3, full=True) for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)): assert_almost_equal(a, a_) # (C,R,K,S,D) = polyfit(x,y,3,full=True) - (c,r,k,s,d) = numpy.polyfit(x[1:-1], y[1:-1,:], 3, full=True) + (c,r,k,s,d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True) for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)): assert_almost_equal(a, a_) Modified: branches/clean_math_config/numpy/ma/tests/test_mrecords.py =================================================================== --- branches/clean_math_config/numpy/ma/tests/test_mrecords.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/ma/tests/test_mrecords.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -8,23 +8,19 @@ __revision__ = "$Revision: 3473 $" __date__ = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $' -import types - import numpy as np from numpy import recarray from numpy.core.records import fromrecords as recfromrecords, \ - fromarrays as recfromarrays + fromarrays as recfromarrays import numpy.ma.testutils from numpy.ma.testutils import * import numpy.ma as ma -from numpy.ma import masked, nomask, getdata, getmaskarray +from numpy.ma import masked, nomask -import numpy.ma.mrecords -reload(numpy.ma.mrecords) -from numpy.ma.mrecords import MaskedRecords, mrecarray,\ - fromarrays, fromtextfile, fromrecords, addfield +from numpy.ma.mrecords import MaskedRecords, mrecarray, fromarrays, \ + fromtextfile, fromrecords, addfield #.............................................................................. class TestMRecords(TestCase): @@ -207,8 +203,8 @@ # def test_set_elements(self): base = self.base.copy() - mbase = base.view(mrecarray) # Set an element to mask ..................... + mbase = base.view(mrecarray).copy() mbase[-2] = masked assert_equal(mbase._fieldmask.tolist(), np.array([(0,0,0),(1,1,1),(0,0,0),(1,1,1),(1,1,1)], @@ -432,7 +428,6 @@ 'strings',4,-1e-10,,,1 """ import os - from datetime import datetime import tempfile (tmp_fd,tmp_fl) = tempfile.mkstemp() os.write(tmp_fd, fcontent) Modified: branches/clean_math_config/numpy/ma/testutils.py =================================================================== --- branches/clean_math_config/numpy/ma/testutils.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/ma/testutils.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -16,12 +16,10 @@ from numpy import ndarray, float_ import numpy.core.umath as umath from numpy.testing import * -from numpy.testing.utils import build_err_msg, rand import numpy.testing.utils as utils -import core -from core import mask_or, getmask, getmaskarray, masked_array, nomask, masked -from core import fix_invalid, filled, equal, less +from core import mask_or, getmask, masked_array, nomask, masked, filled, \ + equal, less #------------------------------------------------------------------------------ def approx (a, b, fill_value=True, rtol=1.e-5, atol=1.e-8): Modified: branches/clean_math_config/numpy/ma/timer_comparison.py =================================================================== --- branches/clean_math_config/numpy/ma/timer_comparison.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/ma/timer_comparison.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -1,17 +1,15 @@ - import timeit -import numpy -from numpy import int_, float_, bool_ -import numpy.core.fromnumeric as fromnumeric +import numpy as np +from numpy import float_ +import np.core.fromnumeric as fromnumeric -from numpy.testing.utils import build_err_msg, rand +from np.testing.utils import build_err_msg +np.seterr(all='ignore') -numpy.seterr(all='ignore') +pi = np.pi -pi = numpy.pi - class moduletester: #----------------------------------- def __init__(self, module): @@ -61,15 +59,15 @@ y = self.filled(self.masked_array(yf, mask=m), fill_value) if (x.dtype.char != "O"): x = x.astype(float_) - if isinstance(x, numpy.ndarray) and x.size > 1: - x[numpy.isnan(x)] = 0 - elif numpy.isnan(x): + if isinstance(x, np.ndarray) and x.size > 1: + x[np.isnan(x)] = 0 + elif np.isnan(x): x = 0 if (y.dtype.char != "O"): y = y.astype(float_) - if isinstance(y, numpy.ndarray) and y.size > 1: - y[numpy.isnan(y)] = 0 - elif numpy.isnan(y): + if isinstance(y, np.ndarray) and y.size > 1: + y[np.isnan(y)] = 0 + elif np.isnan(y): y = 0 try: cond = (x.shape==() or y.shape==()) or x.shape == y.shape @@ -110,23 +108,23 @@ #---------------------------------- def test_0(self): "Tests creation" - x = numpy.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) + x = np.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] xm = self.masked_array(x, mask=m) xm[0] #---------------------------------- def test_1(self): "Tests creation" - x = numpy.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) - y = numpy.array([5.,0.,3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) + x = np.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.]) + y = np.array([5.,0.,3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]) a10 = 10. m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0] m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0 ,0, 1] xm = self.masked_array(x, mask=m1) ym = self.masked_array(y, mask=m2) - z = numpy.array([-.5, 0., .5, .8]) + z = np.array([-.5, 0., .5, .8]) zm = self.masked_array(z, mask=[0,1,0,0]) - xf = numpy.where(m1, 1.e+20, x) + xf = np.where(m1, 1.e+20, x) xm.set_fill_value(1.e+20) #..... assert((xm-ym).filled(0).any()) @@ -146,13 +144,13 @@ #---------------------------------- def test_2(self): "Tests conversions and indexing" - x1 = numpy.array([1,2,4,3]) + x1 = np.array([1,2,4,3]) x2 = self.array(x1, mask=[1,0,0,0]) x3 = self.array(x1, mask=[0,1,0,1]) x4 = self.array(x1) # test conversion to strings junk, garbage = str(x2), repr(x2) -# assert_equal(numpy.sort(x1), self.sort(x2, fill_value=0)) +# assert_equal(np.sort(x1), self.sort(x2, fill_value=0)) # tests of indexing assert type(x2[1]) is type(x1[1]) assert x1[1] == x2[1] @@ -178,12 +176,12 @@ x4[:] = self.masked_array([1,2,3,4],[0,1,1,0]) # assert self.allequal(self.getmask(x4), self.array([0,1,1,0])) # assert self.allequal(x4, self.array([1,2,3,4])) - x1 = numpy.arange(5)*1.0 + x1 = np.arange(5)*1.0 x2 = self.masked_values(x1, 3.0) # assert self.allequal(x1,x2) # assert self.allequal(self.array([0,0,0,1,0], self.MaskType), x2.mask) x1 = self.array([1,'hello',2,3],object) - x2 = numpy.array([1,'hello',2,3],object) + x2 = np.array([1,'hello',2,3],object) s1 = x1[1] s2 = x2[1] assert x1[1:1].shape == (0,) @@ -216,15 +214,15 @@ def test_4(self): "Test of take, transpose, inner, outer products" x = self.arange(24) - y = numpy.arange(24) + y = np.arange(24) x[5:6] = self.masked x = x.reshape(2,3,4) y = y.reshape(2,3,4) - assert self.allequal(numpy.transpose(y,(2,0,1)), self.transpose(x,(2,0,1))) - assert self.allequal(numpy.take(y, (2,0,1), 1), self.take(x, (2,0,1), 1)) - assert self.allequal(numpy.inner(self.filled(x,0), self.filled(y,0)), + assert self.allequal(np.transpose(y,(2,0,1)), self.transpose(x,(2,0,1))) + assert self.allequal(np.take(y, (2,0,1), 1), self.take(x, (2,0,1), 1)) + assert self.allequal(np.inner(self.filled(x,0), self.filled(y,0)), self.inner(x, y)) - assert self.allequal(numpy.outer(self.filled(x,0), self.filled(y,0)), + assert self.allequal(np.outer(self.filled(x,0), self.filled(y,0)), self.outer(x, y)) y = self.array(['abc', 1, 'def', 2, 3], object) y[2] = self.masked @@ -396,8 +394,8 @@ self.assert_array_equal(self.average(x, axis=0), 2.5) self.assert_array_equal(self.average(x, axis=0, weights=w1), 2.5) y = self.array([self.arange(6), 2.0*self.arange(6)]) - self.assert_array_equal(self.average(y, None), numpy.add.reduce(numpy.arange(6))*3./12.) - self.assert_array_equal(self.average(y, axis=0), numpy.arange(6) * 3./2.) + self.assert_array_equal(self.average(y, None), np.add.reduce(np.arange(6))*3./12.) + self.assert_array_equal(self.average(y, axis=0), np.arange(6) * 3./2.) self.assert_array_equal(self.average(y, axis=1), [self.average(x,axis=0), self.average(x,axis=0) * 2.0]) self.assert_array_equal(self.average(y, None, weights=w2), 20./6.) self.assert_array_equal(self.average(y, axis=0, weights=w2), [0.,1.,2.,3.,4.,10.]) @@ -420,7 +418,7 @@ #------------------------ def test_A(self): x = self.arange(24) - y = numpy.arange(24) + y = np.arange(24) x[5:6] = self.masked x = x.reshape(2,3,4) @@ -431,10 +429,10 @@ setup_base = "from __main__ import moduletester \n"\ "import numpy\n" \ "tester = moduletester(module)\n" -# setup_new = "import numpy.ma.core_ini as module\n"+setup_base - setup_cur = "import numpy.ma.core as module\n"+setup_base -# setup_alt = "import numpy.ma.core_alt as module\n"+setup_base -# setup_tmp = "import numpy.ma.core_tmp as module\n"+setup_base +# setup_new = "import np.ma.core_ini as module\n"+setup_base + setup_cur = "import np.ma.core as module\n"+setup_base +# setup_alt = "import np.ma.core_alt as module\n"+setup_base +# setup_tmp = "import np.ma.core_tmp as module\n"+setup_base (nrepeat, nloop) = (10, 10) @@ -445,10 +443,10 @@ cur = timeit.Timer(func, setup_cur).repeat(nrepeat, nloop*10) # alt = timeit.Timer(func, setup_alt).repeat(nrepeat, nloop*10) # tmp = timeit.Timer(func, setup_tmp).repeat(nrepeat, nloop*10) -# new = numpy.sort(new) - cur = numpy.sort(cur) -# alt = numpy.sort(alt) -# tmp = numpy.sort(tmp) +# new = np.sort(new) + cur = np.sort(cur) +# alt = np.sort(alt) +# tmp = np.sort(tmp) print "#%i" % i +50*'.' print eval("moduletester.test_%i.__doc__" % i) # print "core_ini : %.3f - %.3f" % (new[0], new[1]) Modified: branches/clean_math_config/numpy/oldnumeric/arrayfns.py =================================================================== --- branches/clean_math_config/numpy/oldnumeric/arrayfns.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/oldnumeric/arrayfns.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -1,10 +1,11 @@ """Backward compatible with arrayfns from Numeric """ -__all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask', 'histogram', 'index_sort', - 'interp', 'nz', 'reverse', 'span', 'to_corners', 'zmin_zmax'] +__all__ = ['array_set', 'construct3', 'digitize', 'error', 'find_mask', + 'histogram', 'index_sort', 'interp', 'nz', 'reverse', 'span', + 'to_corners', 'zmin_zmax'] -import numpy as nx +import numpy as np from numpy import asarray class error(Exception): @@ -14,7 +15,7 @@ indices = asarray(indices) if indices.ndim != 1: raise ValueError, "index array must be 1-d" - if not isinstance(vals1, ndarray): + if not isinstance(vals1, np.ndarray): raise TypeError, "vals1 must be an ndarray" vals1 = asarray(vals1) vals2 = asarray(vals2) @@ -31,7 +32,7 @@ def interp(y, x, z, typ=None): """y(z) interpolated by treating y(x) as piecewise function """ - res = numpy.interp(z, x, y) + res = np.interp(z, x, y) if typ is None or typ == 'd': return res if typ == 'f': @@ -40,17 +41,17 @@ raise error, "incompatible typecode" def nz(x): - x = asarray(x,dtype=nx.ubyte) + x = asarray(x,dtype=np.ubyte) if x.ndim != 1: raise TypeError, "intput must have 1 dimension." - indxs = nx.flatnonzero(x != 0) + indxs = np.flatnonzero(x != 0) return indxs[-1].item()+1 def reverse(x, n): x = asarray(x,dtype='d') if x.ndim != 2: raise ValueError, "input must be 2-d" - y = nx.empty_like(x) + y = np.empty_like(x) if n == 0: y[...] = x[::-1,:] elif n == 1: @@ -58,11 +59,11 @@ return y def span(lo, hi, num, d2=0): - x = linspace(lo, hi, num) + x = np.linspace(lo, hi, num) if d2 <= 0: return x else: - ret = empty((d2,num),x.dtype) + ret = np.empty((d2,num),x.dtype) ret[...] = x return ret @@ -71,15 +72,15 @@ ireg = asarray(ireg, dtype=int) if z.shape != ireg.shape or z.ndim != 2: raise ValueError, "z and ireg must be the same shape and 2-d" - ix, iy = nx.nonzero(ireg) + ix, iy = np.nonzero(ireg) # Now, add more indices x1m = ix - 1 y1m = iy-1 i1 = x1m>=0 i2 = y1m>=0 i3 = i1 & i2 - nix = nx.r_[ix, x1m[i1], x1m[i1], ix[i2] ] - niy = nx.r_[iy, iy[i1], y1m[i3], y1m[i2]] + nix = np.r_[ix, x1m[i1], x1m[i1], ix[i2] ] + niy = np.r_[iy, iy[i1], y1m[i3], y1m[i2]] # remove any negative indices zres = z[nix,niy] return zres.min().item(), zres.max().item() Modified: branches/clean_math_config/numpy/oldnumeric/compat.py =================================================================== --- branches/clean_math_config/numpy/oldnumeric/compat.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/oldnumeric/compat.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -12,7 +12,7 @@ import numpy.core.multiarray as multiarray import numpy.core.umath as um -from numpy.core.numeric import array, correlate +from numpy.core.numeric import array import functions import sys Modified: branches/clean_math_config/numpy/oldnumeric/mlab.py =================================================================== --- branches/clean_math_config/numpy/oldnumeric/mlab.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/oldnumeric/mlab.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -1,6 +1,10 @@ # This module is for compatibility only. All functions are defined elsewhere. -__all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', 'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc', 'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean'] +__all__ = ['rand', 'tril', 'trapz', 'hanning', 'rot90', 'triu', 'diff', 'angle', + 'roots', 'ptp', 'kaiser', 'randn', 'cumprod', 'diag', 'msort', + 'LinearAlgebra', 'RandomArray', 'prod', 'std', 'hamming', 'flipud', + 'max', 'blackman', 'corrcoef', 'bartlett', 'eye', 'squeeze', 'sinc', + 'tri', 'cov', 'svd', 'min', 'median', 'fliplr', 'eig', 'mean'] import numpy.oldnumeric.linear_algebra as LinearAlgebra import numpy.oldnumeric.random_array as RandomArray @@ -12,7 +16,7 @@ from numpy.linalg import eig, svd from numpy.random import rand, randn -import numpy as nn +import numpy as np from typeconv import convtypecode @@ -22,7 +26,7 @@ """ dtype = convtypecode(typecode, dtype) if M is None: M = N - m = nn.equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) + m = np.equal(np.subtract.outer(np.arange(N), np.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) @@ -32,7 +36,7 @@ """ dtype = convtypecode(typecode, dtype) if M is None: M = N - m = nn.greater_equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k) + m = np.greater_equal(np.subtract.outer(np.arange(N), np.arange(M)),-k) if m.dtype != dtype: return m.astype(dtype) Modified: branches/clean_math_config/numpy/oldnumeric/rng.py =================================================================== --- branches/clean_math_config/numpy/oldnumeric/rng.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/oldnumeric/rng.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -4,9 +4,9 @@ # It is for backwards compatibility only. -__all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution','NormalDistribution', - 'UniformDistribution', 'error', 'default_distribution', 'random_sample', 'ranf', - 'standard_generator'] +__all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution', + 'NormalDistribution', 'UniformDistribution', 'error', 'ranf', + 'default_distribution', 'random_sample', 'standard_generator'] import numpy.random.mtrand as mt import math @@ -44,7 +44,7 @@ return 0.0 else: lambda_ = self._args[0] - return lambda_*exp(-lambda_*x) + return lambda_*math.exp(-lambda_*x) class LogNormalDistribution(Distribution): def __init__(self, m, s): @@ -61,7 +61,7 @@ def density(x): m,s = self._args y = (math.log(x)-self._mn)/self._sn - return self._fac*exp(-0.5*y*y)/x + return self._fac*math.exp(-0.5*y*y)/x class NormalDistribution(Distribution): @@ -76,7 +76,7 @@ def density(x): m,s = self._args y = (x-m)/s - return self._fac*exp(-0.5*y*y) + return self._fac*math.exp(-0.5*y*y) class UniformDistribution(Distribution): def __init__(self, a, b): Modified: branches/clean_math_config/numpy/testing/noseclasses.py =================================================================== --- branches/clean_math_config/numpy/testing/noseclasses.py 2008-09-20 10:53:27 UTC (rev 5843) +++ branches/clean_math_config/numpy/testing/noseclasses.py 2008-09-20 11:39:20 UTC (rev 5844) @@ -9,7 +9,7 @@ from nose.plugins import doctests as npd from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin from nose.plugins.base import Plugin -from nose.util import src, tolist +from nose.util import src, getpackage import numpy from nosetester import get_package_name import inspect @@ -79,10 +79,11 @@ # doctests in extension modules. # Local shorthands - from inspect import isroutine, isclass, ismodule + from inspect import isroutine, isclass, ismodule, isfunction, \ + ismethod # Look for tests in a module's contained objects. - if inspect.ismodule(obj) and self._recurse: + if ismodule(obj) and self._recurse: for valname, val in obj.__dict__.items(): valname1 = '%s.%s' % (name, valname) if ( (isroutine(val) or isclass(val)) @@ -93,7 +94,7 @@ # Look for tests in a class's contained objects. - if inspect.isclass(obj) and self._recurse: + if isclass(obj) and self._recurse: #print 'RECURSE into class:',obj # dbg for valname, val in obj.__dict__.items(): #valname1 = '%s.%s' % (name, valname) # dbg @@ -105,9 +106,8 @@ val = getattr(obj, valname).im_func # Recurse to methods, properties, and nested classes. - if ((inspect.isfunction(val) or inspect.isclass(val) or - inspect.ismethod(val) or - isinstance(val, property)) and + if ((isfunction(val) or isclass(val) or + ismethod(val) or isinstance(val, property)) and self._from_module(module, val)): valname = '%s.%s' % (name, valname) self._find(tests, val, valname, module, source_lines, @@ -175,7 +175,6 @@ def configure(self, options, config): Plugin.configure(self, options, config) self.doctest_tests = True -# self.extension = tolist(options.doctestExtension) self.finder = NumpyDocTestFinder() self.parser = doctest.DocTestParser() From numpy-svn at scipy.org Sat Sep 20 11:58:48 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 10:58:48 -0500 (CDT) Subject: [Numpy-svn] r5845 - branches/clean_math_config/numpy/core/include/numpy Message-ID: <20080920155848.C077739C088@scipy.org> Author: cdavid Date: 2008-09-20 10:58:44 -0500 (Sat, 20 Sep 2008) New Revision: 5845 Modified: branches/clean_math_config/numpy/core/include/numpy/ufuncobject.h Log: Remove redundant definition of isnan and co in ufuncobject.h Modified: branches/clean_math_config/numpy/core/include/numpy/ufuncobject.h =================================================================== --- branches/clean_math_config/numpy/core/include/numpy/ufuncobject.h 2008-09-20 11:39:20 UTC (rev 5844) +++ branches/clean_math_config/numpy/core/include/numpy/ufuncobject.h 2008-09-20 15:58:44 UTC (rev 5845) @@ -263,11 +263,6 @@ | ((SW_INVALID & fpstatus) ? UFUNC_FPE_INVALID : 0); \ } -#define isnan(x) (_isnan((double)(x))) -#define isinf(x) ((_fpclass((double)(x)) == _FPCLASS_PINF) || \ - (_fpclass((double)(x)) == _FPCLASS_NINF)) -#define isfinite(x) (_finite((double) x)) - /* Solaris --------------------------------------------------------*/ /* --------ignoring SunOS ieee_flags approach, someone else can ** deal with that! */ From numpy-svn at scipy.org Sat Sep 20 12:00:13 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 11:00:13 -0500 (CDT) Subject: [Numpy-svn] r5846 - branches/clean_math_config/numpy/core/src Message-ID: <20080920160013.B862E39C088@scipy.org> Author: cdavid Date: 2008-09-20 11:00:09 -0500 (Sat, 20 Sep 2008) New Revision: 5846 Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src Log: Use a single macro for isnan replacement. Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 15:58:44 UTC (rev 5845) +++ branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:00:09 UTC (rev 5846) @@ -136,24 +136,7 @@ ***************************************************************************** */ #if !defined(HAVE_DECL_ISNAN) - # define isnan(x) \ - (sizeof (x) == sizeof (long double) ? isnan_ld (x) \ - : sizeof (x) == sizeof (double) ? isnan_d (x) \ - : isnan_f (x)) -static int isnan_f (float x) -{ - return x != x; -} - -static int isnan_d (double x) -{ - return x != x; -} - -static int isnan_ld (long double x) -{ - return x != x; -} + # define isnan(x) ((x) != (x)) #endif #if !defined(HAVE_DECL_ISINF) From numpy-svn at scipy.org Sat Sep 20 12:01:25 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 11:01:25 -0500 (CDT) Subject: [Numpy-svn] r5847 - branches/clean_math_config/numpy/core/src Message-ID: <20080920160125.E5A4D39C088@scipy.org> Author: cdavid Date: 2008-09-20 11:01:22 -0500 (Sat, 20 Sep 2008) New Revision: 5847 Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src Log: Use a single macro for isinf replacement. Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:00:09 UTC (rev 5846) +++ branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:01:22 UTC (rev 5847) @@ -140,25 +140,7 @@ #endif #if !defined(HAVE_DECL_ISINF) - # define isinf(x) \ - (sizeof (x) == sizeof (long double) ? isinf_ld (x) \ - : sizeof (x) == sizeof (double) ? isinf_d (x) \ - : isinf_f (x)) - -static int isinf_f (float x) -{ - return isnan (x - x); -} - -static int isinf_d (double x) -{ - return isnan (x - x); -} - -static int isinf_ld (long double x) -{ - return isnan (x - x); -} + # define isinf(x) isnan((x) - (x)) #endif #if !defined(HAVE_DECL_SIGNBIT) From numpy-svn at scipy.org Sat Sep 20 12:10:57 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 11:10:57 -0500 (CDT) Subject: [Numpy-svn] r5848 - branches/clean_math_config/numpy/core/src Message-ID: <20080920161057.A188F39C088@scipy.org> Author: cdavid Date: 2008-09-20 11:10:53 -0500 (Sat, 20 Sep 2008) New Revision: 5848 Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src Log: Move isfinite macro with isinf and isnan. Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:01:22 UTC (rev 5847) +++ branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:10:53 UTC (rev 5848) @@ -143,6 +143,11 @@ # define isinf(x) isnan((x) - (x)) #endif +/* Define isfinie if needed */ +#if !defined(HAVE_DECL_ISFINITE) +#define isfinite(x) (!(isinf((x)) || isnan((x)))) +#endif + #if !defined(HAVE_DECL_SIGNBIT) #include "_signbit.c" # define signbit(x) \ @@ -161,11 +166,6 @@ } #endif -/* Define isfinie if needed */ -#if !defined(HAVE_DECL_ISFINITE) -#define isfinite(x) (!(isinf((x)) || isnan((x)))) -#endif - /* * if C99 extensions not available then define dummy functions that use the * double versions for From numpy-svn at scipy.org Sat Sep 20 12:11:54 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 11:11:54 -0500 (CDT) Subject: [Numpy-svn] r5849 - branches/clean_math_config/numpy/core/src Message-ID: <20080920161154.C17AC39C088@scipy.org> Author: cdavid Date: 2008-09-20 11:11:51 -0500 (Sat, 20 Sep 2008) New Revision: 5849 Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src Log: Fix isfinite. Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:10:53 UTC (rev 5848) +++ branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:11:51 UTC (rev 5849) @@ -145,7 +145,7 @@ /* Define isfinie if needed */ #if !defined(HAVE_DECL_ISFINITE) -#define isfinite(x) (!(isinf((x)) || isnan((x)))) +#define isfinite(x) (!isinf(x) && !isnan(x)) #endif #if !defined(HAVE_DECL_SIGNBIT) From numpy-svn at scipy.org Sat Sep 20 12:13:04 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 11:13:04 -0500 (CDT) Subject: [Numpy-svn] r5850 - branches/clean_math_config/numpy/core/src Message-ID: <20080920161304.008CE39C088@scipy.org> Author: cdavid Date: 2008-09-20 11:12:59 -0500 (Sat, 20 Sep 2008) New Revision: 5850 Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src Log: Autoconf suggestion is totally bogus: isinf(nan) is false, not true. Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:11:51 UTC (rev 5849) +++ branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:12:59 UTC (rev 5850) @@ -139,8 +139,8 @@ # define isnan(x) ((x) != (x)) #endif -#if !defined(HAVE_DECL_ISINF) - # define isinf(x) isnan((x) - (x)) +#if !defined(HAVE_DECL_ISFINITE) + # define isfinite(x) !isnan((x) - (x)) #endif /* Define isfinie if needed */ From numpy-svn at scipy.org Sat Sep 20 12:13:52 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 11:13:52 -0500 (CDT) Subject: [Numpy-svn] r5851 - branches/clean_math_config/numpy/core/src Message-ID: <20080920161352.631A839C088@scipy.org> Author: cdavid Date: 2008-09-20 11:13:48 -0500 (Sat, 20 Sep 2008) New Revision: 5851 Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src Log: Define isfinite first, and define isinf in function of isfinite/isnan. Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:12:59 UTC (rev 5850) +++ branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:13:48 UTC (rev 5851) @@ -143,9 +143,8 @@ # define isfinite(x) !isnan((x) - (x)) #endif -/* Define isfinie if needed */ -#if !defined(HAVE_DECL_ISFINITE) -#define isfinite(x) (!isinf(x) && !isnan(x)) +#if !defined(HAVE_DECL_ISINF) +#define isinf(x) (!isfinite(x) && !isnan(x)) #endif #if !defined(HAVE_DECL_SIGNBIT) From numpy-svn at scipy.org Sat Sep 20 12:26:34 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 11:26:34 -0500 (CDT) Subject: [Numpy-svn] r5852 - branches/clean_math_config/numpy/core/src Message-ID: <20080920162634.356C539C088@scipy.org> Author: cdavid Date: 2008-09-20 11:26:30 -0500 (Sat, 20 Sep 2008) New Revision: 5852 Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src Log: Fix for isfinite on VS 2003. VS 2003 seems to think it is ok to simplify x-x to 0 for float, but this is wrong for NaN and Inf. To alleviate, we force the operation to occur with (x) + (-x). Modified: branches/clean_math_config/numpy/core/src/math_c99.inc.src =================================================================== --- branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:13:48 UTC (rev 5851) +++ branches/clean_math_config/numpy/core/src/math_c99.inc.src 2008-09-20 16:26:30 UTC (rev 5852) @@ -139,8 +139,10 @@ # define isnan(x) ((x) != (x)) #endif +/* VS 2003 with /Ox optimizes (x)-(x) to 0, which is not IEEE compliant. So we + * force (x) + (-x), which seems to work. */ #if !defined(HAVE_DECL_ISFINITE) - # define isfinite(x) !isnan((x) - (x)) + # define isfinite(x) !isnan((x) + (-x)) #endif #if !defined(HAVE_DECL_ISINF) From numpy-svn at scipy.org Sat Sep 20 12:56:11 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sat, 20 Sep 2008 11:56:11 -0500 (CDT) Subject: [Numpy-svn] r5853 - branches/clean_math_config/numpy/core Message-ID: <20080920165611.DD8F439C088@scipy.org> Author: cdavid Date: 2008-09-20 11:56:08 -0500 (Sat, 20 Sep 2008) New Revision: 5853 Modified: branches/clean_math_config/numpy/core/setup.py Log: More intrinsics. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-20 16:26:30 UTC (rev 5852) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-20 16:56:08 UTC (rev 5853) @@ -72,7 +72,7 @@ # intrisincs functions are available. # Functions which have intrisinces: sin, cos, tan, sin, cosh, tanh, # fabs, sqrt, log10, log, exp, asin, acos, atan, fmod - mandatory_funcs = ["floor", "ceil", 'modf', 'frexp', 'ldexp'] + mandatory_funcs = ['modf', 'frexp', 'ldexp'] else: mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", From numpy-svn at scipy.org Sun Sep 21 03:10:52 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 21 Sep 2008 02:10:52 -0500 (CDT) Subject: [Numpy-svn] r5854 - branches Message-ID: <20080921071052.6F19739C2C6@scipy.org> Author: charris Date: 2008-09-21 02:10:49 -0500 (Sun, 21 Sep 2008) New Revision: 5854 Added: branches/clean_math_config_chuck/ Log: Make branch from David's work for cleaning inner ufunc loops. Copied: branches/clean_math_config_chuck (from rev 5853, branches/clean_math_config) From numpy-svn at scipy.org Sun Sep 21 07:39:17 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 21 Sep 2008 06:39:17 -0500 (CDT) Subject: [Numpy-svn] r5855 - branches/clean_math_config/numpy/distutils/command Message-ID: <20080921113917.447F439C352@scipy.org> Author: cdavid Date: 2008-09-21 06:39:08 -0500 (Sun, 21 Sep 2008) New Revision: 5855 Modified: branches/clean_math_config/numpy/distutils/command/config.py Log: Handle msvc intrisincs in check_func. Modified: branches/clean_math_config/numpy/distutils/command/config.py =================================================================== --- branches/clean_math_config/numpy/distutils/command/config.py 2008-09-21 07:10:49 UTC (rev 5854) +++ branches/clean_math_config/numpy/distutils/command/config.py 2008-09-21 11:39:08 UTC (rev 5855) @@ -126,6 +126,13 @@ body = [] if decl: body.append("int %s ();" % func) + # Handle MSVC intrisincs: force MS compiler to make a function call. + # Useful to test for some functions when built with optimization on, to + # avoid build error because the intrisinc and our 'fake' test + # declaration do not match. + body.append("#ifdef _MSC_VER") + body.append("#define function(%s)" % func) + body.append("#endif") body.append("int main (void) {") if call: if call_args is None: From numpy-svn at scipy.org Sun Sep 21 07:39:35 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 21 Sep 2008 06:39:35 -0500 (CDT) Subject: [Numpy-svn] r5856 - branches/clean_math_config/numpy/distutils/command Message-ID: <20080921113935.2BF5139C352@scipy.org> Author: cdavid Date: 2008-09-21 06:39:27 -0500 (Sun, 21 Sep 2008) New Revision: 5856 Modified: branches/clean_math_config/numpy/distutils/command/config.py Log: Handle msvc intrisincs in check_funcs_once. Modified: branches/clean_math_config/numpy/distutils/command/config.py =================================================================== --- branches/clean_math_config/numpy/distutils/command/config.py 2008-09-21 11:39:08 UTC (rev 5855) +++ branches/clean_math_config/numpy/distutils/command/config.py 2008-09-21 11:39:27 UTC (rev 5856) @@ -181,6 +181,12 @@ if v: body.append("int %s ();" % f) + # Handle MS intrinsics. See check_func for more info. + body.append("#ifdef _MSC_VER") + for func in funcs: + body.append("#define function(%s)" % func) + body.append("#endif") + body.append("int main (void) {") if call: for f in funcs: From numpy-svn at scipy.org Sun Sep 21 07:50:40 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 21 Sep 2008 06:50:40 -0500 (CDT) Subject: [Numpy-svn] r5857 - branches/clean_math_config/numpy/distutils/command Message-ID: <20080921115040.6F4DE39C352@scipy.org> Author: cdavid Date: 2008-09-21 06:50:32 -0500 (Sun, 21 Sep 2008) New Revision: 5857 Modified: branches/clean_math_config/numpy/distutils/command/config.py Log: define -> pragma, stupid mistake. Modified: branches/clean_math_config/numpy/distutils/command/config.py =================================================================== --- branches/clean_math_config/numpy/distutils/command/config.py 2008-09-21 11:39:27 UTC (rev 5856) +++ branches/clean_math_config/numpy/distutils/command/config.py 2008-09-21 11:50:32 UTC (rev 5857) @@ -131,7 +131,7 @@ # avoid build error because the intrisinc and our 'fake' test # declaration do not match. body.append("#ifdef _MSC_VER") - body.append("#define function(%s)" % func) + body.append("#pragma function(%s)" % func) body.append("#endif") body.append("int main (void) {") if call: @@ -184,7 +184,7 @@ # Handle MS intrinsics. See check_func for more info. body.append("#ifdef _MSC_VER") for func in funcs: - body.append("#define function(%s)" % func) + body.append("#pragma function(%s)" % func) body.append("#endif") body.append("int main (void) {") From numpy-svn at scipy.org Sun Sep 21 07:54:54 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 21 Sep 2008 06:54:54 -0500 (CDT) Subject: [Numpy-svn] r5858 - branches/clean_math_config/numpy/core Message-ID: <20080921115454.DD86A39C352@scipy.org> Author: cdavid Date: 2008-09-21 06:54:48 -0500 (Sun, 21 Sep 2008) New Revision: 5858 Modified: branches/clean_math_config/numpy/core/setup.py Log: Do not use MSVC workaround anymore, since we now can test for function even when they are intrinsincs. Modified: branches/clean_math_config/numpy/core/setup.py =================================================================== --- branches/clean_math_config/numpy/core/setup.py 2008-09-21 11:50:32 UTC (rev 5857) +++ branches/clean_math_config/numpy/core/setup.py 2008-09-21 11:54:48 UTC (rev 5858) @@ -63,20 +63,12 @@ def name_to_defsymb(name): return "HAVE_%s" % name.upper() - use_msvc = config.check_decl("_MSC_VER") + #use_msvc = config.check_decl("_MSC_VER") # Mandatory functions: if not found, fail the build - if use_msvc: - # MSVC use intrisincs functions when build with e.g. /Ox, and this - # breaks tests. Fixing the tests is not trivial, so we assume the - # intrisincs functions are available. - # Functions which have intrisinces: sin, cos, tan, sin, cosh, tanh, - # fabs, sqrt, log10, log, exp, asin, acos, atan, fmod - mandatory_funcs = ['modf', 'frexp', 'ldexp'] - else: - mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", - "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", - "acos", "atan", "fmod", 'modf', 'frexp', 'ldexp'] + mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", + "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", + "acos", "atan", "fmod", 'modf', 'frexp', 'ldexp'] if not check_funcs_once(mandatory_funcs): raise SystemError("One of the required function to build numpy is not" From numpy-svn at scipy.org Sun Sep 21 23:21:49 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 21 Sep 2008 22:21:49 -0500 (CDT) Subject: [Numpy-svn] r5859 - branches/clean_math_config_chuck/numpy/core/src Message-ID: <20080922032149.5C9F239C1EC@scipy.org> Author: charris Date: 2008-09-21 22:21:01 -0500 (Sun, 21 Sep 2008) New Revision: 5859 Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src Log: Initial merge of previous work. Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-21 11:54:48 UTC (rev 5858) +++ branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-22 03:21:01 UTC (rev 5859) @@ -22,6 +22,12 @@ #endif #include "math_c99.inc" +/* + ***************************************************************************** + ** BASIC MATH FUNCTIONS ** + ***************************************************************************** + */ + float degreesf(float x) { return x * (float)(180.0/M_PI); } @@ -436,14 +442,25 @@ */ +/* + ***************************************************************************** + ** BOOLEAN LOOPS ** + ***************************************************************************** + */ + /**begin repeat + * Boolean type + * + * #type = Bool# + * #TYPE = BOOL# + */ - #TYPE=(BOOL, BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*2# - #OP=||, +*13, ^, -*13# - #kind=add*14, subtract*14# - #typ=(Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*2# -*/ - +/**begin repeat1 + * Arithmetic operators + * + * # OP = ||, ^, &&# + * #kind = add, subtract, multiply# + */ static void @TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) { @@ -451,328 +468,347 @@ intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; char *i1=args[0], *i2=args[1], *op=args[2]; for(i=0; ireal, \ - ai=((c at typ@ *)i1)->imag, \ - br=((c at typ@ *)i2)->real, \ - bi=((c at typ@ *)i2)->imag; - ((c at typ@ *)op)->real = ar*br - ai*bi; - ((c at typ@ *)op)->imag = ar*bi + ai*br; + for (i = 0; i < n; i++, i1 += is1, op += os) { + @s@@type@ x = *((@s@@type@ *)i1); + *((@s@@type@ *)op) = x*x; } } static void - at TYP@_divide(char **args, intp *dimensions, intp *steps, void *func) + at S@@TYPE at _reciprocal(char **args, intp *dimensions, intp *steps, void *data) { - register intp i; - intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for (i=0; ireal, \ - ai=((c at typ@ *)i1)->imag, \ - br=((c at typ@ *)i2)->real, \ - bi=((c at typ@ *)i2)->imag; - register @typ@ d = br*br + bi*bi; - ((c at typ@ *)op)->real = (ar*br + ai*bi)/d; - ((c at typ@ *)op)->imag = (ai*br - ar*bi)/d; - } -} + intp i, is1 = steps[0], os = steps[1], n = dimensions[0]; + char *i1 = args[0], *op = args[1]; -static void - at TYP@_floor_divide(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; ireal, \ - ai=((c at typ@ *)i1)->imag, \ - br=((c at typ@ *)i2)->real, \ - bi=((c at typ@ *)i2)->imag; - register @typ@ d = br*br + bi*bi; - ((c at typ@ *)op)->real = floor at c@((ar*br + ai*bi)/d); - ((c at typ@ *)op)->imag = 0; + for (i = 0; i < n; i++, i1 += is1, op += os) { + @s@@type@ x = *((@s@@type@ *)i1); + *((@s@@type@ *)op) = 1.0/x; } } -#define @TYP at _true_divide @TYP at _divide -/**end repeat**/ +/**end repeat1**/ - -/**begin repeat - #TYP=UBYTE,USHORT,UINT,ULONG,ULONGLONG# - #typ=ubyte, ushort, uint, ulong, ulonglong# -*/ static void - at TYP@_divide(char **args, intp *dimensions, intp *steps, void *func) + at TYPE@_divide(char **args, intp *dimensions, intp *steps, void *func) { register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0]; char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i 0) != (y > 0)) && (x % y != 0)) tmp--; - *((@typ@ *)op)= tmp; + *((@type@ *)op)= tmp; } } } -/**end repeat**/ - -/**begin repeat - #TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG# - #typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong# - #otyp=float*4, double*6# -*/ static void - at TYP@_true_divide(char **args, intp *dimensions, intp *steps, void *func) +U at TYPE@_divide(char **args, intp *dimensions, intp *steps, void *func) { register intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0]; char *i1=args[0], *i2=args[1], *op=args[2]; for(i=0; ireal; - xi = x->imag; - y->real = xr*xr - xi*xi; - y->imag = 2*xr*xi; + @type@ x = *((@type@ *)i1); + *((@type@ *)op) = 1.0/x; } } + +#define @TYPE at _true_divide @TYPE at _divide /**end repeat**/ -static PyObject * -Py_square(PyObject *o) + +/* + ***************************************************************************** + ** COMPLEX LOOPS ** + ***************************************************************************** + */ + +/**begin repeat + * complex types + * #ctype= cfloat, cdouble, clongdouble# + * #CTYPE= CFLOAT, CDOUBLE, CLONGDOUBLE# + * #type = float, double, longdouble# + * #c = f, , l# + */ + +/**begin repeat1 + * arithmetic + * #OP = +, -# + * #kind = add, subtract# + */ +static void + at CTYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { - return PyNumber_Multiply(o, o); + register intp i; + intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; + char *i1=args[0], *i2=args[1], *op=args[2]; + for(i=0; ireal; + @type@ ai=((@ctype@ *)i1)->imag; + @type@ br=((@ctype@ *)i2)->real; + @type@ bi=((@ctype@ *)i2)->imag; + ((@ctype@ *)op)->real = ar*br - ai*bi; + ((@ctype@ *)op)->imag = ar*bi + ai*br; + } +} + +static void + at CTYPE@_divide(char **args, intp *dimensions, intp *steps, void *func) +{ + register intp i; + intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0]; + char *i1=args[0], *i2=args[1], *op=args[2]; + for (i=0; ireal; + @type@ ai=((@ctype@ *)i1)->imag; + @type@ br=((@ctype@ *)i2)->real; + @type@ bi=((@ctype@ *)i2)->imag; + @type@ d = br*br + bi*bi; + ((@ctype@ *)op)->real = (ar*br + ai*bi)/d; + ((@ctype@ *)op)->imag = (ai*br - ar*bi)/d; + } +} + +static void + at CTYPE@_floor_divide(char **args, intp *dimensions, intp *steps, void *func) +{ + register intp i; + intp is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0]; + char *i1=args[0], *i2=args[1], *op=args[2]; + for(i=0; ireal; + @type@ ai=((@ctype@ *)i1)->imag; + @type@ br=((@ctype@ *)i2)->real; + @type@ bi=((@ctype@ *)i2)->imag; + @type@ d = br*br + bi*bi; + ((@ctype@ *)op)->real = floor at c@((ar*br + ai*bi)/d); + ((@ctype@ *)op)->imag = 0; + } +} + +static void + at CTYPE@_square(char **args, intp *dimensions, intp *steps, void *data) +{ intp i, is1 = steps[0], os = steps[1], n = dimensions[0]; char *i1 = args[0], *op = args[1]; for (i = 0; i < n; i++, i1 += is1, op += os) { - @typ@ x = *((@typ@ *)i1); - *((@typ@ *)op) = (@typ@) (1.0 / x); + @ctype@ *x = (@ctype@ *)i1; + @ctype@ *y = (@ctype@ *)op; + @type@ xr = x->real; + @type@ xi = x->imag; + y->real = xr*xr - xi*xi; + y->imag = 2*xr*xi; } } -/**end repeat**/ -/**begin repeat - #TYP=CFLOAT,CDOUBLE,CLONGDOUBLE# - #typ=float, double, longdouble# -*/ +/* fixme -- need type specific fabs */ static void - at TYP@_reciprocal(char **args, intp *dimensions, intp *steps, void *data) + at CTYPE@_reciprocal(char **args, intp *dimensions, intp *steps, void *data) { intp i, is1 = steps[0], os = steps[1], n = dimensions[0]; char *i1 = args[0], *op = args[1]; - c at typ@ *x, *y; - @typ@ xr, xi, r, denom; for (i = 0; i < n; i++, i1 += is1, op += os) { - x = (c at typ@ *)i1; - y = (c at typ@ *)op; - xr = x->real; - xi = x->imag; + @ctype@ *x = (@ctype@ *)i1; + @ctype@ *y = (@ctype@ *)op; + @type@ xr = x->real; + @type@ xi = x->imag; if (fabs(xi) <= fabs(xr)) { - r = xi / xr; - denom = xr + xi * r; - y->real = 1 / denom; - y->imag = -r / denom; + @type@ r = xi/xr; + @type@ denom = xr + xi*r; + y->real = 1/denom; + y->imag = -r/denom; } else { - r = xr / xi; - denom = xr * r + xi; - y->real = r / denom; - y->imag = -1 / denom; + @type@ r = xr/xi; + @type@ denom = xr*r + xi; + y->real = r/denom; + y->imag = -1/denom; } } } + +#define @CTYPE at _true_divide @CTYPE at _divide /**end repeat**/ +/* + ***************************************************************************** + ** OBJECT LOOPS ** + ***************************************************************************** + */ + static PyObject * +Py_square(PyObject *o) +{ + return PyNumber_Multiply(o, o); +} + + +static PyObject * Py_reciprocal(PyObject *o) { PyObject *one, *result; @@ -817,6 +853,12 @@ return res; } +/* + ***************************************************************************** + ** UNDONE LOOPS ** + ***************************************************************************** + */ + /* ones_like is defined here because it's used for x**0 */ /**begin repeat From numpy-svn at scipy.org Mon Sep 22 16:28:25 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 22 Sep 2008 15:28:25 -0500 (CDT) Subject: [Numpy-svn] r5860 - in trunk/numpy/lib: . tests Message-ID: <20080922202825.026FE39C089@scipy.org> Author: stefan Date: 2008-09-22 15:28:00 -0500 (Mon, 22 Sep 2008) New Revision: 5860 Modified: trunk/numpy/lib/io.py trunk/numpy/lib/tests/test_io.py Log: Ignore unused converters in `loadtxt`. Modified: trunk/numpy/lib/io.py =================================================================== --- trunk/numpy/lib/io.py 2008-09-22 03:21:01 UTC (rev 5859) +++ trunk/numpy/lib/io.py 2008-09-22 20:28:00 UTC (rev 5860) @@ -378,7 +378,11 @@ # By preference, use the converters specified by the user for i, conv in (user_converters or {}).iteritems(): if usecols: - i = usecols.index(i) + try: + i = usecols.index(i) + except ValueError: + # Unused converter specified + continue converters[i] = conv # Parse each line, including the first Modified: trunk/numpy/lib/tests/test_io.py =================================================================== --- trunk/numpy/lib/tests/test_io.py 2008-09-22 03:21:01 UTC (rev 5859) +++ trunk/numpy/lib/tests/test_io.py 2008-09-22 20:28:00 UTC (rev 5860) @@ -258,6 +258,17 @@ 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() From numpy-svn at scipy.org Mon Sep 22 23:48:07 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 22 Sep 2008 22:48:07 -0500 (CDT) Subject: [Numpy-svn] r5861 - in branches/clean_math_config: . numpy/lib numpy/lib/tests Message-ID: <20080923034807.E801D39C034@scipy.org> Author: cdavid Date: 2008-09-22 22:48:01 -0500 (Mon, 22 Sep 2008) New Revision: 5861 Modified: branches/clean_math_config/ branches/clean_math_config/numpy/lib/io.py branches/clean_math_config/numpy/lib/tests/test_io.py Log: Merged revisions 5844-5860 via svnmerge from http://svn.scipy.org/svn/numpy/trunk ........ r5860 | stefan | 2008-09-23 05:28:00 +0900 (Tue, 23 Sep 2008) | 2 lines Ignore unused converters in `loadtxt`. ........ Property changes on: branches/clean_math_config ___________________________________________________________________ Name: svnmerge-integrated - /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5843 + /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5860 Modified: branches/clean_math_config/numpy/lib/io.py =================================================================== --- branches/clean_math_config/numpy/lib/io.py 2008-09-22 20:28:00 UTC (rev 5860) +++ branches/clean_math_config/numpy/lib/io.py 2008-09-23 03:48:01 UTC (rev 5861) @@ -378,7 +378,11 @@ # By preference, use the converters specified by the user for i, conv in (user_converters or {}).iteritems(): if usecols: - i = usecols.index(i) + try: + i = usecols.index(i) + except ValueError: + # Unused converter specified + continue converters[i] = conv # Parse each line, including the first Modified: branches/clean_math_config/numpy/lib/tests/test_io.py =================================================================== --- branches/clean_math_config/numpy/lib/tests/test_io.py 2008-09-22 20:28:00 UTC (rev 5860) +++ branches/clean_math_config/numpy/lib/tests/test_io.py 2008-09-23 03:48:01 UTC (rev 5861) @@ -258,6 +258,17 @@ 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() From numpy-svn at scipy.org Wed Sep 24 07:50:45 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 24 Sep 2008 06:50:45 -0500 (CDT) Subject: [Numpy-svn] r5862 - trunk/numpy/lib Message-ID: <20080924115045.85A2539C2EA@scipy.org> Author: ptvirtan Date: 2008-09-24 06:50:38 -0500 (Wed, 24 Sep 2008) New Revision: 5862 Modified: trunk/numpy/lib/utils.py Log: Fix python2.5 dependency in lookfor Modified: trunk/numpy/lib/utils.py =================================================================== --- trunk/numpy/lib/utils.py 2008-09-23 03:48:01 UTC (rev 5861) +++ trunk/numpy/lib/utils.py 2008-09-24 11:50:38 UTC (rev 5862) @@ -1,6 +1,5 @@ import os import sys -import pkgutil import types import re @@ -680,15 +679,21 @@ _all = item.__all__ except AttributeError: _all = None + # import sub-packages if import_modules and hasattr(item, '__path__'): - for m in pkgutil.iter_modules(item.__path__): - if _all is not None and m[1] not in _all: - continue - try: - __import__("%s.%s" % (name, m[1])) - except ImportError: - continue + for pth in item.__path__: + for mod_path in os.listdir(pth): + init_py = os.path.join(pth, mod_path, '__init__.py') + if not os.path.isfile(init_py): + continue + if _all is not None and mod_path not in _all: + continue + try: + __import__("%s.%s" % (name, mod_path)) + except ImportError: + continue + for n, v in inspect.getmembers(item): if _all is not None and n not in _all: continue From numpy-svn at scipy.org Thu Sep 25 00:45:07 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 24 Sep 2008 23:45:07 -0500 (CDT) Subject: [Numpy-svn] r5863 - tags Message-ID: <20080925044507.9A08639C0EA@scipy.org> Author: jarrod.millman Date: 2008-09-24 23:45:04 -0500 (Wed, 24 Sep 2008) New Revision: 5863 Added: tags/1.2.0/ Log: tagging the release Copied: tags/1.2.0 (from rev 5862, branches/1.2.x) From numpy-svn at scipy.org Thu Sep 25 00:46:20 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Wed, 24 Sep 2008 23:46:20 -0500 (CDT) Subject: [Numpy-svn] r5864 - tags/1.2.0/numpy Message-ID: <20080925044620.19AA339C0EA@scipy.org> Author: jarrod.millman Date: 2008-09-24 23:46:16 -0500 (Wed, 24 Sep 2008) New Revision: 5864 Modified: tags/1.2.0/numpy/version.py Log: making the release Modified: tags/1.2.0/numpy/version.py =================================================================== --- tags/1.2.0/numpy/version.py 2008-09-25 04:45:04 UTC (rev 5863) +++ tags/1.2.0/numpy/version.py 2008-09-25 04:46:16 UTC (rev 5864) @@ -1,5 +1,5 @@ version='1.2.0' -release=False +release=True if not release: version += '.dev' From numpy-svn at scipy.org Thu Sep 25 13:31:37 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 25 Sep 2008 12:31:37 -0500 (CDT) Subject: [Numpy-svn] r5865 - branches/clean_math_config_chuck/numpy/core/src Message-ID: <20080925173137.9F6C139C0F7@scipy.org> Author: charris Date: 2008-09-25 12:31:35 -0500 (Thu, 25 Sep 2008) New Revision: 5865 Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src Log: Work in progress Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-25 04:46:16 UTC (rev 5864) +++ branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-25 17:31:35 UTC (rev 5865) @@ -473,6 +473,52 @@ } /**end repeat1**/ +static void + at TYPE@_ones_like(char **args, intp *dimensions, intp *steps, void *data) +{ + intp i, os = steps[1], n = dimensions[0]; + char *op = args[1]; + + for (i = 0; i < n; i++, op += os) { + *((@type@ *)op) = 1; + } +} + +static void + at TYPE@_absolute(char **args, intp *dimensions, intp *steps, void *func) +{ + intp i, n; + intp is1=steps[0], os=steps[1]; + char *i1=args[0], *op=args[1]; + + n=dimensions[0]; + + for(i=0; i, >=, <, <=, ==, !=, &&, ||, &, |, ^# + **/ +static void + at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) +{ + register intp i; + intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; + char *i1=args[0], *i2=args[1], *op=args[2]; + Bool in1, in2; + for(i=0; i, >=, <, <=, ==, !=, &&, ||# + */ static void + at S@@TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) +{ + intp i; + intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; + char *i1=args[0], *i2=args[1], *op=args[2]; + for(i=0; i, >=, ==, !=, &&, ||# + */ static void + at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) +{ + register intp i; + intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; + char *i1=args[0], *i2=args[1], *op=args[2]; + for(i=0; ireal = 1.0; + y->imag = 0.0; + } +} + +static void + at CTYPE@_conjugate(char **args, intp *dimensions, intp *steps, void *func) { + intp i, is1=steps[0], os=steps[1], n=dimensions[0]; + char *i1=args[0], *op=args[1]; + + for(i=0; i, >=, <, <=# + */ +static void + at CTYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) +{ + intp i; + intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; + char *i1=args[0], *i2=args[1], *op=args[2]; + for(i=0; ireal == ((c at type@ *)i2)->real) + *((Bool *)op)=((c at type@ *)i1)->imag @OP@ + ((c at type@ *)i2)->imag; + else + *((Bool *)op)=((c at type@ *)i1)->real @OP@ + ((c at type@ *)i2)->real; + } +} +/**end repeat1**/ + #define @CTYPE at _true_divide @CTYPE at _divide /**end repeat**/ @@ -807,6 +1061,11 @@ return PyNumber_Multiply(o, o); } +static PyObject * +Py_get_one(PyObject *o) +{ + return PyInt_FromLong(1); +} static PyObject * Py_reciprocal(PyObject *o) @@ -853,278 +1112,8 @@ return res; } -/* - ***************************************************************************** - ** UNDONE LOOPS ** - ***************************************************************************** - */ - -/* ones_like is defined here because it's used for x**0 */ - /**begin repeat - #TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE# - #typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble# -*/ -static void - at TYP@_ones_like(char **args, intp *dimensions, intp *steps, void *data) -{ - intp i, os = steps[1], n = dimensions[0]; - char *op = args[1]; - for (i = 0; i < n; i++, op += os) { - *((@typ@ *)op) = 1; - } -} -/**end repeat**/ - -/**begin repeat - #TYP=CFLOAT,CDOUBLE,CLONGDOUBLE# - #typ=float, double, longdouble# -*/ -static void - at TYP@_ones_like(char **args, intp *dimensions, intp *steps, void *data) -{ - intp i, is1 = steps[0], os = steps[1], n = dimensions[0]; - char *i1 = args[0], *op = args[1]; - c at typ@ *y; - - for (i = 0; i < n; i++, i1 += is1, op += os) { - y = (c at typ@ *)op; - y->real = 1.0; - y->imag = 0.0; - } -} -/**end repeat**/ - -static PyObject * -Py_get_one(PyObject *o) -{ - return PyInt_FromLong(1); -} - - -/**begin repeat - #TYP=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG# - #typ=char, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong# - #btyp=float*4, double*6# -*/ -static void - at TYP@_power(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i, is1=steps[0],is2=steps[1]; - register intp os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - @btyp@ x, y; - - for(i=0; i, >=, <, <=, ==, !=, &&, ||, &, |, ^# -**/ -static void -BOOL_ at kind@(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - Bool in1, in2; - for(i=0; i*13, >=*13, <*13, <=*13# - #typ=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*4# - #kind= greater*13, greater_equal*13, less*13, less_equal*13# -*/ - -static void - at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i*3, >=*3, <*3, <=*3# - #typ=(cfloat, cdouble, clongdouble)*4# - #kind= greater*3, greater_equal*3, less*3, less_equal*3# -*/ - -static void - at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; ireal == ((@typ@ *)i2)->real) - *((Bool *)op)=((@typ@ *)i1)->imag @OP@ \ - ((@typ@ *)i2)->imag; - else - *((Bool *)op)=((@typ@ *)i1)->real @OP@ \ - ((@typ@ *)i2)->real; - } -} -/**end repeat**/ - - -/**begin repeat - #TYPE=(BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*4# - #typ=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*4# - #OP= ==*13, !=*13, &&*13, ||*13# - #kind=equal*13, not_equal*13, logical_and*13, logical_or*13# -*/ -static void - at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i 0 ? 1 : ((x) < 0 ? -1 : 0)) #define _SIGN2(x) ((x) == 0 ? 0 : 1) #define _SIGNC(x) (((x).real > 0) ? 1 : ((x).real < 0 ? -1 : ((x).imag > 0 ? 1 : ((x).imag < 0) ? -1 : 0))) @@ -1223,7 +1222,7 @@ Py_DECREF(zero); } - +/*logical_not*/ /**begin repeat #TYPE=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE# #typ=Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble# @@ -1259,7 +1258,7 @@ - +/*remainder*/ /**begin repeat #TYPE=BYTE,SHORT,INT,LONG,LONGLONG# #typ=byte, short, int, long, longlong# @@ -1338,7 +1337,7 @@ } /**end repeat**/ - +/*fmod*/ /**begin repeat #TYPE=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG# @@ -1366,6 +1365,7 @@ } /**end repeat**/ +/*bitwise operators*/ /**begin repeat #TYPE=(BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG)*5# @@ -1386,7 +1386,7 @@ } /**end repeat**/ - +/*invert*/ /**begin repeat #TYPE=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG# #typ=byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong# @@ -1414,7 +1414,7 @@ } } - +/*logical_xor*/ /**begin repeat #TYPE=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE# #typ=Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble# @@ -1453,7 +1453,7 @@ /**end repeat**/ - +/*max,min*/ /**begin repeat #TYPE=(BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*2# @@ -1565,6 +1565,7 @@ } /**end repeat**/ +/*frexp, ldexp*/ /**begin repeat #TYPE=FLOAT, DOUBLE, LONGDOUBLE# #typ=float, double, longdouble# From numpy-svn at scipy.org Fri Sep 26 00:38:42 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Thu, 25 Sep 2008 23:38:42 -0500 (CDT) Subject: [Numpy-svn] r5866 - branches/clean_math_config_chuck/numpy/core/src Message-ID: <20080926043842.B78C339C0F1@scipy.org> Author: charris Date: 2008-09-25 23:38:40 -0500 (Thu, 25 Sep 2008) New Revision: 5866 Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src Log: Work in progress. Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-25 17:31:35 UTC (rev 5865) +++ branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-26 04:38:40 UTC (rev 5866) @@ -455,37 +455,41 @@ * #TYPE = BOOL# */ -/**begin repeat1 - * Arithmetic operators + +/**begin repeat * - * # OP = ||, ^, &&# - * #kind = add, subtract, multiply# - */ + * #kind = add, subtract, multiply, greater, greater_equal, less, less_equal, + * equal, not_equal, logical_and, logical_or, bitwise_and, bitwise_or, + * bitwise_xor# + * #OP = ||, ^, &&, >, >=, <, <=, ==, !=, &&, ||, &, |, ^# + **/ static void - at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) +BOOL_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { - register intp i; + intp i; intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; char *i1=args[0], *i2=args[1], *op=args[2]; for(i=0; i, >=, <, <=, ==, !=, &&, ||, &, |, ^# - **/ static void - at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) +BOOL_logical_not(char **args, intp *dimensions, intp *steps, void *func) { - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - Bool in1, in2; - for(i=0; i># */ static void @S@@TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) @@ -559,9 +554,9 @@ /**end repeat2**/ /**begin repeat2 - * kind = greater, greater_equal, less, less_equal, equal, not_equal, - * logical_and, logical_or# - * OP = >, >=, <, <=, ==, !=, &&, ||# + * #kind = greater, greater_equal, less, less_equal, equal, not_equal, + * logical_and, logical_or# + * #OP = >, >=, <, <=, ==, !=, &&, ||# */ static void @S@@TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) @@ -652,6 +647,28 @@ } } +static void + at S@@TYPE at _negative(char **args, intp *dimensions, intp *steps, void *func) +{ + register intp i; + intp is1=steps[0],os=steps[1], n=dimensions[0]; + char *i1=args[0], *op=args[1]; + for(i=0; ireal; } } + +static void + at CTYPE@_logical_not(char **args, intp *dimensions, intp *steps, void *func) +{ + intp i; + intp is1=steps[0],os=steps[1], n=dimensions[0]; + char *i1=args[0], *op=args[1]; + for(i=0; ireal || + ((@ctype@ *)i1)->imag); + } +} + /**end repeat1**/ #define @CTYPE at _true_divide @CTYPE at _divide @@ -1135,29 +1186,6 @@ ***************************************************************************** */ - - -/*negative*/ -/**begin repeat - - #TYPE=BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE# - #typ=byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble# - #styp=byte, byte, short, short, int, int, long, long, longlong, longlong, float, double, longdouble# -*/ -static void - at TYPE@_negative(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],os=steps[1], n=dimensions[0]; - char *i1=args[0], *op=args[1]; - for(i=0; i 0 ? 1 : ((x) < 0 ? -1 : 0)) #define _SIGN2(x) ((x) == 0 ? 0 : 1) @@ -1222,42 +1250,9 @@ Py_DECREF(zero); } -/*logical_not*/ -/**begin repeat - #TYPE=BOOL,BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE# - #typ=Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble# -*/ -static void - at TYPE@_logical_not(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],os=steps[1], n=dimensions[0]; - char *i1=args[0], *op=args[1]; - for(i=0; ireal || \ - ((@typ@ *)i1)->imag); - } -} -/**end repeat**/ - /*remainder*/ /**begin repeat #TYPE=BYTE,SHORT,INT,LONG,LONGLONG# @@ -1365,27 +1360,7 @@ } /**end repeat**/ -/*bitwise operators*/ -/**begin repeat - #TYPE=(BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG)*5# - #typ=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong)*5# - #OP= &*10, |*10, ^*10, <<*10, >>*10# - #kind=bitwise_and*10, bitwise_or*10, bitwise_xor*10, left_shift*10, right_shift*10# - -*/ -static void - at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - register char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i Author: charris Date: 2008-09-26 22:35:33 -0500 (Fri, 26 Sep 2008) New Revision: 5867 Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src Log: Work in progress. Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-26 04:38:40 UTC (rev 5866) +++ branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-27 03:35:33 UTC (rev 5867) @@ -441,7 +441,19 @@ ***************************************************************************** */ +#define BINARY_LOOP\ + char *ip1 = args[0], *ip2 = args[1], *op = args[2];\ + intp is1 = steps[0], is2 = steps[1], os = steps[2];\ + intp n = dimensions[0];\ + intp i;\ + for(i = 0; i < n; i++, ip1 += is1, ip2 += is2, op += os) +#define UNARY_LOOP\ + char *ip1 = args[0], *op = args[1];\ + intp is1 = steps[0], os = steps[1];\ + intp n = dimensions[0];\ + intp i;\ + for(i = 0; i < n; i++, ip1 += is1, op += os) /* ***************************************************************************** ** BOOLEAN LOOPS ** @@ -449,81 +461,75 @@ */ /**begin repeat - * Boolean type - * - * #type = Bool# - * #TYPE = BOOL# - */ - - -/**begin repeat - * - * #kind = add, subtract, multiply, greater, greater_equal, less, less_equal, - * equal, not_equal, logical_and, logical_or, bitwise_and, bitwise_or, - * bitwise_xor# - * #OP = ||, ^, &&, >, >=, <, <=, ==, !=, &&, ||, &, |, ^# + * #kind = equal, not_equal, greater, greater_equal, less, less_equal, + * logical_and, logical_or, logical_xor# + * #OP = ==, !=, >, >=, <, <=, &&, ||, ^# **/ static void BOOL_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { - intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i, <# + **/ static void -BOOL_ones_like(char **args, intp *dimensions, intp *steps, void *data) +BOOL_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { - intp i, os = steps[1], n = dimensions[0]; - char *op = args[1]; - - for (i = 0; i < n; i++, op += os) { - *((Bool *)op) = 1; + BINARY_LOOP { + Bool in1 = (*((Bool *)ip1) != 0); + Bool in2 = (*((Bool *)ip2) != 0); + *((Bool *)op) = (in1 @OP@ in2) ? in1 : in2; } } +/**end repeat**/ +/**begin repeat + * #kind = absolute, logical_not# + * #OP = !=, ==# + **/ static void -BOOL_absolute(char **args, intp *dimensions, intp *steps, void *func) +BOOL_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { - intp i, n; - intp is1=steps[0], os=steps[1]; - char *i1=args[0], *op=args[1]; - - n=dimensions[0]; - - for(i=0; i># - */ static void - at S@@TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) + at S@@TYPE at _square(char **args, intp *dimensions, intp *steps, void *data) { - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i, >=, <, <=, ==, !=, &&, ||# - */ static void - at S@@TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) + at S@@TYPE at _reciprocal(char **args, intp *dimensions, intp *steps, void *data) { - intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i># + */ static void - at S@@TYPE at _power(char **args, intp *dimensions, intp *steps, void *func) + at S@@TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) { - intp i, is1=steps[0],is2=steps[1]; - intp os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - @ftype@ x, y; - - for(i=0; i, >=, <, <=, &&, ||# + */ static void - at S@@TYPE at _conjugate(char **args, intp *dimensions, intp *steps, void *func) + at S@@TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) { - register intp i, is1=steps[0], os=steps[1], n=dimensions[0]; - char *i1=args[0], *op=args[1]; - for(i=0; i 0) ? in1 : -in1; *((@type@ *)op) += 0; /* fixme clear sign-bit ? */ } } @@ -702,21 +677,18 @@ static void @TYPE at _divide(char **args, intp *dimensions, intp *steps, void *func) { - intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - @type@ x, y, tmp; - - for(i=0; i 0) != (in2 > 0)) && (in1 % in2 != 0)) { + *((@type@ *)op) = in1/in2 - 1; + } else { - x = *((@type@ *)i1); - tmp = x / y; - if (((x > 0) != (y > 0)) && (x % y != 0)) tmp--; - *((@type@ *)op)= tmp; + *((@type@ *)op) = in1/in2; } } } @@ -724,15 +696,15 @@ static void U at TYPE@_divide(char **args, intp *dimensions, intp *steps, void *func) { - intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i*14, <*14# - #typ=(Bool, byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*2# - #kind= maximum*14, minimum*14# + #TYPE=(BYTE,UBYTE,SHORT,USHORT,INT,UINT,LONG,ULONG,LONGLONG,ULONGLONG,FLOAT,DOUBLE,LONGDOUBLE)*2# + #OP= >*13, <*13# + #typ=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*2# + #kind= maximum*13, minimum*13# */ static void @TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) From numpy-svn at scipy.org Sun Sep 28 11:19:58 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 28 Sep 2008 10:19:58 -0500 (CDT) Subject: [Numpy-svn] r5868 - branches/clean_math_config_chuck/numpy/core/src Message-ID: <20080928151958.DF25339C05F@scipy.org> Author: charris Date: 2008-09-28 10:19:56 -0500 (Sun, 28 Sep 2008) New Revision: 5868 Modified: branches/clean_math_config_chuck/numpy/core/src/arraytypes.inc.src Log: Clarify what string is repeated by code generator. Modified: branches/clean_math_config_chuck/numpy/core/src/arraytypes.inc.src =================================================================== --- branches/clean_math_config_chuck/numpy/core/src/arraytypes.inc.src 2008-09-27 03:35:33 UTC (rev 5867) +++ branches/clean_math_config_chuck/numpy/core/src/arraytypes.inc.src 2008-09-28 15:19:56 UTC (rev 5868) @@ -664,7 +664,7 @@ #from=BYTE*13,UBYTE*13,SHORT*13,USHORT*13,INT*13,UINT*13,LONG*13,ULONG*13,LONGLONG*13,ULONGLONG*13,FLOAT*13,DOUBLE*13,LONGDOUBLE*13,CFLOAT*13,CDOUBLE*13,CLONGDOUBLE*13# #totyp=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*16# #fromtyp=byte*13, ubyte*13, short*13, ushort*13, int*13, uint*13, long*13, ulong*13, longlong*13, ulonglong*13, float*13, double*13, longdouble*13, float*13, double*13, longdouble*13# -#incr= ip++*169,ip+=2*39# +#incr= (ip++)*169,(ip+=2)*39# */ static void @from at _to_@to@(register @fromtyp@ *ip, register @totyp@ *op, register intp n, From numpy-svn at scipy.org Sun Sep 28 13:27:41 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 28 Sep 2008 12:27:41 -0500 (CDT) Subject: [Numpy-svn] r5869 - in trunk/numpy/ma: . tests Message-ID: <20080928172741.3C94639C0F1@scipy.org> Author: pierregm Date: 2008-09-28 12:27:37 -0500 (Sun, 28 Sep 2008) New Revision: 5869 Modified: trunk/numpy/ma/core.py trunk/numpy/ma/tests/test_core.py Log: core: * added __rmul and __radd__ * fixed concatenate for flexible-dtype Modified: trunk/numpy/ma/core.py =================================================================== --- trunk/numpy/ma/core.py 2008-09-28 15:19:56 UTC (rev 5868) +++ trunk/numpy/ma/core.py 2008-09-28 17:27:37 UTC (rev 5869) @@ -1978,14 +1978,26 @@ "Add other to self, and return a new masked array." return add(self, other) # + def __radd__(self, other): + "Add other to self, and return a new masked array." + return add(self, other) + # def __sub__(self, other): "Subtract other to self, and return a new masked array." return subtract(self, other) # + def __rsub__(self, other): + "Subtract other to self, and return a new masked array." + return subtract(other, self) + # def __mul__(self, other): "Multiply other by self, and return a new masked array." return multiply(self, other) # + def __rmul__(self, other): + "Multiply other by self, and return a new masked array." + return multiply(self, other) + # def __div__(self, other): "Divide other into self, and return a new masked array." return divide(self, other) @@ -3527,7 +3539,7 @@ # ... all of them are True, and then check for dm.any() # shrink = numpy.logical_or.reduce([getattr(a,'_shrinkmask',True) for a in arrays]) # if shrink and not dm.any(): - if not dm.any(): + if not dm.dtype.fields and not dm.any(): data._mask = nomask else: data._mask = dm.reshape(d.shape) Modified: trunk/numpy/ma/tests/test_core.py =================================================================== --- trunk/numpy/ma/tests/test_core.py 2008-09-28 15:19:56 UTC (rev 5868) +++ trunk/numpy/ma/tests/test_core.py 2008-09-28 17:27:37 UTC (rev 5869) @@ -132,6 +132,15 @@ assert_array_equal(z,[1,1,0,0]) assert_array_equal(z.mask,[False,True,False,False]) + def test_concatenate_flexible(self): + "Tests the concatenation on flexible arrays." + data = masked_array(zip(np.random.rand(10), + np.arange(10)), + dtype=[('a',float),('b',int)]) + # + test = concatenate([data[:5], data[5:]]) + assert_equal_records(test, data) + def test_creation_ndmin(self): "Check the use of ndmin" x = array([1,2,3],mask=[1,0,0], ndmin=2) From numpy-svn at scipy.org Sun Sep 28 16:05:12 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 28 Sep 2008 15:05:12 -0500 (CDT) Subject: [Numpy-svn] r5870 - branches/clean_math_config_chuck/numpy/distutils Message-ID: <20080928200512.5513439C0F1@scipy.org> Author: charris Date: 2008-09-28 15:05:10 -0500 (Sun, 28 Sep 2008) New Revision: 5870 Modified: branches/clean_math_config_chuck/numpy/distutils/conv_template.py Log: Allow continuation lines in code generator for substitution values. Modified: branches/clean_math_config_chuck/numpy/distutils/conv_template.py =================================================================== --- branches/clean_math_config_chuck/numpy/distutils/conv_template.py 2008-09-28 17:27:37 UTC (rev 5869) +++ branches/clean_math_config_chuck/numpy/distutils/conv_template.py 2008-09-28 20:05:10 UTC (rev 5870) @@ -128,19 +128,22 @@ numrep = obj.group(2) return ','.join([torep]*int(numrep)) -parenrep = re.compile(r"[(]([^)]*?)[)]\*(\d+)") +parenrep = re.compile(r"[(]([^)]*)[)]\*(\d+)") plainrep = re.compile(r"([^*]+)\*(\d+)") -def conv(astr): +def parse_values(astr): # replaces all occurrences of '(a,b,c)*4' in astr - # with 'a,b,c,a,b,c,a,b,c,a,b,c'. The result is + # with 'a,b,c,a,b,c,a,b,c,a,b,c'. Empty braces generate + # empty values, i.e., ()*4 yields ',,,'. The result is # split at ',' and a list of values returned. - astr = parenrep.sub(paren_repl,astr) + astr = parenrep.sub(paren_repl, astr) # replaces occurences of xxx*3 with xxx, xxx, xxx astr = ','.join([plainrep.sub(paren_repl,x.strip()) for x in astr.split(',')]) return astr.split(',') -named_re = re.compile(r"#\s*([\w]*)\s*=\s*([^#]*)#") + +stripast = re.compile(r"\n\s*\*?") +named_re = re.compile(r"#\s*(\w*)\s*=([^#]*)#") def parse_loop_header(loophead) : """Find all named replacements in the header @@ -149,23 +152,29 @@ value is the replacement string. """ + # Strip out '\n' and leading '*', if any, in continuation lines. + # This should not effect code previous to this change as + # continuation lines were not allowed. + loophead = stripast.sub("", loophead) # parse out the names and lists of values names = [] reps = named_re.findall(loophead) nsub = None for rep in reps: - name = rep[0].strip() - vals = conv(rep[1]) + name = rep[0] + vals = parse_values(rep[1]) size = len(vals) if nsub is None : nsub = size elif nsub != size : - msg = "Mismatch in number: %s - %s" % (name, vals) + msg = "Mismatch in number of values:\n%s = %s" % (name, vals) raise ValueError, msg names.append((name,vals)) # generate list of dictionaries, one for each template iteration dlist = [] + if nsub is None : + raise ValueError, "No substitution variables found" for i in range(nsub) : tmp = {} for name,vals in names : @@ -183,8 +192,8 @@ try : val = env[name] except KeyError, e : - msg = '%s: %s'%(lineno, e) - raise KeyError, msg + msg = 'line %d: %s'%(line, e) + raise ValueError, msg return val code = [lineno] @@ -203,7 +212,7 @@ try : envlist = parse_loop_header(head) except ValueError, e : - msg = "%s: %s" % (lineno, e) + msg = "line %d: %s" % (newline, e) raise ValueError, msg for newenv in envlist : newenv.update(env) @@ -249,7 +258,10 @@ def process_file(source): lines = resolve_includes(source) sourcefile = os.path.normcase(source).replace("\\","\\\\") - code = process_str(''.join(lines)) + try: + code = process_str(''.join(lines)) + except ValueError, e: + raise ValueError, '"%s", %s' % (sourcefile, e) return '#line 1 "%s"\n%s' % (sourcefile, code) @@ -284,5 +296,8 @@ outfile = open(newname,'w') allstr = fid.read() - writestr = process_str(allstr) + try: + writestr = process_str(allstr) + except ValueError, e: + raise ValueError, "file %s, %s" % (file, e) outfile.write(writestr) From numpy-svn at scipy.org Sun Sep 28 16:06:02 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 28 Sep 2008 15:06:02 -0500 (CDT) Subject: [Numpy-svn] r5871 - branches/clean_math_config_chuck/numpy/core/src Message-ID: <20080928200602.22A4C39C0F1@scipy.org> Author: charris Date: 2008-09-28 15:06:00 -0500 (Sun, 28 Sep 2008) New Revision: 5871 Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src Log: Work in progress. Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-28 20:05:10 UTC (rev 5870) +++ branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-28 20:06:00 UTC (rev 5871) @@ -596,7 +596,7 @@ /**begin repeat2 * Arithmetic - * #kind = add, subtract, multiply, bitwise_and, bitwise_or, bitwise_xor + * #kind = add, subtract, multiply, bitwise_and, bitwise_or, bitwise_xor, * left_shift, right_shift# * #OP = +, -,*, &, |, ^, <<, >># */ @@ -635,7 +635,7 @@ const @s@@type@ in2 = *(@s@@type@ *)ip2; if (in2 == 0) { generate_divbyzero_error(); - *((@otype@ *)op) = 0; + *((@ftype@ *)op) = 0; } else { *((@ftype@ *)op) = (@ftype@)in1 / (@ftype@)in2; @@ -652,7 +652,6 @@ *((@s@@type@ *)op) = (@s@@type@) pow(in1, in2); } } - /**end repeat1**/ static void @@ -745,9 +744,9 @@ /**end repeat1**/ /**begin repeat1 - * kind = less, less_equal, greater, greater_equal, equal, not_equal, - * logical_and, logical_or# - * OP = <, <=, >, >=, ==, !=, &&, ||# + * #kind = less, less_equal, greater, greater_equal, equal, not_equal, + * logical_and, logical_or# + * #OP = <, <=, >, >=, ==, !=, &&, ||# */ static void @TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) @@ -1053,6 +1052,7 @@ ((c at type@ *)i2)->real; } } +/**end repeat1**/ static void @CTYPE at _logical_not(char **args, intp *dimensions, intp *steps, void *func) @@ -1066,8 +1066,6 @@ } } -/**end repeat1**/ - #define @CTYPE at _true_divide @CTYPE at _divide /**end repeat**/ From numpy-svn at scipy.org Sun Sep 28 16:16:12 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 28 Sep 2008 15:16:12 -0500 (CDT) Subject: [Numpy-svn] r5872 - in branches/clean_math_config_chuck/numpy: core distutils/command lib lib/tests Message-ID: <20080928201612.0C0D039C0F1@scipy.org> Author: charris Date: 2008-09-28 15:16:08 -0500 (Sun, 28 Sep 2008) New Revision: 5872 Modified: branches/clean_math_config_chuck/numpy/core/setup.py branches/clean_math_config_chuck/numpy/distutils/command/config.py branches/clean_math_config_chuck/numpy/lib/io.py branches/clean_math_config_chuck/numpy/lib/tests/test_io.py Log: Keep current with David's work. Modified: branches/clean_math_config_chuck/numpy/core/setup.py =================================================================== --- branches/clean_math_config_chuck/numpy/core/setup.py 2008-09-28 20:06:00 UTC (rev 5871) +++ branches/clean_math_config_chuck/numpy/core/setup.py 2008-09-28 20:16:08 UTC (rev 5872) @@ -63,20 +63,12 @@ def name_to_defsymb(name): return "HAVE_%s" % name.upper() - use_msvc = config.check_decl("_MSC_VER") + #use_msvc = config.check_decl("_MSC_VER") # Mandatory functions: if not found, fail the build - if use_msvc: - # MSVC use intrisincs functions when build with e.g. /Ox, and this - # breaks tests. Fixing the tests is not trivial, so we assume the - # intrisincs functions are available. - # Functions which have intrisinces: sin, cos, tan, sin, cosh, tanh, - # fabs, sqrt, log10, log, exp, asin, acos, atan, fmod - mandatory_funcs = ['modf', 'frexp', 'ldexp'] - else: - mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", - "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", - "acos", "atan", "fmod", 'modf', 'frexp', 'ldexp'] + mandatory_funcs = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs", + "floor", "ceil", "sqrt", "log10", "log", "exp", "asin", + "acos", "atan", "fmod", 'modf', 'frexp', 'ldexp'] if not check_funcs_once(mandatory_funcs): raise SystemError("One of the required function to build numpy is not" Modified: branches/clean_math_config_chuck/numpy/distutils/command/config.py =================================================================== --- branches/clean_math_config_chuck/numpy/distutils/command/config.py 2008-09-28 20:06:00 UTC (rev 5871) +++ branches/clean_math_config_chuck/numpy/distutils/command/config.py 2008-09-28 20:16:08 UTC (rev 5872) @@ -126,6 +126,13 @@ body = [] if decl: body.append("int %s ();" % func) + # Handle MSVC intrisincs: force MS compiler to make a function call. + # Useful to test for some functions when built with optimization on, to + # avoid build error because the intrisinc and our 'fake' test + # declaration do not match. + body.append("#ifdef _MSC_VER") + body.append("#pragma function(%s)" % func) + body.append("#endif") body.append("int main (void) {") if call: if call_args is None: @@ -174,6 +181,12 @@ if v: body.append("int %s ();" % f) + # Handle MS intrinsics. See check_func for more info. + body.append("#ifdef _MSC_VER") + for func in funcs: + body.append("#pragma function(%s)" % func) + body.append("#endif") + body.append("int main (void) {") if call: for f in funcs: Modified: branches/clean_math_config_chuck/numpy/lib/io.py =================================================================== --- branches/clean_math_config_chuck/numpy/lib/io.py 2008-09-28 20:06:00 UTC (rev 5871) +++ branches/clean_math_config_chuck/numpy/lib/io.py 2008-09-28 20:16:08 UTC (rev 5872) @@ -378,7 +378,11 @@ # By preference, use the converters specified by the user for i, conv in (user_converters or {}).iteritems(): if usecols: - i = usecols.index(i) + try: + i = usecols.index(i) + except ValueError: + # Unused converter specified + continue converters[i] = conv # Parse each line, including the first Modified: branches/clean_math_config_chuck/numpy/lib/tests/test_io.py =================================================================== --- branches/clean_math_config_chuck/numpy/lib/tests/test_io.py 2008-09-28 20:06:00 UTC (rev 5871) +++ branches/clean_math_config_chuck/numpy/lib/tests/test_io.py 2008-09-28 20:16:08 UTC (rev 5872) @@ -258,6 +258,17 @@ 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() From numpy-svn at scipy.org Sun Sep 28 18:58:27 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 28 Sep 2008 17:58:27 -0500 (CDT) Subject: [Numpy-svn] r5873 - branches/clean_math_config_chuck Message-ID: <20080928225827.DC09639C0F1@scipy.org> Author: charris Date: 2008-09-28 17:58:24 -0500 (Sun, 28 Sep 2008) New Revision: 5873 Modified: branches/clean_math_config_chuck/ Log: Update . Property changes on: branches/clean_math_config_chuck ___________________________________________________________________ Name: svnmerge-integrated - /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5843 + /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5860 From numpy-svn at scipy.org Sun Sep 28 19:35:18 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 28 Sep 2008 18:35:18 -0500 (CDT) Subject: [Numpy-svn] r5874 - in branches/clean_math_config/numpy: core/src distutils Message-ID: <20080928233518.9141B39C0F1@scipy.org> Author: charris Date: 2008-09-28 18:35:15 -0500 (Sun, 28 Sep 2008) New Revision: 5874 Modified: branches/clean_math_config/numpy/core/src/arraytypes.inc.src branches/clean_math_config/numpy/distutils/conv_template.py Log: Enhance code_generator to allow continuation lines. Small clarification in arraytypes.inc.src. Practice merging ;) Modified: branches/clean_math_config/numpy/core/src/arraytypes.inc.src =================================================================== --- branches/clean_math_config/numpy/core/src/arraytypes.inc.src 2008-09-28 22:58:24 UTC (rev 5873) +++ branches/clean_math_config/numpy/core/src/arraytypes.inc.src 2008-09-28 23:35:15 UTC (rev 5874) @@ -664,7 +664,7 @@ #from=BYTE*13,UBYTE*13,SHORT*13,USHORT*13,INT*13,UINT*13,LONG*13,ULONG*13,LONGLONG*13,ULONGLONG*13,FLOAT*13,DOUBLE*13,LONGDOUBLE*13,CFLOAT*13,CDOUBLE*13,CLONGDOUBLE*13# #totyp=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*16# #fromtyp=byte*13, ubyte*13, short*13, ushort*13, int*13, uint*13, long*13, ulong*13, longlong*13, ulonglong*13, float*13, double*13, longdouble*13, float*13, double*13, longdouble*13# -#incr= ip++*169,ip+=2*39# +#incr= (ip++)*169,(ip+=2)*39# */ static void @from at _to_@to@(register @fromtyp@ *ip, register @totyp@ *op, register intp n, Modified: branches/clean_math_config/numpy/distutils/conv_template.py =================================================================== --- branches/clean_math_config/numpy/distutils/conv_template.py 2008-09-28 22:58:24 UTC (rev 5873) +++ branches/clean_math_config/numpy/distutils/conv_template.py 2008-09-28 23:35:15 UTC (rev 5874) @@ -128,19 +128,22 @@ numrep = obj.group(2) return ','.join([torep]*int(numrep)) -parenrep = re.compile(r"[(]([^)]*?)[)]\*(\d+)") +parenrep = re.compile(r"[(]([^)]*)[)]\*(\d+)") plainrep = re.compile(r"([^*]+)\*(\d+)") -def conv(astr): +def parse_values(astr): # replaces all occurrences of '(a,b,c)*4' in astr - # with 'a,b,c,a,b,c,a,b,c,a,b,c'. The result is + # with 'a,b,c,a,b,c,a,b,c,a,b,c'. Empty braces generate + # empty values, i.e., ()*4 yields ',,,'. The result is # split at ',' and a list of values returned. - astr = parenrep.sub(paren_repl,astr) + astr = parenrep.sub(paren_repl, astr) # replaces occurences of xxx*3 with xxx, xxx, xxx astr = ','.join([plainrep.sub(paren_repl,x.strip()) for x in astr.split(',')]) return astr.split(',') -named_re = re.compile(r"#\s*([\w]*)\s*=\s*([^#]*)#") + +stripast = re.compile(r"\n\s*\*?") +named_re = re.compile(r"#\s*(\w*)\s*=([^#]*)#") def parse_loop_header(loophead) : """Find all named replacements in the header @@ -149,23 +152,29 @@ value is the replacement string. """ + # Strip out '\n' and leading '*', if any, in continuation lines. + # This should not effect code previous to this change as + # continuation lines were not allowed. + loophead = stripast.sub("", loophead) # parse out the names and lists of values names = [] reps = named_re.findall(loophead) nsub = None for rep in reps: - name = rep[0].strip() - vals = conv(rep[1]) + name = rep[0] + vals = parse_values(rep[1]) size = len(vals) if nsub is None : nsub = size elif nsub != size : - msg = "Mismatch in number: %s - %s" % (name, vals) + msg = "Mismatch in number of values:\n%s = %s" % (name, vals) raise ValueError, msg names.append((name,vals)) # generate list of dictionaries, one for each template iteration dlist = [] + if nsub is None : + raise ValueError, "No substitution variables found" for i in range(nsub) : tmp = {} for name,vals in names : @@ -183,8 +192,8 @@ try : val = env[name] except KeyError, e : - msg = '%s: %s'%(lineno, e) - raise KeyError, msg + msg = 'line %d: %s'%(line, e) + raise ValueError, msg return val code = [lineno] @@ -203,7 +212,7 @@ try : envlist = parse_loop_header(head) except ValueError, e : - msg = "%s: %s" % (lineno, e) + msg = "line %d: %s" % (newline, e) raise ValueError, msg for newenv in envlist : newenv.update(env) @@ -249,7 +258,10 @@ def process_file(source): lines = resolve_includes(source) sourcefile = os.path.normcase(source).replace("\\","\\\\") - code = process_str(''.join(lines)) + try: + code = process_str(''.join(lines)) + except ValueError, e: + raise ValueError, '"%s", %s' % (sourcefile, e) return '#line 1 "%s"\n%s' % (sourcefile, code) @@ -284,5 +296,8 @@ outfile = open(newname,'w') allstr = fid.read() - writestr = process_str(allstr) + try: + writestr = process_str(allstr) + except ValueError, e: + raise ValueError, "file %s, %s" % (file, e) outfile.write(writestr) From numpy-svn at scipy.org Sun Sep 28 22:48:16 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Sun, 28 Sep 2008 21:48:16 -0500 (CDT) Subject: [Numpy-svn] r5875 - branches/clean_math_config_chuck/numpy/core/src Message-ID: <20080929024816.EDC3C39C344@scipy.org> Author: charris Date: 2008-09-28 21:48:14 -0500 (Sun, 28 Sep 2008) New Revision: 5875 Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src Log: Work in progress Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-28 23:35:15 UTC (rev 5874) +++ branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-29 02:48:14 UTC (rev 5875) @@ -454,6 +454,13 @@ intp n = dimensions[0];\ intp i;\ for(i = 0; i < n; i++, ip1 += is1, op += os) + +#define OUTPUT_LOOP\ + char *op = args[1];\ + intp os = steps[1];\ + intp n = dimensions[0];\ + intp i;\ + for(i = 0; i < n; i++, op += os) /* ***************************************************************************** ** BOOLEAN LOOPS ** @@ -462,20 +469,30 @@ /**begin repeat * #kind = equal, not_equal, greater, greater_equal, less, less_equal, - * logical_and, logical_or, logical_xor# - * #OP = ==, !=, >, >=, <, <=, &&, ||, ^# + * logical_and, logical_or# + * #OP = ==, !=, >, >=, <, <=, &&, ||# **/ static void BOOL_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { BINARY_LOOP { - Bool in1 = (*((Bool *)ip1) != 0); - Bool in2 = (*((Bool *)ip2) != 0); + Bool in1 = *((Bool *)ip1) != 0; + Bool in2 = *((Bool *)ip2) != 0; *((Bool *)op)= in1 @OP@ in2; } } /**end repeat**/ +static void +BOOL_logical_xor(char **args, intp *dimensions, intp *steps, void *func) +{ + BINARY_LOOP { + Bool in1 = *((Bool *)ip1) != 0; + Bool in2 = *((Bool *)ip2) != 0; + *((Bool *)op)= (in1 && !in2) || (!in1 && in2); + } +} + /**begin repeat * #kind = maximum, minimum# * #OP = >, <# @@ -484,8 +501,8 @@ BOOL_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { BINARY_LOOP { - Bool in1 = (*((Bool *)ip1) != 0); - Bool in2 = (*((Bool *)ip2) != 0); + Bool in1 = *((Bool *)ip1) != 0; + Bool in2 = *((Bool *)ip2) != 0; *((Bool *)op) = (in1 @OP@ in2) ? in1 : in2; } } @@ -508,7 +525,7 @@ static void BOOL_ones_like(char **args, intp *dimensions, intp *steps, void *data) { - UNARY_LOOP { + OUTPUT_LOOP { *((Bool *)op) = 1; } } @@ -542,28 +559,28 @@ */ static void - at S@@TYPE at _square(char **args, intp *dimensions, intp *steps, void *data) + at S@@TYPE at _ones_like(char **args, intp *dimensions, intp *steps, void *data) { - UNARY_LOOP { - const @s@@type@ in1 = *((@s@@type@ *)ip1); - *((@s@@type@ *)op) = in1*in1; + OUTPUT_LOOP { + *((@s@@type@ *)op) = 1; } } static void - at S@@TYPE at _reciprocal(char **args, intp *dimensions, intp *steps, void *data) + at S@@TYPE at _square(char **args, intp *dimensions, intp *steps, void *data) { UNARY_LOOP { - const @s@@type@ in1 = *((@s@@type@ *)ip1); - *((@s@@type@ *)op) = 1.0/in1; + const @s@@type@ in1 = *(@s@@type@ *)ip1; + *((@s@@type@ *)op) = in1*in1; } } static void - at S@@TYPE at _ones_like(char **args, intp *dimensions, intp *steps, void *data) + at S@@TYPE at _reciprocal(char **args, intp *dimensions, intp *steps, void *data) { UNARY_LOOP { - *((@s@@type@ *)op) = 1; + const @s@@type@ in1 = *(@s@@type@ *)ip1; + *((@s@@type@ *)op) = 1.0/in1; } } @@ -571,7 +588,7 @@ @S@@TYPE at _conjugate(char **args, intp *dimensions, intp *steps, void *func) { UNARY_LOOP { - const @s@@type@ in1 = *((@s@@type@ *)ip1); + const @s@@type@ in1 = *(@s@@type@ *)ip1; *((@s@@type@ *)op) = in1; } } @@ -580,7 +597,7 @@ @S@@TYPE at _negative(char **args, intp *dimensions, intp *steps, void *func) { UNARY_LOOP { - const @s@@type@ in1 = *((@s@@type@ *)ip1); + const @s@@type@ in1 = *(@s@@type@ *)ip1; *((@s@@type@ *)op) = (@s@@type@)(-(@type@)in1); } } @@ -589,11 +606,20 @@ @S@@TYPE at _logical_not(char **args, intp *dimensions, intp *steps, void *func) { UNARY_LOOP { - const @s@@type@ in1 = *((@s@@type@ *)ip1); + const @s@@type@ in1 = *(@s@@type@ *)ip1; *((Bool *)op) = !in1; } } +static void + at S@@TYPE at _invert(char **args, intp *dimensions, intp *steps, void *func) +{ + UNARY_LOOP { + const @s@@type@ in1 = *(@s@@type@ *)ip1; + *((@s@@type@ *)op) = ~in1; + } +} + /**begin repeat2 * Arithmetic * #kind = add, subtract, multiply, bitwise_and, bitwise_or, bitwise_xor, @@ -628,6 +654,31 @@ /**end repeat2**/ static void + at S@@TYPE at _logical_xor(char **args, intp *dimensions, intp *steps, void *func) +{ + BINARY_LOOP { + const @s@@type@ in1 = *(@s@@type@ *)ip1; + const @s@@type@ in2 = *(@s@@type@ *)ip2; + *((Bool *)op)= (in1 && !in2) || (!in1 && in2); + } +} + +/**begin repeat2 + * #kind = maximum, minimum# + * #OP = >, <# + **/ +static void + at S@@TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) +{ + BINARY_LOOP { + const @s@@type@ in1 = *(@s@@type@ *)ip1; + const @s@@type@ in2 = *(@s@@type@ *)ip2; + *((@s@@type@ *)op) = (in1 @OP@ in2) ? in1 : in2; + } +} +/**end repeat2**/ + +static void @S@@TYPE at _true_divide(char **args, intp *dimensions, intp *steps, void *func) { BINARY_LOOP { @@ -647,8 +698,8 @@ @S@@TYPE at _power(char **args, intp *dimensions, intp *steps, void *func) { BINARY_LOOP { - const @ftype@ in1 = (@ftype@)*((@s@@type@ *)ip1); - const @ftype@ in2 = (@ftype@)*((@s@@type@ *)ip2); + const @ftype@ in1 = (@ftype@)*(@s@@type@ *)ip1; + const @ftype@ in2 = (@ftype@)*(@s@@type@ *)ip2; *((@s@@type@ *)op) = (@s@@type@) pow(in1, in2); } } @@ -658,7 +709,7 @@ U at TYPE@_absolute(char **args, intp *dimensions, intp *steps, void *func) { UNARY_LOOP { - const u at type@ in1 = *((u at type@ *)ip1); + const u at type@ in1 = *(u at type@ *)ip1; *((u at type@ *)op) = in1; } } @@ -667,9 +718,8 @@ @TYPE at _absolute(char **args, intp *dimensions, intp *steps, void *func) { UNARY_LOOP { - const @type@ in1 = *((@type@ *)ip1); + const @type@ in1 = *(@type@ *)ip1; *((@type@ *)op) = (in1 > 0) ? in1 : -in1; - *((@type@ *)op) += 0; /* fixme clear sign-bit ? */ } } @@ -728,79 +778,93 @@ /**begin repeat1 * Arithmetic - * # OP = +, -, *, /# * # kind = add, subtract, multiply, divide# + * # OP = +, -, *, /# */ static void @TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) { - intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i, >=, ==, !=, &&, ||# + * #OP = ==, !=, <, <=, >, >=, &&, ||# */ static void @TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) { - intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i, <# + **/ +static void + at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) +{ + BINARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + const @type@ in2 = *(@type@ *)ip2; + *((@type@ *)op) = (in1 @OP@ in2) ? in1 : in2; + } +} +/**end repeat1**/ + +static void @TYPE at _floor_divide(char **args, intp *dimensions, intp *steps, void *func) { - intp i, is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i*13, <*13# - #typ=(byte, ubyte, short, ushort, int, uint, long, ulong, longlong, ulonglong, float, double, longdouble)*2# - #kind= maximum*13, minimum*13# -*/ -static void - at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i*3, <*3# #typ=(cfloat, cdouble, clongdouble)*2# From numpy-svn at scipy.org Mon Sep 29 03:14:25 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 29 Sep 2008 02:14:25 -0500 (CDT) Subject: [Numpy-svn] r5876 - branches/clean_math_config_chuck/numpy/core/src Message-ID: <20080929071425.ED61039C089@scipy.org> Author: charris Date: 2008-09-29 02:14:21 -0500 (Mon, 29 Sep 2008) New Revision: 5876 Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src Log: Work in progress. Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-29 02:48:14 UTC (rev 5875) +++ branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-29 07:14:21 UTC (rev 5876) @@ -703,6 +703,24 @@ *((@s@@type@ *)op) = (@s@@type@) pow(in1, in2); } } + +static void + at S@@TYPE at _fmod(char **args, intp *dimensions, intp *steps, void *func) +{ + BINARY_LOOP { + const @s@@type@ in1 = *(@s@@type@ *)ip1; + const @s@@type@ in2 = *(@s@@type@ *)ip2; + if (in2 == 0) { + generate_divbyzero_error(); + *((@s@@type@ *)op) = 0; + } + else { + *((@s@@type@ *)op)= in1 % in2; + } + + } +} + /**end repeat1**/ static void @@ -724,6 +742,24 @@ } static void +U at TYPE@_sign(char **args, intp *dimensions, intp *steps, void *func) +{ + UNARY_LOOP { + const u at type@ in1 = *(u at type@ *)ip1; + *((u at type@ *)op) = in1 > 0 ? 1 : 0; + } +} + +static void + at TYPE@_sign(char **args, intp *dimensions, intp *steps, void *func) +{ + UNARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + *((@type@ *)op) = in1 > 0 ? 1 : (in1 < 0 ? -1 : 0); + } +} + +static void @TYPE at _divide(char **args, intp *dimensions, intp *steps, void *func) { BINARY_LOOP { @@ -758,6 +794,45 @@ } } +static void + at TYPE@_remainder(char **args, intp *dimensions, intp *steps, void *func) +{ + BINARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + const @type@ in2 = *(@type@ *)ip2; + if (in2 == 0) { + generate_divbyzero_error(); + *((@type@ *)op) = 0; + } + else { + /* handle mixed case the way Python does */ + const @type@ rem = in1 % in2; + if ((in1 > 0) == (in2 > 0) || rem == 0) { + *((@type@ *)op) = rem; + } + else { + *((@type@ *)op) = rem + in2; + } + } + } +} + +static void +U at TYPE@_remainder(char **args, intp *dimensions, intp *steps, void *func) +{ + BINARY_LOOP { + const u at type@ in1 = *(u at type@ *)ip1; + const u at type@ in2 = *(u at type@ *)ip2; + if (in2 == 0) { + generate_divbyzero_error(); + *((@type@ *)op) = 0; + } + else { + *((@type@ *)op) = in1 % in2; + } + } +} + #define @TYPE at _floor_divide @TYPE at _divide #define U at TYPE@_floor_divide U at TYPE@_divide /**end repeat**/ @@ -844,6 +919,22 @@ } static void + at TYPE@_remainder(char **args, intp *dimensions, intp *steps, void *func) +{ + BINARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + const @type@ in2 = *(@type@ *)ip2; + const @type@ res = fmod at c@(in1,in2); + if (res && ((in2 < 0) != (res < 0))) { + *((@type@ *)op) = res + in2; + } + else { + *((@type@ *)op) = res; + } + } +} + +static void @TYPE at _square(char **args, intp *dimensions, intp *steps, void *data) { UNARY_LOOP { @@ -905,6 +996,15 @@ } } +static void + at TYPE@_sign(char **args, intp *dimensions, intp *steps, void *func) +{ + UNARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + *((@type@ *)op) = in1 > 0 ? 1 : (in1 < 0 ? -1 : 0); + } +} + #define @TYPE at _true_divide @TYPE at _divide /**end repeat**/ @@ -925,127 +1025,173 @@ /**begin repeat1 * arithmetic - * #OP = +, -# * #kind = add, subtract# + * #OP = +, -# */ static void @CTYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) { - intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i, >=, <, <=# + */ static void - at CTYPE@_multiply(char **args, intp *dimensions, intp *steps, void *func) + at CTYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { - register intp i; - intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for (i=0; ireal; - @type@ ai=((@ctype@ *)i1)->imag; - @type@ br=((@ctype@ *)i2)->real; - @type@ bi=((@ctype@ *)i2)->imag; - ((@ctype@ *)op)->real = ar*br - ai*bi; - ((@ctype@ *)op)->imag = ar*bi + ai*br; + BINARY_LOOP { + const @type@ in1r = ((@type@ *)ip1)[0]; + const @type@ in1i = ((@type@ *)ip1)[1]; + const @type@ in2r = ((@type@ *)ip2)[0]; + const @type@ in2i = ((@type@ *)ip2)[1]; + if (in1r != in2r) { + *((Bool *)op) = in1r @OP@ in2r ? 1 : 0; + } + else { + *((Bool *)op) = in1i @OP@ in2i ? 1 : 0; + } } } +/**end repeat1**/ +/**begin repeat1 + #kind = logical_and, logical_or# + #OP1 = ||, ||# + #OP2 = &&, ||# +*/ static void - at CTYPE@_divide(char **args, intp *dimensions, intp *steps, void *func) + at CTYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { - register intp i; - intp is1=steps[0], is2=steps[1], os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for (i=0; ireal; - @type@ ai=((@ctype@ *)i1)->imag; - @type@ br=((@ctype@ *)i2)->real; - @type@ bi=((@ctype@ *)i2)->imag; - @type@ d = br*br + bi*bi; - ((@ctype@ *)op)->real = (ar*br + ai*bi)/d; - ((@ctype@ *)op)->imag = (ai*br - ar*bi)/d; + BINARY_LOOP { + const @type@ in1r = ((@type@ *)ip1)[0]; + const @type@ in1i = ((@type@ *)ip1)[1]; + const @type@ in2r = ((@type@ *)ip2)[0]; + const @type@ in2i = ((@type@ *)ip2)[1]; + *((Bool *)op) = (in1r @OP1@ in1i) @OP2@ (in2r @OP1@ in2i); } } +/**end repeat1**/ static void - at CTYPE@_floor_divide(char **args, intp *dimensions, intp *steps, void *func) + at CTYPE@_logical_xor(char **args, intp *dimensions, intp *steps, void *func) { - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2],n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; ireal; - @type@ ai=((@ctype@ *)i1)->imag; - @type@ br=((@ctype@ *)i2)->real; - @type@ bi=((@ctype@ *)i2)->imag; - @type@ d = br*br + bi*bi; - ((@ctype@ *)op)->real = floor at c@((ar*br + ai*bi)/d); - ((@ctype@ *)op)->imag = 0; + BINARY_LOOP { + const @type@ in1r = ((@type@ *)ip1)[0]; + const @type@ in1i = ((@type@ *)ip1)[1]; + const @type@ in2r = ((@type@ *)ip2)[0]; + const @type@ in2i = ((@type@ *)ip2)[1]; + const Bool tmp1 = (in1r || in1i); + const Bool tmp2 = (in2r || in2i); + *((Bool *)op) = (tmp1 && !tmp2) || (!tmp1 && tmp2); } } static void - at CTYPE@_square(char **args, intp *dimensions, intp *steps, void *data) + at CTYPE@_logical_not(char **args, intp *dimensions, intp *steps, void *func) { - intp i, is1 = steps[0], os = steps[1], n = dimensions[0]; - char *i1 = args[0], *op = args[1]; + UNARY_LOOP { + const @type@ in1r = ((@type@ *)ip1)[0]; + const @type@ in1i = ((@type@ *)ip1)[1]; + *((Bool *)op) = !(in1r || in1i); + } +} - for (i = 0; i < n; i++, i1 += is1, op += os) { - @ctype@ *x = (@ctype@ *)i1; - @ctype@ *y = (@ctype@ *)op; - @type@ xr = x->real; - @type@ xi = x->imag; - y->real = xr*xr - xi*xi; - y->imag = 2*xr*xi; +static void + at CTYPE@_square(char **args, intp *dimensions, intp *steps, void *data) +{ + UNARY_LOOP { + const @type@ in1r = ((@type@ *)ip1)[0]; + const @type@ in1i = ((@type@ *)ip1)[1]; + ((@type@ *)op)[0] = in1r*in1r - in1i*in1i; + ((@type@ *)op)[1] = in1r*in1i + in1i*in1r; } } -/* fixme -- need type specific fabs */ static void @CTYPE at _reciprocal(char **args, intp *dimensions, intp *steps, void *data) { - intp i, is1 = steps[0], os = steps[1], n = dimensions[0]; - char *i1 = args[0], *op = args[1]; - - for (i = 0; i < n; i++, i1 += is1, op += os) { - @ctype@ *x = (@ctype@ *)i1; - @ctype@ *y = (@ctype@ *)op; - @type@ xr = x->real; - @type@ xi = x->imag; - if (fabs(xi) <= fabs(xr)) { - @type@ r = xi/xr; - @type@ denom = xr + xi*r; - y->real = 1/denom; - y->imag = -r/denom; + UNARY_LOOP { + const @type@ in1r = ((@type@ *)ip1)[0]; + const @type@ in1i = ((@type@ *)ip1)[1]; + if (fabs at c@(in1i) <= fabs at c@(in1r)) { + const @type@ r = in1i/in1r; + const @type@ d = in1r + in1i*r; + ((@type@ *)op)[0] = 1/d; + ((@type@ *)op)[1] = -r/d; } else { - @type@ r = xr/xi; - @type@ denom = xr*r + xi; - y->real = r/denom; - y->imag = -1/denom; + const @type@ r = in1r/in1i; + const @type@ d = in1r*r + in1i; + ((@type@ *)op)[0] = r/d; + ((@type@ *)op)[1] = -1/d; } } } @@ -1053,72 +1199,74 @@ static void @CTYPE at _ones_like(char **args, intp *dimensions, intp *steps, void *data) { - intp i, is1 = steps[0], os = steps[1], n = dimensions[0]; - char *i1 = args[0], *op = args[1]; - @ctype@ *y; - - for (i = 0; i < n; i++, i1 += is1, op += os) { - y = (@ctype@ *)op; - y->real = 1.0; - y->imag = 0.0; + OUTPUT_LOOP { + ((@type@ *)op)[0] = 1; + ((@type@ *)op)[1] = 0; } } static void @CTYPE at _conjugate(char **args, intp *dimensions, intp *steps, void *func) { - intp i, is1=steps[0], os=steps[1], n=dimensions[0]; - char *i1=args[0], *op=args[1]; - - for(i=0; i, >=, <, <=# - */ static void - at CTYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) + at CTYPE@_sign(char **args, intp *dimensions, intp *steps, void *func) { - intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; ireal == ((c at type@ *)i2)->real) - *((Bool *)op)=((c at type@ *)i1)->imag @OP@ - ((c at type@ *)i2)->imag; - else - *((Bool *)op)=((c at type@ *)i1)->real @OP@ - ((c at type@ *)i2)->real; + UNARY_LOOP { + const @type@ in1r = ((@type@ *)ip1)[0]; + const @type@ in1i = ((@type@ *)ip1)[1]; + if (in1r != 0) { + ((@type@ *)op)[0] = in1r > 0 ? 1 : -1; + } + else if (in1i != 0) { + ((@type@ *)op)[0] = in1i > 0 ? 1 : -1; + } + else { + ((@type@ *)op)[0] = 0; + } + ((@type@ *)op)[1] = 0; } } -/**end repeat1**/ +/**begin repeat1 + * #kind = maximum, minimum# + * #OP = >, <# + */ static void - at CTYPE@_logical_not(char **args, intp *dimensions, intp *steps, void *func) + at CTYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { - intp i; - intp is1=steps[0],os=steps[1], n=dimensions[0]; - char *i1=args[0], *op=args[1]; - for(i=0; ireal || - ((@ctype@ *)i1)->imag); + BINARY_LOOP { + const @type@ in1r = ((@type@ *)ip1)[0]; + const @type@ in1i = ((@type@ *)ip1)[1]; + const @type@ in2r = ((@type@ *)ip2)[0]; + const @type@ in2i = ((@type@ *)ip2)[1]; + if (in1r @OP@ in2r || ((in1r == in2r) && (in1i @OP@ in2i))) { + ((@type@ *)op)[0] = in1r; + ((@type@ *)op)[1] = in1i; + } + else { + ((@type@ *)op)[0] = in2r; + ((@type@ *)op)[1] = in2i; + } } } +/**end repeat1**/ #define @CTYPE at _true_divide @CTYPE at _divide /**end repeat**/ @@ -1210,55 +1358,8 @@ ***************************************************************************** */ -/*sign*/ -#define _SIGN1(x) ((x) > 0 ? 1 : ((x) < 0 ? -1 : 0)) -#define _SIGN2(x) ((x) == 0 ? 0 : 1) -#define _SIGNC(x) (((x).real > 0) ? 1 : ((x).real < 0 ? -1 : ((x).imag > 0 ? 1 : ((x).imag < 0) ? -1 : 0))) -/**begin repeat - #TYPE=BYTE,SHORT,INT,LONG,LONGLONG,FLOAT,DOUBLE,LONGDOUBLE,UBYTE,USHORT,UINT,ULONG,ULONGLONG# - #typ=byte,short,int,long,longlong,float,double,longdouble,ubyte,ushort,uint,ulong,ulonglong# - #func=_SIGN1*8,_SIGN2*5# -*/ -static void - at TYPE@_sign(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],os=steps[1], n=dimensions[0]; - char *i1=args[0], *op=args[1]; - @typ@ t1; - for(i=0; i 0) == (iy > 0)) { - *((@typ@ *)op) = ix % iy; - } - else { /* handle mixed case the way Python does */ - tmp = ix % iy; - if (tmp) tmp += iy; - *((@typ@ *)op)= tmp; - } - } -} -/**end repeat**/ - -/**begin repeat - #TYPE=UBYTE,USHORT,UINT,ULONG,ULONGLONG# - #typ=ubyte, ushort, uint, ulong, ulonglong# -*/ -static void - at TYPE@_remainder(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - register @typ@ ix,iy; - for(i=0; ireal || ((@typ@ *)i1)->imag; - p2 = ((@typ@ *)i2)->real || ((@typ@ *)i2)->imag; - *((Bool *)op)= (p1 || p2) && !(p1 && p2); - } -} -/**end repeat**/ - - -/*max,min*/ -/**begin repeat - - #TYPE=(CFLOAT,CDOUBLE,CLONGDOUBLE)*2# - #OP= >*3, <*3# - #typ=(cfloat, cdouble, clongdouble)*2# - #kind= maximum*3, minimum*3# -*/ -static void - at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) -{ - register intp i; - intp is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - @typ@ *i1c, *i2c; - for(i=0; ireal @OP@ i2c->real) || \ - ((i1c->real==i2c->real) && (i1c->imag @OP@ i2c->imag))) - memmove(op, i1, sizeof(@typ@)); - else - memmove(op, i2, sizeof(@typ@)); - } -} -/**end repeat**/ - - - /*** isinf, isinf, isfinite, signbit ***/ /**begin repeat #kind=isnan*3, isinf*3, isfinite*3, signbit*3# From numpy-svn at scipy.org Mon Sep 29 12:20:50 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 29 Sep 2008 11:20:50 -0500 (CDT) Subject: [Numpy-svn] r5877 - branches/clean_math_config_chuck/numpy/core/src Message-ID: <20080929162050.151A139C2F8@scipy.org> Author: charris Date: 2008-09-29 11:20:47 -0500 (Mon, 29 Sep 2008) New Revision: 5877 Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src Log: Work in progress Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-29 07:14:21 UTC (rev 5876) +++ branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-29 16:20:47 UTC (rev 5877) @@ -50,16 +50,72 @@ /* ***************************************************************************** + ** PYTHON OBJECT FUNCTIONS ** + ***************************************************************************** + */ + +static PyObject * +Py_square(PyObject *o) +{ + return PyNumber_Multiply(o, o); +} + +static PyObject * +Py_get_one(PyObject *o) +{ + return PyInt_FromLong(1); +} + +static PyObject * +Py_reciprocal(PyObject *o) +{ + PyObject *one = PyInt_FromLong(1); + PyObject *result; + + if (!one) { + return NULL; + } + result = PyNumber_Divide(one, o); + Py_DECREF(one); + return result; +} + +/**begin repeat + * #Kind = Max, Min# + * #OP = >=, <=# + */ +static PyObject * +_npy_Object at Kind@(PyObject *i1, PyObject *i2) +{ + PyObject *result; + int cmp; + + if (PyObject_Cmp(i1, i2, &cmp) < 0) { + return NULL; + } + if (cmp @OP@ 0) { + result = i1; + } + else { + result = i2; + } + Py_INCREF(result); + return result; +} +/**end repeat**/ + +/* + ***************************************************************************** ** COMPLEX FUNCTIONS ** ***************************************************************************** */ /* Don't pass structures between functions (only pointers) because how - structures are passed is compiler dependent and could cause - segfaults if ufuncobject.c is compiled with a different compiler - than an extension that makes use of the UFUNC API -*/ + * structures are passed is compiler dependent and could cause + * segfaults if ufuncobject.c is compiled with a different compiler + * than an extension that makes use of the UFUNC API + */ /**begin repeat @@ -73,10 +129,11 @@ static c at typ@ nc_i at c@ = {0., 1.}; static c at typ@ nc_i2 at c@ = {0., 0.5}; /* - static c at typ@ nc_mi at c@ = {0., -1.}; - static c at typ@ nc_pi2 at c@ = {M_PI/2., 0.}; -*/ + * static c at typ@ nc_mi at c@ = {0., -1.}; + * static c at typ@ nc_pi2 at c@ = {M_PI/2., 0.}; + */ + static void nc_sum at c@(c at typ@ *a, c at typ@ *b, c at typ@ *r) { @@ -104,7 +161,7 @@ static void nc_prod at c@(c at typ@ *a, c at typ@ *b, c at typ@ *r) { - register @typ@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag; + @typ@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag; r->real = ar*br - ai*bi; r->imag = ar*bi + ai*br; return; @@ -114,8 +171,8 @@ nc_quot at c@(c at typ@ *a, c at typ@ *b, c at typ@ *r) { - register @typ@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag; - register @typ@ d = br*br + bi*bi; + @typ@ ar=a->real, br=b->real, ai=a->imag, bi=b->imag; + @typ@ d = br*br + bi*bi; r->real = (ar*br + ai*bi)/d; r->imag = (ai*br - ar*bi)/d; return; @@ -224,8 +281,10 @@ return; } } - /* complexobect.c uses an inline version of this formula - investigate whether this had better performance or accuracy */ + /* + * complexobect.c uses an inline version of this formula + * investigate whether this had better performance or accuracy + */ nc_log at c@(a, r); nc_prod at c@(r, b, r); nc_exp at c@(r, r); @@ -246,6 +305,10 @@ static void nc_acos at c@(c at typ@ *x, c at typ@ *r) { + /* + * return nc_neg(nc_prodi(nc_log(nc_sum(x,nc_prod(nc_i, + * nc_sqrt(nc_diff(nc_1,nc_prod(x,x)))))))); + */ nc_prod at c@(x,x,r); nc_diff at c@(&nc_1 at c@, r, r); nc_sqrt at c@(r, r); @@ -255,14 +318,15 @@ nc_prodi at c@(r, r); nc_neg at c@(r, r); return; - /* return nc_neg(nc_prodi(nc_log(nc_sum(x,nc_prod(nc_i, - nc_sqrt(nc_diff(nc_1,nc_prod(x,x)))))))); - */ } static void nc_acosh at c@(c at typ@ *x, c at typ@ *r) { + /* + * return nc_log(nc_sum(x, + * nc_prod(nc_sqrt(nc_sum(x,nc_1)), nc_sqrt(nc_diff(x,nc_1))))); + */ c at typ@ t; nc_sum at c@(x, &nc_1 at c@, &t); @@ -273,15 +337,15 @@ nc_sum at c@(x, r, r); nc_log at c@(r, r); return; - /* - return nc_log(nc_sum(x, - nc_prod(nc_sqrt(nc_sum(x,nc_1)), nc_sqrt(nc_diff(x,nc_1))))); - */ } static void nc_asin at c@(c at typ@ *x, c at typ@ *r) { + /* + * return nc_neg(nc_prodi(nc_log(nc_sum(nc_prod(nc_i,x), + * nc_sqrt(nc_diff(nc_1,nc_prod(x,x))))))); + */ c at typ@ a, *pa=&a; nc_prod at c@(x, x, r); nc_diff at c@(&nc_1 at c@, r, r); @@ -292,30 +356,29 @@ nc_prodi at c@(r, r); nc_neg at c@(r, r); return; - /* - return nc_neg(nc_prodi(nc_log(nc_sum(nc_prod(nc_i,x), - nc_sqrt(nc_diff(nc_1,nc_prod(x,x))))))); - */ } static void nc_asinh at c@(c at typ@ *x, c at typ@ *r) { + /* + * return nc_log(nc_sum(nc_sqrt(nc_sum(nc_1,nc_prod(x,x))),x)); + */ nc_prod at c@(x, x, r); nc_sum at c@(&nc_1 at c@, r, r); nc_sqrt at c@(r, r); nc_sum at c@(r, x, r); nc_log at c@(r, r); return; - /* - return nc_log(nc_sum(nc_sqrt(nc_sum(nc_1,nc_prod(x,x))),x)); - */ } static void nc_atan at c@(c at typ@ *x, c at typ@ *r) { + /* + * return nc_prod(nc_i2,nc_log(nc_quot(nc_sum(nc_i,x),nc_diff(nc_i,x)))); + */ c at typ@ a, *pa=&a; nc_diff at c@(&nc_i at c@, x, pa); nc_sum at c@(&nc_i at c@, x, r); @@ -323,14 +386,14 @@ nc_log at c@(r,r); nc_prod at c@(&nc_i2 at c@, r, r); return; - /* - return nc_prod(nc_i2,nc_log(nc_quot(nc_sum(nc_i,x),nc_diff(nc_i,x)))); - */ } static void nc_atanh at c@(c at typ@ *x, c at typ@ *r) { + /* + * return nc_prod(nc_half,nc_log(nc_quot(nc_sum(nc_1,x),nc_diff(nc_1,x)))); + */ c at typ@ a, *pa=&a; nc_diff at c@(&nc_1 at c@, x, r); nc_sum at c@(&nc_1 at c@, x, pa); @@ -338,9 +401,6 @@ nc_log at c@(r, r); nc_prod at c@(&nc_half at c@, r, r); return; - /* - return nc_prod(nc_half,nc_log(nc_quot(nc_sum(nc_1,x),nc_diff(nc_1,x)))); - */ } static void @@ -441,12 +501,12 @@ ***************************************************************************** */ -#define BINARY_LOOP\ - char *ip1 = args[0], *ip2 = args[1], *op = args[2];\ - intp is1 = steps[0], is2 = steps[1], os = steps[2];\ +#define OUTPUT_LOOP\ + char *op = args[1];\ + intp os = steps[1];\ intp n = dimensions[0];\ intp i;\ - for(i = 0; i < n; i++, ip1 += is1, ip2 += is2, op += os) + for(i = 0; i < n; i++, op += os) #define UNARY_LOOP\ char *ip1 = args[0], *op = args[1];\ @@ -455,23 +515,48 @@ intp i;\ for(i = 0; i < n; i++, ip1 += is1, op += os) -#define OUTPUT_LOOP\ - char *op = args[1];\ - intp os = steps[1];\ +#define UNARY_LOOP_TWO_OUT\ + char *ip1 = args[0], *op1 = args[1], *op2 = args[2];\ + intp is1 = steps[0], os1 = steps[1], os2 = steps[2];\ intp n = dimensions[0];\ intp i;\ - for(i = 0; i < n; i++, op += os) + for(i = 0; i < n; i++, ip1 += is1, op1 += os1, op2 += os2) + +#define BINARY_LOOP\ + char *ip1 = args[0], *ip2 = args[1], *op = args[2];\ + intp is1 = steps[0], is2 = steps[1], os = steps[2];\ + intp n = dimensions[0];\ + intp i;\ + for(i = 0; i < n; i++, ip1 += is1, ip2 += is2, op += os) + +#define BINARY_LOOP_TWO_OUT\ + char *ip1 = args[0], *ip2 = args[1], *op1 = args[2], *op2 = args[3];\ + intp is1 = steps[0], is2 = steps[1], os1 = steps[2], os2 = steps[3];\ + intp n = dimensions[0];\ + intp i;\ + for(i = 0; i < n; i++, ip1 += is1, ip2 += is2, op1 += os1, op2 += os2) + /* ***************************************************************************** ** BOOLEAN LOOPS ** ***************************************************************************** */ +#define BOOL_invert BOOL_logical_not +#define BOOL_negative BOOL_logical_not +#define BOOL_add BOOL_logical_or +#define BOOL_bitwise_and BOOL_logical_and +#define BOOL_bitwise_or BOOL_logical_or +#define BOOL_bitwise_xor BOOL_logical_xor +#define BOOL_multiply BOOL_logical_and +#define BOOL_subtract BOOL_logical_xor + /**begin repeat * #kind = equal, not_equal, greater, greater_equal, less, less_equal, * logical_and, logical_or# * #OP = ==, !=, >, >=, <, <=, &&, ||# **/ + static void BOOL_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { @@ -530,16 +615,7 @@ } } -#define BOOL_invert BOOL_logical_not -#define BOOL_negative BOOL_logical_not -#define BOOL_add BOOL_logical_or -#define BOOL_bitwise_and BOOL_logical_and -#define BOOL_bitwise_or BOOL_logical_or -#define BOOL_bitwise_xor BOOL_logical_xor -#define BOOL_multiply BOOL_logical_and -#define BOOL_subtract BOOL_logical_xor - /* ***************************************************************************** ** INTEGER LOOPS @@ -554,10 +630,12 @@ /**begin repeat1 * both signed and unsigned integer types - * # s = , u# - * # S = , U# + * #s = , u# + * #S = , U# */ +#define @S@@TYPE at _floor_divide @S@@TYPE at _divide + static void @S@@TYPE at _ones_like(char **args, intp *dimensions, intp *steps, void *data) { @@ -833,8 +911,6 @@ } } -#define @TYPE at _floor_divide @TYPE at _divide -#define U at TYPE@_floor_divide U at TYPE@_divide /**end repeat**/ /* @@ -849,6 +925,7 @@ * #type = float, double, longdouble# * #TYPE = FLOAT, DOUBLE, LONGDOUBLE# * #c = f, , l# + * #C = F, , L# */ /**begin repeat1 @@ -894,6 +971,20 @@ } /**begin repeat1 + * #kind = isnan, isinf, isfinite, signbit# + * #func = isnan, isinf, isfinite, signbit# + **/ +static void + at TYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) +{ + UNARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + *((Bool *)op) = @func@(in1) != 0; + } +} +/**end repeat1**/ + +/**begin repeat1 * #kind = maximum, minimum# * #OP = >, <# **/ @@ -1005,7 +1096,40 @@ } } +static void + at TYPE@_modf(char **args, intp *dimensions, intp *steps, void *func) +{ + UNARY_LOOP_TWO_OUT { + const @type@ in1 = *(@type@ *)ip1; + *(@type@ *)op1 = modf at c@(in1, (@type@ *)op2); + } +} + +#ifdef HAVE_FREXP at C@ +static void + at TYPE@_frexp(char **args, intp *dimensions, intp *steps, void *func) +{ + UNARY_LOOP_TWO_OUT { + const @type@ in1 = *(@type@ *)ip1; + *(@type@ *)op1 = frexp at c@(in1, (int *)op2); + } +} +#endif + +#ifdef HAVE_LDEXP at C@ +static void + at TYPE@_ldexp(char **args, intp *dimensions, intp *steps, void *func) +{ + BINARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + const int in2 = *(int *)ip2; + *(@type@ *)op = ldexp at c@(in1, in2); + } +} +#endif + #define @TYPE at _true_divide @TYPE at _divide + /**end repeat**/ @@ -1165,7 +1289,23 @@ } } +/**begin repeat1 + * #kind = isnan, isinf, isfinite# + * #func = isnan, isinf, isfinite# + * #OP = ||, ||, &&# + **/ static void + at CTYPE@_ at kind@(char **args, intp *dimensions, intp *steps, void *func) +{ + UNARY_LOOP { + const @type@ in1r = ((@type@ *)ip1)[0]; + const @type@ in1i = ((@type@ *)ip1)[1]; + *((Bool *)op) = @func@(in1r) @OP@ @func@(in1i); + } +} +/**end repeat1**/ + +static void @CTYPE at _square(char **args, intp *dimensions, intp *steps, void *data) { UNARY_LOOP { @@ -1278,213 +1418,38 @@ ***************************************************************************** */ -static PyObject * -Py_square(PyObject *o) -{ - return PyNumber_Multiply(o, o); -} - -static PyObject * -Py_get_one(PyObject *o) -{ - return PyInt_FromLong(1); -} - -static PyObject * -Py_reciprocal(PyObject *o) -{ - PyObject *one, *result; - one = PyInt_FromLong(1); - if (!one) return NULL; - result = PyNumber_Divide(one, o); - Py_DECREF(one); - return result; -} - -static PyObject * -_npy_ObjectMax(PyObject *i1, PyObject *i2) -{ - int cmp; - PyObject *res; - if (PyObject_Cmp(i1, i2, &cmp) < 0) return NULL; - - if (cmp >= 0) { - res = i1; - } - else { - res = i2; - } - Py_INCREF(res); - return res; -} - -static PyObject * -_npy_ObjectMin(PyObject *i1, PyObject *i2) -{ - int cmp; - PyObject *res; - if (PyObject_Cmp(i1, i2, &cmp) < 0) return NULL; - - if (cmp <= 0) { - res = i1; - } - else { - res = i2; - } - Py_INCREF(res); - return res; -} - /**begin repeat - - #kind=greater, greater_equal, less, less_equal, equal, not_equal# - #op=GT, GE, LT, LE, EQ, NE# -*/ + * #kind = equal, not_equal, greater, greater_equal, less, less_equal# + * #OP = EQ, NE, GT, GE, LT, LE# + */ static void OBJECT_ at kind@(char **args, intp *dimensions, intp *steps, void *func) { - register intp i, is1=steps[0],is2=steps[1],os=steps[2], n=dimensions[0]; - char *i1=args[0], *i2=args[1], *op=args[2]; - for(i=0; i Author: ptvirtan Date: 2008-09-29 12:23:43 -0500 (Mon, 29 Sep 2008) New Revision: 5878 Modified: trunk/numpy/core/tests/test_umath.py Log: Umath tests: remove signed zero check on branch cut for log* as it fails on some platforms. Modified: trunk/numpy/core/tests/test_umath.py =================================================================== --- trunk/numpy/core/tests/test_umath.py 2008-09-29 16:20:47 UTC (rev 5877) +++ trunk/numpy/core/tests/test_umath.py 2008-09-29 17:23:43 UTC (rev 5878) @@ -205,9 +205,9 @@ def test_branch_cuts(self): # check branch cuts and continuity on them - yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True - yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True - yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True + yield _check_branch_cut, np.log, -0.5, 1j, 1, -1 + yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1 + yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1 yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1 yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, -1j], 1, -1 @@ -229,6 +229,11 @@ @dec.knownfailureif(True, "These branch cuts are known to fail") def test_branch_cuts_failing(self): + # XXX: signed zero not OK with ICC on 64-bit platform for log, see + # http://permalink.gmane.org/gmane.comp.python.numeric.general/25335 + yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True + yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True + yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True # XXX: signed zeros are not OK for sqrt or for the arc* functions yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, -1j], 1, -1, True From numpy-svn at scipy.org Mon Sep 29 16:24:33 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 29 Sep 2008 15:24:33 -0500 (CDT) Subject: [Numpy-svn] r5879 - trunk/numpy/ma Message-ID: <20080929202433.B819D39C0EA@scipy.org> Author: pierregm Date: 2008-09-29 15:24:29 -0500 (Mon, 29 Sep 2008) New Revision: 5879 Modified: trunk/numpy/ma/testutils.py Log: use if ...: raise AssertionError instead of assert Modified: trunk/numpy/ma/testutils.py =================================================================== --- trunk/numpy/ma/testutils.py 2008-09-29 17:23:43 UTC (rev 5878) +++ trunk/numpy/ma/testutils.py 2008-09-29 20:24:29 UTC (rev 5879) @@ -81,10 +81,12 @@ """ # Case #1: dictionary ..... if isinstance(desired, dict): - assert isinstance(actual, dict), repr(type(actual)) + if not isinstance(actual, dict): + raise AssertionError(repr(type(actual))) assert_equal(len(actual),len(desired),err_msg) for k,i in desired.items(): - assert k in actual, repr(k) + if not k in actual: + raise AssertionError("%s not in %s" % (k,actual)) assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg)) return # Case #2: lists ..... @@ -92,7 +94,8 @@ return _assert_equal_on_sequences(actual, desired, err_msg='') if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)): msg = build_err_msg([actual, desired], err_msg,) - assert desired == actual, msg + if not desired == actual: + raise AssertionError(msg) return # Case #4. arrays or equivalent if ((actual is masked) and not (desired is masked)) or \ @@ -122,10 +125,12 @@ """Raises an assertion error if two items are equal. """ if isinstance(desired, dict): - assert isinstance(actual, dict), repr(type(actual)) + if not isinstance(actual, dict): + raise AssertionError(repr(type(actual))) fail_if_equal(len(actual),len(desired),err_msg) for k,i in desired.items(): - assert k in actual, repr(k) + if not k in actual: + raise AssertionError(repr(k)) fail_if_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg)) return if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)): @@ -136,7 +141,8 @@ if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray): return fail_if_array_equal(actual, desired, err_msg) msg = build_err_msg([actual, desired], err_msg) - assert desired != actual, msg + if not desired != actual: + raise AssertionError(msg) assert_not_equal = fail_if_equal @@ -149,7 +155,8 @@ err_msg=err_msg, verbose=verbose) msg = build_err_msg([actual, desired], err_msg=err_msg, verbose=verbose) - assert round(abs(desired - actual),decimal) == 0, msg + if not round(abs(desired - actual),decimal) == 0: + raise AssertionError(msg) assert_close = assert_almost_equal From numpy-svn at scipy.org Mon Sep 29 16:25:01 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 29 Sep 2008 15:25:01 -0500 (CDT) Subject: [Numpy-svn] r5880 - trunk/numpy/ma/tests Message-ID: <20080929202501.1079E39C0EA@scipy.org> Author: pierregm Date: 2008-09-29 15:24:56 -0500 (Mon, 29 Sep 2008) New Revision: 5880 Modified: trunk/numpy/ma/tests/test_core.py trunk/numpy/ma/tests/test_extras.py trunk/numpy/ma/tests/test_mrecords.py trunk/numpy/ma/tests/test_subclassing.py Log: replaced assert with self.failUnless Modified: trunk/numpy/ma/tests/test_core.py =================================================================== --- trunk/numpy/ma/tests/test_core.py 2008-09-29 20:24:29 UTC (rev 5879) +++ trunk/numpy/ma/tests/test_core.py 2008-09-29 20:24:56 UTC (rev 5880) @@ -60,15 +60,15 @@ x = masked_array(0, mask=False) assert_equal(str(x), '0') x = array(0, mask=1) - assert(x.filled().dtype is x._data.dtype) + self.failUnless(x.filled().dtype is x._data.dtype) def test_basic1d(self): "Test of basic array creation and properties in 1 dimension." (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d - assert(not isMaskedArray(x)) - assert(isMaskedArray(xm)) - assert((xm-ym).filled(0).any()) + self.failUnless(not isMaskedArray(x)) + self.failUnless(isMaskedArray(xm)) + self.failUnless((xm-ym).filled(0).any()) fail_if_equal(xm.mask.astype(int_), ym.mask.astype(int_)) s = x.shape assert_equal(np.shape(xm), s) @@ -92,8 +92,8 @@ ym.shape = s xf.shape = s # - assert(not isMaskedArray(x)) - assert(isMaskedArray(xm)) + self.failUnless(not isMaskedArray(x)) + self.failUnless(isMaskedArray(xm)) assert_equal(shape(xm), s) assert_equal(xm.shape, s) assert_equal( xm.size , reduce(lambda x,y:x*y, s)) @@ -177,7 +177,7 @@ x.mask = nomask data = array((x,x[::-1])) assert_equal(data, [[0,1,2,3,4],[4,3,2,1,0]]) - assert(data.mask is nomask) + self.failUnless(data.mask is nomask) def test_asarray(self): (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d @@ -200,8 +200,8 @@ "Test of masked element" x = arange(6) x[1] = masked - assert(str(masked) == '--') - assert(x[1] is masked) + self.failUnless(str(masked) == '--') + self.failUnless(x[1] is masked) assert_equal(filled(x[1], 0), 0) # don't know why these should raise an exception... #self.failUnlessRaises(Exception, lambda x,y: x+y, masked, masked) @@ -215,12 +215,12 @@ x = (1,2,3,4,5) a[0] = x assert_equal(a[0], x) - assert(a[0] is x) + self.failUnless(a[0] is x) # import datetime dt = datetime.datetime.now() a[0] = dt - assert(a[0] is dt) + self.failUnless(a[0] is dt) def test_indexing(self): @@ -279,39 +279,39 @@ n = [0,0,1,0,0] m = make_mask(n) m2 = make_mask(m) - assert(m is m2) + self.failUnless(m is m2) m3 = make_mask(m, copy=1) - assert(m is not m3) + self.failUnless(m is not m3) warnings.simplefilter('ignore', DeprecationWarning) x1 = np.arange(5) y1 = array(x1, mask=m) - #assert( y1._data is x1) + #self.failUnless( y1._data is x1) assert_equal(y1._data.__array_interface__, x1.__array_interface__) - assert( allequal(x1,y1.raw_data())) - #assert( y1.mask is m) + self.failUnless( allequal(x1,y1.raw_data())) + #self.failUnless( y1.mask is m) assert_equal(y1._mask.__array_interface__, m.__array_interface__) warnings.simplefilter('default', DeprecationWarning) y1a = array(y1) - #assert( y1a.raw_data() is y1.raw_data()) - assert( y1a._data.__array_interface__ == y1._data.__array_interface__) - assert( y1a.mask is y1.mask) + #self.failUnless( y1a.raw_data() is y1.raw_data()) + self.failUnless( y1a._data.__array_interface__ == y1._data.__array_interface__) + self.failUnless( y1a.mask is y1.mask) y2 = array(x1, mask=m) - #assert( y2.raw_data() is x1) - assert (y2._data.__array_interface__ == x1.__array_interface__) - #assert( y2.mask is m) - assert (y2._mask.__array_interface__ == m.__array_interface__) - assert( y2[2] is masked) + #self.failUnless( y2.raw_data() is x1) + self.failUnless(y2._data.__array_interface__ == x1.__array_interface__) + #self.failUnless( y2.mask is m) + self.failUnless(y2._mask.__array_interface__ == m.__array_interface__) + self.failUnless( y2[2] is masked) y2[2] = 9 - assert( y2[2] is not masked) - #assert( y2.mask is not m) - assert (y2._mask.__array_interface__ != m.__array_interface__) - assert( allequal(y2.mask, 0)) + self.failUnless( y2[2] is not masked) + #self.failUnless( y2.mask is not m) + self.failUnless(y2._mask.__array_interface__ != m.__array_interface__) + self.failUnless( allequal(y2.mask, 0)) y3 = array(x1*1.0, mask=m) - assert(filled(y3).dtype is (x1*1.0).dtype) + self.failUnless(filled(y3).dtype is (x1*1.0).dtype) x4 = arange(4) x4[2] = masked @@ -374,7 +374,7 @@ a_pickled = cPickle.loads(a.dumps()) assert_equal(a_pickled._mask, a._mask) assert_equal(a_pickled, a) - assert(isinstance(a_pickled._data,np.matrix)) + self.failUnless(isinstance(a_pickled._data,np.matrix)) def test_single_element_subscript(self): @@ -401,7 +401,7 @@ a = array([1,2,3],mask=[1,0,0]) self.assertRaises(TypeError, lambda:float(a)) assert_equal(float(a[-1]), 3.) - assert(np.isnan(float(a[0]))) + self.failUnless(np.isnan(float(a[0]))) self.assertRaises(TypeError, int, a) assert_equal(int(a[-1]), 3) self.assertRaises(MAError, lambda:int(a[0])) @@ -575,11 +575,11 @@ "Tests some scalar arithmetics on MaskedArrays." # Masked singleton should remain masked no matter what xm = array(0, mask=1) - assert((1/array(0)).mask) - assert((1 + xm).mask) - assert((-xm).mask) - assert(maximum(xm, xm).mask) - assert(minimum(xm, xm).mask) + self.failUnless((1/array(0)).mask) + self.failUnless((1 + xm).mask) + self.failUnless((-xm).mask) + self.failUnless(maximum(xm, xm).mask) + self.failUnless(minimum(xm, xm).mask) def test_arithmetic_with_masked_singleton(self): "Checks that there's no collapsing to masked" @@ -633,7 +633,7 @@ def test_count_func (self): "Tests count" ott = array([0.,1.,2.,3.], mask=[1,0,0,0]) - assert( isinstance(count(ott), int)) + self.failUnless( isinstance(count(ott), int)) assert_equal(3, count(ott)) assert_equal(1, count(1)) assert_equal(0, array(1,mask=[1])) @@ -670,19 +670,19 @@ def test_minimummaximum_func(self): a = np.ones((2,2)) aminimum = minimum(a,a) - assert(isinstance(aminimum, MaskedArray)) + self.failUnless(isinstance(aminimum, MaskedArray)) assert_equal(aminimum, np.minimum(a,a)) # aminimum = minimum.outer(a,a) - assert(isinstance(aminimum, MaskedArray)) + self.failUnless(isinstance(aminimum, MaskedArray)) assert_equal(aminimum, np.minimum.outer(a,a)) # amaximum = maximum(a,a) - assert(isinstance(amaximum, MaskedArray)) + self.failUnless(isinstance(amaximum, MaskedArray)) assert_equal(amaximum, np.maximum(a,a)) # amaximum = maximum.outer(a,a) - assert(isinstance(amaximum, MaskedArray)) + self.failUnless(isinstance(amaximum, MaskedArray)) assert_equal(amaximum, np.maximum.outer(a,a)) def test_minmax_funcs_with_output(self): @@ -697,11 +697,11 @@ # Use the np version nout = np.empty((4,), dtype=int) result = npfunc(xm,axis=0,out=nout) - assert(result is nout) + self.failUnless(result is nout) # Use the ma version nout.fill(-999) result = mafunc(xm,axis=0,out=nout) - assert(result is nout) + self.failUnless(result is nout) def test_minmax_methods(self): @@ -709,22 +709,22 @@ (_, _, _, _, _, xm, _, _, _, _) = self.d xm.shape = (xm.size,) assert_equal(xm.max(), 10) - assert(xm[0].max() is masked) - assert(xm[0].max(0) is masked) - assert(xm[0].max(-1) is masked) + self.failUnless(xm[0].max() is masked) + self.failUnless(xm[0].max(0) is masked) + self.failUnless(xm[0].max(-1) is masked) assert_equal(xm.min(), -10.) - assert(xm[0].min() is masked) - assert(xm[0].min(0) is masked) - assert(xm[0].min(-1) is masked) + self.failUnless(xm[0].min() is masked) + self.failUnless(xm[0].min(0) is masked) + self.failUnless(xm[0].min(-1) is masked) assert_equal(xm.ptp(), 20.) - assert(xm[0].ptp() is masked) - assert(xm[0].ptp(0) is masked) - assert(xm[0].ptp(-1) is masked) + self.failUnless(xm[0].ptp() is masked) + self.failUnless(xm[0].ptp(0) is masked) + self.failUnless(xm[0].ptp(-1) is masked) # x = array([1,2,3], mask=True) - assert(x.min() is masked) - assert(x.max() is masked) - assert(x.ptp() is masked) + self.failUnless(x.min() is masked) + self.failUnless(x.max() is masked) + self.failUnless(x.ptp() is masked) #........................ def test_addsumprod (self): "Tests add, sum, product." @@ -797,13 +797,13 @@ output.fill(-9999) result = npfunc(xm, axis=0,out=output) # ... the result should be the given output - assert(result is output) + self.failUnless(result is output) assert_equal(result, xmmeth(axis=0, out=output)) # output = empty(4, dtype=int) result = xmmeth(axis=0, out=output) - assert(result is output) - assert(output[0] is masked) + self.failUnless(result is output) + self.failUnless(output[0] is masked) #------------------------------------------------------------------------------ @@ -837,8 +837,8 @@ assert_equal(xs._data, [0,10,2,3,40]) #assert_equal(xh.mask.ctypes._data, m.ctypes._data) assert_equal(xs.mask, [0,0,0,1,0]) - assert(xh._hardmask) - assert(not xs._hardmask) + self.failUnless(xh._hardmask) + self.failUnless(not xs._hardmask) xh[1:4] = [10,20,30] xs[1:4] = [10,20,30] assert_equal(xh._data, [0,10,20,3,4]) @@ -931,39 +931,39 @@ ndtype = [('a',int),('b',float),('c',"|S3")] # A check on a list should return a single record fval = _check_fill_value([-999,-999.9,"???"], ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [-999,-999.9,"???"]) # A check on Non should output the defaults fval = _check_fill_value(None, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [default_fill_value(0), default_fill_value(0.), default_fill_value("0")]) #.....Using a flexible type as fill_value should work fill_val = np.array((-999,-999.9,"???"),dtype=ndtype) fval = _check_fill_value(fill_val, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [-999,-999.9,"???"]) #.....Using a flexible type w/ a different type shouldn't matter fill_val = np.array((-999,-999.9,"???"), dtype=[("A",int),("B",float),("C","|S3")]) fval = _check_fill_value(fill_val, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [-999,-999.9,"???"]) #.....Using an object-array shouldn't matter either fill_value = np.array((-999,-999.9,"???"), dtype=object) fval = _check_fill_value(fill_val, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [-999,-999.9,"???"]) # fill_value = np.array((-999,-999.9,"???")) fval = _check_fill_value(fill_val, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [-999,-999.9,"???"]) #.....One-field-only flexible type should work as well ndtype = [("a",int)] fval = _check_fill_value(-999, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), (-999,)) @@ -1087,8 +1087,8 @@ def test_reduce(self): "Tests reduce on MaskedArrays." a = self.d[0] - assert(not alltrue(a,axis=0)) - assert(sometrue(a,axis=0)) + self.failUnless(not alltrue(a,axis=0)) + self.failUnless(sometrue(a,axis=0)) assert_equal(sum(a[:3],axis=0), 0) assert_equal(product(a,axis=0), 0) assert_equal(add.reduce(a), pi) @@ -1101,8 +1101,8 @@ assert_equal(amask.min(), 5) assert_equal(amask.max(0), a.max(0)) assert_equal(amask.min(0), [5,6,7,8]) - assert(amask.max(1)[0].mask) - assert(amask.min(1)[0].mask) + self.failUnless(amask.max(1)[0].mask) + self.failUnless(amask.min(1)[0].mask) #------------------------------------------------------------------------------ @@ -1355,18 +1355,18 @@ store = empty(1, dtype=bool) full = array([1,2,3], mask=True) # - assert(full.all() is masked) + self.failUnless(full.all() is masked) full.all(out=store) - assert(store) - assert(store._mask, True) - assert(store is not masked) + self.failUnless(store) + self.failUnless(store._mask, True) + self.failUnless(store is not masked) # store = empty(1, dtype=bool) - assert(full.any() is masked) + self.failUnless(full.any() is masked) full.any(out=store) - assert(not store) - assert(store._mask, True) - assert(store is not masked) + self.failUnless(not store) + self.failUnless(store._mask, True) + self.failUnless(store is not masked) def test_argmax_argmin(self): @@ -1454,7 +1454,7 @@ a = array(np.matrix([1,2,3,4]), mask=[0,0,0,0]) b = a.compressed() assert_equal(b,a) - assert(isinstance(b,np.matrix)) + self.failUnless(isinstance(b,np.matrix)) a[0,0] = masked b = a.compressed() assert_equal(b, [[2,3,4]]) @@ -1482,12 +1482,12 @@ n = [0,0,0,1,1] m = make_mask(n) x = array(d, mask = m) - assert( x[3] is masked) - assert( x[4] is masked) + self.failUnless( x[3] is masked) + self.failUnless( x[4] is masked) x[[1,4]] = [10,40] -# assert( x.mask is not m) - assert( x[3] is masked) - assert( x[4] is not masked) +# self.failUnless( x.mask is not m) + self.failUnless( x[3] is masked) + self.failUnless( x[4] is not masked) assert_equal(x, [0,10,2,-1,40]) # x = masked_array(arange(10), mask=[1,0,0,0,0]*2) @@ -1607,7 +1607,7 @@ # x = [1,4,2,3] sortedx = sort(x) - assert(not isinstance(sorted, MaskedArray)) + self.failUnless(not isinstance(sorted, MaskedArray)) # x = array([0,1,-1,-2,2], mask=nomask, dtype=np.int8) sortedx = sort(x, endwith=False) @@ -1667,7 +1667,7 @@ assert_equal(data.squeeze(), [1,2,3]) assert_equal(data.squeeze()._mask, [1,1,1]) data = masked_array([[1]], mask=True) - assert(data.squeeze() is masked) + self.failUnless(data.squeeze() is masked) def test_swapaxes(self): @@ -1714,8 +1714,8 @@ x = array(np.arange(12)) x[[1,-2]] = masked xlist = x.tolist() - assert(xlist[1] is None) - assert(xlist[-2] is None) + self.failUnless(xlist[1] is None) + self.failUnless(xlist[-2] is None) # x.shape = (3,4) xlist = x.tolist() @@ -1830,12 +1830,12 @@ output.fill(-9999) result = npfunc(xm, axis=0,out=output) # ... the result should be the given output - assert(result is output) + self.failUnless(result is output) assert_equal(result, xmmeth(axis=0, out=output)) # output = empty((3,4), dtype=int) result = xmmeth(axis=0, out=output) - assert(result is output) + self.failUnless(result is output) def test_ptp(self): @@ -1890,31 +1890,31 @@ x = array(arange(10), mask=True) for methodname in ('var', 'std'): method = getattr(x,methodname) - assert(method() is masked) - assert(method(0) is masked) - assert(method(-1) is masked) + self.failUnless(method() is masked) + self.failUnless(method(0) is masked) + self.failUnless(method(-1) is masked) # Using a masked array as explicit output _ = method(out=mout) - assert(mout is not masked) + self.failUnless(mout is not masked) assert_equal(mout.mask, True) # Using a ndarray as explicit output _ = method(out=nout) - assert(np.isnan(nout)) + self.failUnless(np.isnan(nout)) # x = array(arange(10), mask=True) x[-1] = 9 for methodname in ('var', 'std'): method = getattr(x,methodname) - assert(method(ddof=1) is masked) - assert(method(0, ddof=1) is masked) - assert(method(-1, ddof=1) is masked) + self.failUnless(method(ddof=1) is masked) + self.failUnless(method(0, ddof=1) is masked) + self.failUnless(method(-1, ddof=1) is masked) # Using a masked array as explicit output _ = method(out=mout, ddof=1) - assert(mout is not masked) + self.failUnless(mout is not masked) assert_equal(mout.mask, True) # Using a ndarray as explicit output _ = method(out=nout, ddof=1) - assert(np.isnan(nout)) + self.failUnless(np.isnan(nout)) #------------------------------------------------------------------------------ @@ -2032,7 +2032,7 @@ else: raise AssertionError("Should have failed...") test = masked_equal(a,1) - assert(test.mask, [0,1,0,0,0,0,0,0,0,0]) + assert_equal(test.mask, [0,1,0,0,0,0,0,0,0,0]) def test_masked_otherfunctions(self): @@ -2078,24 +2078,24 @@ output.fill(-9999) result = np.round(xm, decimals=2,out=output) # ... the result should be the given output - assert(result is output) + self.failUnless(result is output) assert_equal(result, xm.round(decimals=2, out=output)) # output = empty((3,4), dtype=float) result = xm.round(decimals=2, out=output) - assert(result is output) + self.failUnless(result is output) def test_identity(self): a = identity(5) - assert(isinstance(a, MaskedArray)) + self.failUnless(isinstance(a, MaskedArray)) assert_equal(a, np.identity(5)) def test_power(self): x = -1.1 assert_almost_equal(power(x,2.), 1.21) - assert(power(x,masked) is masked) + self.failUnless(power(x,masked) is masked) x = array([-1.1,-1.1,1.1,1.1,0.]) b = array([0.5,2.,0.5,2.,-1.], mask=[0,0,0,0,1]) y = power(x,b) @@ -2228,7 +2228,7 @@ store = empty(4, dtype=int) chosen = choose([2, 3, 1, 0], choices, out=store) assert_equal(store, array([20, 31, 12, 3])) - assert(store is chosen) + self.failUnless(store is chosen) # Check with some masked indices + out store = empty(4, dtype=int) indices_ = array([2, 3, 1, 0], mask=[1,0,0,1]) @@ -2250,25 +2250,25 @@ # Try the default b = a.reshape((5,2)) assert_equal(b.shape, (5,2)) - assert(b.flags['C']) + self.failUnless(b.flags['C']) # Try w/ arguments as list instead of tuple b = a.reshape(5,2) assert_equal(b.shape, (5,2)) - assert(b.flags['C']) + self.failUnless(b.flags['C']) # Try w/ order b = a.reshape((5,2), order='F') assert_equal(b.shape, (5,2)) - assert(b.flags['F']) + self.failUnless(b.flags['F']) # Try w/ order b = a.reshape(5,2, order='F') assert_equal(b.shape, (5,2)) - assert(b.flags['F']) + self.failUnless(b.flags['F']) # c = np.reshape(a, (2,5)) - assert(isinstance(c, MaskedArray)) + self.failUnless(isinstance(c, MaskedArray)) assert_equal(c.shape, (2,5)) - assert(c[0,0] is masked) - assert(c.flags['C']) + self.failUnless(c[0,0] is masked) + self.failUnless(c.flags['C']) #------------------------------------------------------------------------------ @@ -2380,7 +2380,7 @@ # test = a.view((float,2), np.matrix) assert_equal(test, data) - assert(isinstance(test, np.matrix)) + self.failUnless(isinstance(test, np.matrix)) # def test_getitem(self): ndtype = [('a',float), ('b',float)] @@ -2389,13 +2389,13 @@ [1,0,0,0,0,0,0,0,1,0]), dtype=[('a',bool),('b',bool)]) # No mask - assert(isinstance(a[1], np.void)) + self.failUnless(isinstance(a[1], np.void)) # One element masked - assert(isinstance(a[0], MaskedArray)) + self.failUnless(isinstance(a[0], MaskedArray)) assert_equal_records(a[0]._data, a._data[0]) assert_equal_records(a[0]._mask, a._mask[0]) # All element masked - assert(isinstance(a[-2], MaskedArray)) + self.failUnless(isinstance(a[-2], MaskedArray)) assert_equal_records(a[-2]._data, a._data[-2]) assert_equal_records(a[-2]._mask, a._mask[-2]) Modified: trunk/numpy/ma/tests/test_extras.py =================================================================== --- trunk/numpy/ma/tests/test_extras.py 2008-09-29 20:24:29 UTC (rev 5879) +++ trunk/numpy/ma/tests/test_extras.py 2008-09-29 20:24:56 UTC (rev 5880) @@ -26,7 +26,7 @@ assert_equal(2.0, average(ott, weights=[1., 1., 2., 1.])) result, wts = average(ott, weights=[1.,1.,2.,1.], returned=1) assert_equal(2.0, result) - assert(wts == 4.0) + self.failUnless(wts == 4.0) ott[:] = masked assert_equal(average(ott,axis=0).mask, [True]) ott = array([0.,1.,2.,3.], mask=[1,0,0,0]) @@ -104,7 +104,7 @@ m = [1,0,0,0,0] d = masked_array(b,mask=m) c = mr_[d,0,0,d] - assert(isinstance(c,MaskedArray) or isinstance(c,core.MaskedArray)) + self.failUnless(isinstance(c,MaskedArray) or isinstance(c,core.MaskedArray)) assert_array_equal(c,[1,1,1,1,1,0,0,1,1,1,1,1]) assert_array_equal(c.mask, mr_[m,0,0,m]) @@ -117,12 +117,12 @@ b_1 = masked_array(a_1,mask=m_1) b_2 = masked_array(a_2,mask=m_2) d = mr_['1',b_1,b_2] # append columns - assert(d.shape == (5,10)) + self.failUnless(d.shape == (5,10)) assert_array_equal(d[:,:5],b_1) assert_array_equal(d[:,5:],b_2) assert_array_equal(d.mask, np.r_['1',m_1,m_2]) d = mr_[b_1,b_2] - assert(d.shape == (10,5)) + self.failUnless(d.shape == (10,5)) assert_array_equal(d[:5,:],b_1) assert_array_equal(d[5:,:],b_2) assert_array_equal(d.mask, np.r_[m_1,m_2]) @@ -158,14 +158,14 @@ assert_equal(tmp[-3], slice(0,3,None)) # tmp = notmasked_contiguous(a, 0) - assert(len(tmp[-1]) == 1) - assert(tmp[-2] is None) + self.failUnless(len(tmp[-1]) == 1) + self.failUnless(tmp[-2] is None) assert_equal(tmp[-3],tmp[-1]) - assert(len(tmp[0]) == 2) + self.failUnless(len(tmp[0]) == 2) # tmp = notmasked_contiguous(a, 1) assert_equal(tmp[0][-1], slice(0,3,None)) - assert(tmp[1] is None) + self.failUnless(tmp[1] is None) assert_equal(tmp[2][-1], slice(7,7,None)) assert_equal(tmp[2][-2], slice(0,5,None)) @@ -205,12 +205,12 @@ assert_equal(mask_rowcols(x,0).mask, [[1,1,1],[1,1,1],[0,0,0]] ) assert_equal(mask_rowcols(x,1,).mask, [[1,1,0],[1,1,0],[1,1,0]] ) x = array(x._data, mask=[[1,0,0],[0,1,0],[0,0,1]]) - assert(mask_rowcols(x).all() is masked) - assert(mask_rowcols(x,0).all() is masked) - assert(mask_rowcols(x,1).all() is masked) - assert(mask_rowcols(x).mask.all()) - assert(mask_rowcols(x,0).mask.all()) - assert(mask_rowcols(x,1).mask.all()) + self.failUnless(mask_rowcols(x).all() is masked) + self.failUnless(mask_rowcols(x,0).all() is masked) + self.failUnless(mask_rowcols(x,1).all() is masked) + self.failUnless(mask_rowcols(x).mask.all()) + self.failUnless(mask_rowcols(x,0).mask.all()) + self.failUnless(mask_rowcols(x,1).mask.all()) # def test_dot(self): "Tests dot product" Modified: trunk/numpy/ma/tests/test_mrecords.py =================================================================== --- trunk/numpy/ma/tests/test_mrecords.py 2008-09-29 20:24:29 UTC (rev 5879) +++ trunk/numpy/ma/tests/test_mrecords.py 2008-09-29 20:24:56 UTC (rev 5880) @@ -264,16 +264,16 @@ base = self.base.copy() mbase = base.view(mrecarray) mbase.harden_mask() - assert(mbase._hardmask) + self.failUnless(mbase._hardmask) mbase._mask = nomask assert_equal_records(mbase._mask, base._mask) mbase.soften_mask() - assert(not mbase._hardmask) + self.failUnless(not mbase._hardmask) mbase._mask = nomask # So, the mask of a field is no longer set to nomask... assert_equal_records(mbase._mask, ma.make_mask_none(base.shape,base.dtype)) - assert(ma.make_mask(mbase['b']._mask) is nomask) + self.failUnless(ma.make_mask(mbase['b']._mask) is nomask) assert_equal(mbase['a']._mask,mbase['b']._mask) # def test_pickling(self): @@ -435,7 +435,7 @@ mrectxt = fromtextfile(tmp_fl, delimitor=',',varnames='ABCDEFG') os.remove(tmp_fl) # - assert(isinstance(mrectxt, MaskedRecords)) + self.failUnless(isinstance(mrectxt, MaskedRecords)) assert_equal(mrectxt.F, [1,1,1,1]) assert_equal(mrectxt.E._mask, [1,1,1,1]) assert_equal(mrectxt.C, [1,2,3.e+5,-1e-10]) Modified: trunk/numpy/ma/tests/test_subclassing.py =================================================================== --- trunk/numpy/ma/tests/test_subclassing.py 2008-09-29 20:24:29 UTC (rev 5879) +++ trunk/numpy/ma/tests/test_subclassing.py 2008-09-29 20:24:56 UTC (rev 5880) @@ -76,24 +76,24 @@ m = [0,0,1,0,0] xsub = SubArray(x) xmsub = masked_array(xsub, mask=m) - assert isinstance(xmsub, MaskedArray) + self.failUnless(isinstance(xmsub, MaskedArray)) assert_equal(xmsub._data, xsub) - assert isinstance(xmsub._data, SubArray) + self.failUnless(isinstance(xmsub._data, SubArray)) def test_maskedarray_subclassing(self): "Tests subclassing MaskedArray" x = np.arange(5) mx = mmatrix(x,mask=[0,1,0,0,0]) - assert isinstance(mx._data, np.matrix) + self.failUnless(isinstance(mx._data, np.matrix)) "Tests masked_unary_operation" - assert isinstance(add(mx,mx), mmatrix) - assert isinstance(add(mx,x), mmatrix) + self.failUnless(isinstance(add(mx,mx), mmatrix)) + self.failUnless(isinstance(add(mx,x), mmatrix)) assert_equal(add(mx,x), mx+x) - assert isinstance(add(mx,mx)._data, np.matrix) - assert isinstance(add.outer(mx,mx), mmatrix) + self.failUnless(isinstance(add(mx,mx)._data, np.matrix)) + self.failUnless(isinstance(add.outer(mx,mx), mmatrix)) "Tests masked_binary_operation" - assert isinstance(hypot(mx,mx), mmatrix) - assert isinstance(hypot(mx,x), mmatrix) + self.failUnless(isinstance(hypot(mx,mx), mmatrix)) + self.failUnless(isinstance(hypot(mx,x), mmatrix)) def test_attributepropagation(self): x = array(arange(5), mask=[0]+[1]*4) @@ -101,16 +101,16 @@ ym = msubarray(x) # z = (my+1) - assert isinstance(z,MaskedArray) - assert not isinstance(z, MSubArray) - assert isinstance(z._data, SubArray) + self.failUnless(isinstance(z,MaskedArray)) + self.failUnless(not isinstance(z, MSubArray)) + self.failUnless(isinstance(z._data, SubArray)) assert_equal(z._data.info, {}) # z = (ym+1) - assert isinstance(z, MaskedArray) - assert isinstance(z, MSubArray) - assert isinstance(z._data, SubArray) - assert z._data.info['added'] > 0 + self.failUnless(isinstance(z, MaskedArray)) + self.failUnless(isinstance(z, MSubArray)) + self.failUnless(isinstance(z._data, SubArray)) + self.failUnless(z._data.info['added'] > 0) # ym._set_mask([1,0,0,0,1]) assert_equal(ym._mask, [1,0,0,0,1]) @@ -119,7 +119,7 @@ # xsub = subarray(x, info={'name':'x'}) mxsub = masked_array(xsub) - assert hasattr(mxsub, 'info') + self.failUnless(hasattr(mxsub, 'info')) assert_equal(mxsub.info, xsub.info) def test_subclasspreservation(self): @@ -130,22 +130,22 @@ xsub = MSubArray(x, mask=m, info={'xsub':xinfo}) # mxsub = masked_array(xsub, subok=False) - assert not isinstance(mxsub, MSubArray) - assert isinstance(mxsub, MaskedArray) + self.failUnless(not isinstance(mxsub, MSubArray)) + self.failUnless(isinstance(mxsub, MaskedArray)) assert_equal(mxsub._mask, m) # mxsub = asarray(xsub) - assert not isinstance(mxsub, MSubArray) - assert isinstance(mxsub, MaskedArray) + self.failUnless(not isinstance(mxsub, MSubArray)) + self.failUnless(isinstance(mxsub, MaskedArray)) assert_equal(mxsub._mask, m) # mxsub = masked_array(xsub, subok=True) - assert isinstance(mxsub, MSubArray) + self.failUnless(isinstance(mxsub, MSubArray)) assert_equal(mxsub.info, xsub.info) assert_equal(mxsub._mask, xsub._mask) # mxsub = asanyarray(xsub) - assert isinstance(mxsub, MSubArray) + self.failUnless(isinstance(mxsub, MSubArray)) assert_equal(mxsub.info, xsub.info) assert_equal(mxsub._mask, m) @@ -160,16 +160,16 @@ ym = msubarray(x) # z = (my+1) - assert isinstance(z,MaskedArray) - assert not isinstance(z, MSubArray) - assert isinstance(z._data, SubArray) + self.failUnless(isinstance(z,MaskedArray)) + self.failUnless(not isinstance(z, MSubArray)) + self.failUnless(isinstance(z._data, SubArray)) assert_equal(z._data.info, {}) # z = (ym+1) - assert isinstance(z, MaskedArray) - assert isinstance(z, MSubArray) - assert isinstance(z._data, SubArray) - assert z._data.info['added'] > 0 + self.failUnless(isinstance(z, MaskedArray)) + self.failUnless(isinstance(z, MSubArray)) + self.failUnless(isinstance(z._data, SubArray)) + self.failUnless(z._data.info['added'] > 0) # ym._set_mask([1,0,0,0,1]) assert_equal(ym._mask, [1,0,0,0,1]) From numpy-svn at scipy.org Mon Sep 29 22:03:03 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 29 Sep 2008 21:03:03 -0500 (CDT) Subject: [Numpy-svn] r5881 - branches/clean_math_config_chuck/numpy/core/src Message-ID: <20080930020303.5CB7E39C405@scipy.org> Author: charris Date: 2008-09-29 21:03:00 -0500 (Mon, 29 Sep 2008) New Revision: 5881 Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src Log: Work in Progress Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-29 20:24:56 UTC (rev 5880) +++ branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-30 02:03:00 UTC (rev 5881) @@ -815,7 +815,7 @@ { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; - *((@type@ *)op) = (in1 > 0) ? in1 : -in1; + *((@type@ *)op) = (in1 >= 0) ? in1 : -in1; } } @@ -970,6 +970,15 @@ } } +static void + at TYPE@_logical_not(char **args, intp *dimensions, intp *steps, void *func) +{ + UNARY_LOOP { + const @type@ in1 = *(@type@ *)ip1; + *((Bool *)op) = !in1; + } +} + /**begin repeat1 * #kind = isnan, isinf, isfinite, signbit# * #func = isnan, isinf, isfinite, signbit# @@ -986,15 +995,25 @@ /**begin repeat1 * #kind = maximum, minimum# - * #OP = >, <# + * #OP1 = >=, <=# + * #OP2 = <=, >=# **/ static void @TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) { + /* Return NaN if either value is NaN */ BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; - *((@type@ *)op) = (in1 @OP@ in2) ? in1 : in2; + if (in1 @OP1@ in2) { + *((@type@ *)op) = in1; + } + else if (in1 @OP2@ in2) { + *((@type@ *)op) = in2; + } + else { + *((@type@ *)op) = NAN; + } } } /**end repeat1**/ @@ -1065,7 +1084,9 @@ { UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; - *((@type@ *)op) = (in1 < 0) ? -in1 : in1; + const @type@ tmp = (in1 > 0) ? in1 : -in1; + /* add 0 to clear -0.0 */ + *((@type@ *)op) = tmp + 0; } } @@ -1079,20 +1100,24 @@ } static void - at TYPE@_logical_not(char **args, intp *dimensions, intp *steps, void *func) -{ - UNARY_LOOP { - const @type@ in1 = *(@type@ *)ip1; - *((Bool *)op) = !in1; - } -} - -static void @TYPE at _sign(char **args, intp *dimensions, intp *steps, void *func) { + /* Returns NaN as sign of NaN */ UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; - *((@type@ *)op) = in1 > 0 ? 1 : (in1 < 0 ? -1 : 0); + if (in1 > 0) { + *((@type@ *)op) = 1; + } + else if (in1 < 0) { + *((@type@ *)op) = -1; + } + else if (in1 == 0) { + *((@type@ *)op) = 0; + } + else { + /* is NaN */ + *((@type@ *)op) = in1; + } } } From numpy-svn at scipy.org Tue Sep 30 00:40:25 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Mon, 29 Sep 2008 23:40:25 -0500 (CDT) Subject: [Numpy-svn] r5882 - in branches/clean_math_config: . numpy/core/tests numpy/lib numpy/ma numpy/ma/tests Message-ID: <20080930044025.60E9C39C580@scipy.org> Author: cdavid Date: 2008-09-29 23:40:13 -0500 (Mon, 29 Sep 2008) New Revision: 5882 Modified: branches/clean_math_config/ branches/clean_math_config/numpy/core/tests/test_umath.py branches/clean_math_config/numpy/lib/utils.py branches/clean_math_config/numpy/ma/core.py branches/clean_math_config/numpy/ma/tests/test_core.py branches/clean_math_config/numpy/ma/tests/test_extras.py branches/clean_math_config/numpy/ma/tests/test_mrecords.py branches/clean_math_config/numpy/ma/tests/test_subclassing.py branches/clean_math_config/numpy/ma/testutils.py Log: Merged revisions 5861-5881 via svnmerge from http://svn.scipy.org/svn/numpy/trunk ........ r5862 | ptvirtan | 2008-09-24 20:50:38 +0900 (Wed, 24 Sep 2008) | 1 line Fix python2.5 dependency in lookfor ........ r5869 | pierregm | 2008-09-29 02:27:37 +0900 (Mon, 29 Sep 2008) | 3 lines core: * added __rmul and __radd__ * fixed concatenate for flexible-dtype ........ r5878 | ptvirtan | 2008-09-30 02:23:43 +0900 (Tue, 30 Sep 2008) | 1 line Umath tests: remove signed zero check on branch cut for log* as it fails on some platforms. ........ r5879 | pierregm | 2008-09-30 05:24:29 +0900 (Tue, 30 Sep 2008) | 1 line use if ...: raise AssertionError instead of assert ........ r5880 | pierregm | 2008-09-30 05:24:56 +0900 (Tue, 30 Sep 2008) | 1 line replaced assert with self.failUnless ........ Property changes on: branches/clean_math_config ___________________________________________________________________ Name: svnmerge-integrated - /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5860 + /branches/aligned_alloca:1-5127 /branches/build_with_scons:1-4676 /branches/cdavid:1-5257 /branches/cleanconfig_rtm:1-4677 /branches/distutils-revamp:1-2752 /branches/distutils_scons_command:1-4619 /branches/multicore:1-3687 /branches/numpy.scons:1-4484 /branches/vs_longstring:1-5656 /cleaned_math_config:1-5731 /trunk:1-5881 Modified: branches/clean_math_config/numpy/core/tests/test_umath.py =================================================================== --- branches/clean_math_config/numpy/core/tests/test_umath.py 2008-09-30 02:03:00 UTC (rev 5881) +++ branches/clean_math_config/numpy/core/tests/test_umath.py 2008-09-30 04:40:13 UTC (rev 5882) @@ -205,9 +205,9 @@ def test_branch_cuts(self): # check branch cuts and continuity on them - yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True - yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True - yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True + yield _check_branch_cut, np.log, -0.5, 1j, 1, -1 + yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1 + yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1 yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1 yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, -1j], 1, -1 @@ -229,6 +229,11 @@ @dec.knownfailureif(True, "These branch cuts are known to fail") def test_branch_cuts_failing(self): + # XXX: signed zero not OK with ICC on 64-bit platform for log, see + # http://permalink.gmane.org/gmane.comp.python.numeric.general/25335 + yield _check_branch_cut, np.log, -0.5, 1j, 1, -1, True + yield _check_branch_cut, np.log10, -0.5, 1j, 1, -1, True + yield _check_branch_cut, np.log1p, -1.5, 1j, 1, -1, True # XXX: signed zeros are not OK for sqrt or for the arc* functions yield _check_branch_cut, np.sqrt, -0.5, 1j, 1, -1, True yield _check_branch_cut, np.arcsin, [ -2, 2], [1j, -1j], 1, -1, True Modified: branches/clean_math_config/numpy/lib/utils.py =================================================================== --- branches/clean_math_config/numpy/lib/utils.py 2008-09-30 02:03:00 UTC (rev 5881) +++ branches/clean_math_config/numpy/lib/utils.py 2008-09-30 04:40:13 UTC (rev 5882) @@ -1,6 +1,5 @@ import os import sys -import pkgutil import types import re @@ -680,15 +679,21 @@ _all = item.__all__ except AttributeError: _all = None + # import sub-packages if import_modules and hasattr(item, '__path__'): - for m in pkgutil.iter_modules(item.__path__): - if _all is not None and m[1] not in _all: - continue - try: - __import__("%s.%s" % (name, m[1])) - except ImportError: - continue + for pth in item.__path__: + for mod_path in os.listdir(pth): + init_py = os.path.join(pth, mod_path, '__init__.py') + if not os.path.isfile(init_py): + continue + if _all is not None and mod_path not in _all: + continue + try: + __import__("%s.%s" % (name, mod_path)) + except ImportError: + continue + for n, v in inspect.getmembers(item): if _all is not None and n not in _all: continue Modified: branches/clean_math_config/numpy/ma/core.py =================================================================== --- branches/clean_math_config/numpy/ma/core.py 2008-09-30 02:03:00 UTC (rev 5881) +++ branches/clean_math_config/numpy/ma/core.py 2008-09-30 04:40:13 UTC (rev 5882) @@ -1978,14 +1978,26 @@ "Add other to self, and return a new masked array." return add(self, other) # + def __radd__(self, other): + "Add other to self, and return a new masked array." + return add(self, other) + # def __sub__(self, other): "Subtract other to self, and return a new masked array." return subtract(self, other) # + def __rsub__(self, other): + "Subtract other to self, and return a new masked array." + return subtract(other, self) + # def __mul__(self, other): "Multiply other by self, and return a new masked array." return multiply(self, other) # + def __rmul__(self, other): + "Multiply other by self, and return a new masked array." + return multiply(self, other) + # def __div__(self, other): "Divide other into self, and return a new masked array." return divide(self, other) @@ -3527,7 +3539,7 @@ # ... all of them are True, and then check for dm.any() # shrink = numpy.logical_or.reduce([getattr(a,'_shrinkmask',True) for a in arrays]) # if shrink and not dm.any(): - if not dm.any(): + if not dm.dtype.fields and not dm.any(): data._mask = nomask else: data._mask = dm.reshape(d.shape) Modified: branches/clean_math_config/numpy/ma/tests/test_core.py =================================================================== --- branches/clean_math_config/numpy/ma/tests/test_core.py 2008-09-30 02:03:00 UTC (rev 5881) +++ branches/clean_math_config/numpy/ma/tests/test_core.py 2008-09-30 04:40:13 UTC (rev 5882) @@ -60,15 +60,15 @@ x = masked_array(0, mask=False) assert_equal(str(x), '0') x = array(0, mask=1) - assert(x.filled().dtype is x._data.dtype) + self.failUnless(x.filled().dtype is x._data.dtype) def test_basic1d(self): "Test of basic array creation and properties in 1 dimension." (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d - assert(not isMaskedArray(x)) - assert(isMaskedArray(xm)) - assert((xm-ym).filled(0).any()) + self.failUnless(not isMaskedArray(x)) + self.failUnless(isMaskedArray(xm)) + self.failUnless((xm-ym).filled(0).any()) fail_if_equal(xm.mask.astype(int_), ym.mask.astype(int_)) s = x.shape assert_equal(np.shape(xm), s) @@ -92,8 +92,8 @@ ym.shape = s xf.shape = s # - assert(not isMaskedArray(x)) - assert(isMaskedArray(xm)) + self.failUnless(not isMaskedArray(x)) + self.failUnless(isMaskedArray(xm)) assert_equal(shape(xm), s) assert_equal(xm.shape, s) assert_equal( xm.size , reduce(lambda x,y:x*y, s)) @@ -132,6 +132,15 @@ assert_array_equal(z,[1,1,0,0]) assert_array_equal(z.mask,[False,True,False,False]) + def test_concatenate_flexible(self): + "Tests the concatenation on flexible arrays." + data = masked_array(zip(np.random.rand(10), + np.arange(10)), + dtype=[('a',float),('b',int)]) + # + test = concatenate([data[:5], data[5:]]) + assert_equal_records(test, data) + def test_creation_ndmin(self): "Check the use of ndmin" x = array([1,2,3],mask=[1,0,0], ndmin=2) @@ -168,7 +177,7 @@ x.mask = nomask data = array((x,x[::-1])) assert_equal(data, [[0,1,2,3,4],[4,3,2,1,0]]) - assert(data.mask is nomask) + self.failUnless(data.mask is nomask) def test_asarray(self): (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d @@ -191,8 +200,8 @@ "Test of masked element" x = arange(6) x[1] = masked - assert(str(masked) == '--') - assert(x[1] is masked) + self.failUnless(str(masked) == '--') + self.failUnless(x[1] is masked) assert_equal(filled(x[1], 0), 0) # don't know why these should raise an exception... #self.failUnlessRaises(Exception, lambda x,y: x+y, masked, masked) @@ -206,12 +215,12 @@ x = (1,2,3,4,5) a[0] = x assert_equal(a[0], x) - assert(a[0] is x) + self.failUnless(a[0] is x) # import datetime dt = datetime.datetime.now() a[0] = dt - assert(a[0] is dt) + self.failUnless(a[0] is dt) def test_indexing(self): @@ -270,39 +279,39 @@ n = [0,0,1,0,0] m = make_mask(n) m2 = make_mask(m) - assert(m is m2) + self.failUnless(m is m2) m3 = make_mask(m, copy=1) - assert(m is not m3) + self.failUnless(m is not m3) warnings.simplefilter('ignore', DeprecationWarning) x1 = np.arange(5) y1 = array(x1, mask=m) - #assert( y1._data is x1) + #self.failUnless( y1._data is x1) assert_equal(y1._data.__array_interface__, x1.__array_interface__) - assert( allequal(x1,y1.raw_data())) - #assert( y1.mask is m) + self.failUnless( allequal(x1,y1.raw_data())) + #self.failUnless( y1.mask is m) assert_equal(y1._mask.__array_interface__, m.__array_interface__) warnings.simplefilter('default', DeprecationWarning) y1a = array(y1) - #assert( y1a.raw_data() is y1.raw_data()) - assert( y1a._data.__array_interface__ == y1._data.__array_interface__) - assert( y1a.mask is y1.mask) + #self.failUnless( y1a.raw_data() is y1.raw_data()) + self.failUnless( y1a._data.__array_interface__ == y1._data.__array_interface__) + self.failUnless( y1a.mask is y1.mask) y2 = array(x1, mask=m) - #assert( y2.raw_data() is x1) - assert (y2._data.__array_interface__ == x1.__array_interface__) - #assert( y2.mask is m) - assert (y2._mask.__array_interface__ == m.__array_interface__) - assert( y2[2] is masked) + #self.failUnless( y2.raw_data() is x1) + self.failUnless(y2._data.__array_interface__ == x1.__array_interface__) + #self.failUnless( y2.mask is m) + self.failUnless(y2._mask.__array_interface__ == m.__array_interface__) + self.failUnless( y2[2] is masked) y2[2] = 9 - assert( y2[2] is not masked) - #assert( y2.mask is not m) - assert (y2._mask.__array_interface__ != m.__array_interface__) - assert( allequal(y2.mask, 0)) + self.failUnless( y2[2] is not masked) + #self.failUnless( y2.mask is not m) + self.failUnless(y2._mask.__array_interface__ != m.__array_interface__) + self.failUnless( allequal(y2.mask, 0)) y3 = array(x1*1.0, mask=m) - assert(filled(y3).dtype is (x1*1.0).dtype) + self.failUnless(filled(y3).dtype is (x1*1.0).dtype) x4 = arange(4) x4[2] = masked @@ -365,7 +374,7 @@ a_pickled = cPickle.loads(a.dumps()) assert_equal(a_pickled._mask, a._mask) assert_equal(a_pickled, a) - assert(isinstance(a_pickled._data,np.matrix)) + self.failUnless(isinstance(a_pickled._data,np.matrix)) def test_single_element_subscript(self): @@ -392,7 +401,7 @@ a = array([1,2,3],mask=[1,0,0]) self.assertRaises(TypeError, lambda:float(a)) assert_equal(float(a[-1]), 3.) - assert(np.isnan(float(a[0]))) + self.failUnless(np.isnan(float(a[0]))) self.assertRaises(TypeError, int, a) assert_equal(int(a[-1]), 3) self.assertRaises(MAError, lambda:int(a[0])) @@ -566,11 +575,11 @@ "Tests some scalar arithmetics on MaskedArrays." # Masked singleton should remain masked no matter what xm = array(0, mask=1) - assert((1/array(0)).mask) - assert((1 + xm).mask) - assert((-xm).mask) - assert(maximum(xm, xm).mask) - assert(minimum(xm, xm).mask) + self.failUnless((1/array(0)).mask) + self.failUnless((1 + xm).mask) + self.failUnless((-xm).mask) + self.failUnless(maximum(xm, xm).mask) + self.failUnless(minimum(xm, xm).mask) def test_arithmetic_with_masked_singleton(self): "Checks that there's no collapsing to masked" @@ -624,7 +633,7 @@ def test_count_func (self): "Tests count" ott = array([0.,1.,2.,3.], mask=[1,0,0,0]) - assert( isinstance(count(ott), int)) + self.failUnless( isinstance(count(ott), int)) assert_equal(3, count(ott)) assert_equal(1, count(1)) assert_equal(0, array(1,mask=[1])) @@ -661,19 +670,19 @@ def test_minimummaximum_func(self): a = np.ones((2,2)) aminimum = minimum(a,a) - assert(isinstance(aminimum, MaskedArray)) + self.failUnless(isinstance(aminimum, MaskedArray)) assert_equal(aminimum, np.minimum(a,a)) # aminimum = minimum.outer(a,a) - assert(isinstance(aminimum, MaskedArray)) + self.failUnless(isinstance(aminimum, MaskedArray)) assert_equal(aminimum, np.minimum.outer(a,a)) # amaximum = maximum(a,a) - assert(isinstance(amaximum, MaskedArray)) + self.failUnless(isinstance(amaximum, MaskedArray)) assert_equal(amaximum, np.maximum(a,a)) # amaximum = maximum.outer(a,a) - assert(isinstance(amaximum, MaskedArray)) + self.failUnless(isinstance(amaximum, MaskedArray)) assert_equal(amaximum, np.maximum.outer(a,a)) def test_minmax_funcs_with_output(self): @@ -688,11 +697,11 @@ # Use the np version nout = np.empty((4,), dtype=int) result = npfunc(xm,axis=0,out=nout) - assert(result is nout) + self.failUnless(result is nout) # Use the ma version nout.fill(-999) result = mafunc(xm,axis=0,out=nout) - assert(result is nout) + self.failUnless(result is nout) def test_minmax_methods(self): @@ -700,22 +709,22 @@ (_, _, _, _, _, xm, _, _, _, _) = self.d xm.shape = (xm.size,) assert_equal(xm.max(), 10) - assert(xm[0].max() is masked) - assert(xm[0].max(0) is masked) - assert(xm[0].max(-1) is masked) + self.failUnless(xm[0].max() is masked) + self.failUnless(xm[0].max(0) is masked) + self.failUnless(xm[0].max(-1) is masked) assert_equal(xm.min(), -10.) - assert(xm[0].min() is masked) - assert(xm[0].min(0) is masked) - assert(xm[0].min(-1) is masked) + self.failUnless(xm[0].min() is masked) + self.failUnless(xm[0].min(0) is masked) + self.failUnless(xm[0].min(-1) is masked) assert_equal(xm.ptp(), 20.) - assert(xm[0].ptp() is masked) - assert(xm[0].ptp(0) is masked) - assert(xm[0].ptp(-1) is masked) + self.failUnless(xm[0].ptp() is masked) + self.failUnless(xm[0].ptp(0) is masked) + self.failUnless(xm[0].ptp(-1) is masked) # x = array([1,2,3], mask=True) - assert(x.min() is masked) - assert(x.max() is masked) - assert(x.ptp() is masked) + self.failUnless(x.min() is masked) + self.failUnless(x.max() is masked) + self.failUnless(x.ptp() is masked) #........................ def test_addsumprod (self): "Tests add, sum, product." @@ -788,13 +797,13 @@ output.fill(-9999) result = npfunc(xm, axis=0,out=output) # ... the result should be the given output - assert(result is output) + self.failUnless(result is output) assert_equal(result, xmmeth(axis=0, out=output)) # output = empty(4, dtype=int) result = xmmeth(axis=0, out=output) - assert(result is output) - assert(output[0] is masked) + self.failUnless(result is output) + self.failUnless(output[0] is masked) #------------------------------------------------------------------------------ @@ -828,8 +837,8 @@ assert_equal(xs._data, [0,10,2,3,40]) #assert_equal(xh.mask.ctypes._data, m.ctypes._data) assert_equal(xs.mask, [0,0,0,1,0]) - assert(xh._hardmask) - assert(not xs._hardmask) + self.failUnless(xh._hardmask) + self.failUnless(not xs._hardmask) xh[1:4] = [10,20,30] xs[1:4] = [10,20,30] assert_equal(xh._data, [0,10,20,3,4]) @@ -922,39 +931,39 @@ ndtype = [('a',int),('b',float),('c',"|S3")] # A check on a list should return a single record fval = _check_fill_value([-999,-999.9,"???"], ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [-999,-999.9,"???"]) # A check on Non should output the defaults fval = _check_fill_value(None, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [default_fill_value(0), default_fill_value(0.), default_fill_value("0")]) #.....Using a flexible type as fill_value should work fill_val = np.array((-999,-999.9,"???"),dtype=ndtype) fval = _check_fill_value(fill_val, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [-999,-999.9,"???"]) #.....Using a flexible type w/ a different type shouldn't matter fill_val = np.array((-999,-999.9,"???"), dtype=[("A",int),("B",float),("C","|S3")]) fval = _check_fill_value(fill_val, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [-999,-999.9,"???"]) #.....Using an object-array shouldn't matter either fill_value = np.array((-999,-999.9,"???"), dtype=object) fval = _check_fill_value(fill_val, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [-999,-999.9,"???"]) # fill_value = np.array((-999,-999.9,"???")) fval = _check_fill_value(fill_val, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), [-999,-999.9,"???"]) #.....One-field-only flexible type should work as well ndtype = [("a",int)] fval = _check_fill_value(-999, ndtype) - assert(isinstance(fval,ndarray)) + self.failUnless(isinstance(fval,ndarray)) assert_equal(fval.item(), (-999,)) @@ -1078,8 +1087,8 @@ def test_reduce(self): "Tests reduce on MaskedArrays." a = self.d[0] - assert(not alltrue(a,axis=0)) - assert(sometrue(a,axis=0)) + self.failUnless(not alltrue(a,axis=0)) + self.failUnless(sometrue(a,axis=0)) assert_equal(sum(a[:3],axis=0), 0) assert_equal(product(a,axis=0), 0) assert_equal(add.reduce(a), pi) @@ -1092,8 +1101,8 @@ assert_equal(amask.min(), 5) assert_equal(amask.max(0), a.max(0)) assert_equal(amask.min(0), [5,6,7,8]) - assert(amask.max(1)[0].mask) - assert(amask.min(1)[0].mask) + self.failUnless(amask.max(1)[0].mask) + self.failUnless(amask.min(1)[0].mask) #------------------------------------------------------------------------------ @@ -1346,18 +1355,18 @@ store = empty(1, dtype=bool) full = array([1,2,3], mask=True) # - assert(full.all() is masked) + self.failUnless(full.all() is masked) full.all(out=store) - assert(store) - assert(store._mask, True) - assert(store is not masked) + self.failUnless(store) + self.failUnless(store._mask, True) + self.failUnless(store is not masked) # store = empty(1, dtype=bool) - assert(full.any() is masked) + self.failUnless(full.any() is masked) full.any(out=store) - assert(not store) - assert(store._mask, True) - assert(store is not masked) + self.failUnless(not store) + self.failUnless(store._mask, True) + self.failUnless(store is not masked) def test_argmax_argmin(self): @@ -1445,7 +1454,7 @@ a = array(np.matrix([1,2,3,4]), mask=[0,0,0,0]) b = a.compressed() assert_equal(b,a) - assert(isinstance(b,np.matrix)) + self.failUnless(isinstance(b,np.matrix)) a[0,0] = masked b = a.compressed() assert_equal(b, [[2,3,4]]) @@ -1473,12 +1482,12 @@ n = [0,0,0,1,1] m = make_mask(n) x = array(d, mask = m) - assert( x[3] is masked) - assert( x[4] is masked) + self.failUnless( x[3] is masked) + self.failUnless( x[4] is masked) x[[1,4]] = [10,40] -# assert( x.mask is not m) - assert( x[3] is masked) - assert( x[4] is not masked) +# self.failUnless( x.mask is not m) + self.failUnless( x[3] is masked) + self.failUnless( x[4] is not masked) assert_equal(x, [0,10,2,-1,40]) # x = masked_array(arange(10), mask=[1,0,0,0,0]*2) @@ -1598,7 +1607,7 @@ # x = [1,4,2,3] sortedx = sort(x) - assert(not isinstance(sorted, MaskedArray)) + self.failUnless(not isinstance(sorted, MaskedArray)) # x = array([0,1,-1,-2,2], mask=nomask, dtype=np.int8) sortedx = sort(x, endwith=False) @@ -1658,7 +1667,7 @@ assert_equal(data.squeeze(), [1,2,3]) assert_equal(data.squeeze()._mask, [1,1,1]) data = masked_array([[1]], mask=True) - assert(data.squeeze() is masked) + self.failUnless(data.squeeze() is masked) def test_swapaxes(self): @@ -1705,8 +1714,8 @@ x = array(np.arange(12)) x[[1,-2]] = masked xlist = x.tolist() - assert(xlist[1] is None) - assert(xlist[-2] is None) + self.failUnless(xlist[1] is None) + self.failUnless(xlist[-2] is None) # x.shape = (3,4) xlist = x.tolist() @@ -1821,12 +1830,12 @@ output.fill(-9999) result = npfunc(xm, axis=0,out=output) # ... the result should be the given output - assert(result is output) + self.failUnless(result is output) assert_equal(result, xmmeth(axis=0, out=output)) # output = empty((3,4), dtype=int) result = xmmeth(axis=0, out=output) - assert(result is output) + self.failUnless(result is output) def test_ptp(self): @@ -1881,31 +1890,31 @@ x = array(arange(10), mask=True) for methodname in ('var', 'std'): method = getattr(x,methodname) - assert(method() is masked) - assert(method(0) is masked) - assert(method(-1) is masked) + self.failUnless(method() is masked) + self.failUnless(method(0) is masked) + self.failUnless(method(-1) is masked) # Using a masked array as explicit output _ = method(out=mout) - assert(mout is not masked) + self.failUnless(mout is not masked) assert_equal(mout.mask, True) # Using a ndarray as explicit output _ = method(out=nout) - assert(np.isnan(nout)) + self.failUnless(np.isnan(nout)) # x = array(arange(10), mask=True) x[-1] = 9 for methodname in ('var', 'std'): method = getattr(x,methodname) - assert(method(ddof=1) is masked) - assert(method(0, ddof=1) is masked) - assert(method(-1, ddof=1) is masked) + self.failUnless(method(ddof=1) is masked) + self.failUnless(method(0, ddof=1) is masked) + self.failUnless(method(-1, ddof=1) is masked) # Using a masked array as explicit output _ = method(out=mout, ddof=1) - assert(mout is not masked) + self.failUnless(mout is not masked) assert_equal(mout.mask, True) # Using a ndarray as explicit output _ = method(out=nout, ddof=1) - assert(np.isnan(nout)) + self.failUnless(np.isnan(nout)) #------------------------------------------------------------------------------ @@ -2023,7 +2032,7 @@ else: raise AssertionError("Should have failed...") test = masked_equal(a,1) - assert(test.mask, [0,1,0,0,0,0,0,0,0,0]) + assert_equal(test.mask, [0,1,0,0,0,0,0,0,0,0]) def test_masked_otherfunctions(self): @@ -2069,24 +2078,24 @@ output.fill(-9999) result = np.round(xm, decimals=2,out=output) # ... the result should be the given output - assert(result is output) + self.failUnless(result is output) assert_equal(result, xm.round(decimals=2, out=output)) # output = empty((3,4), dtype=float) result = xm.round(decimals=2, out=output) - assert(result is output) + self.failUnless(result is output) def test_identity(self): a = identity(5) - assert(isinstance(a, MaskedArray)) + self.failUnless(isinstance(a, MaskedArray)) assert_equal(a, np.identity(5)) def test_power(self): x = -1.1 assert_almost_equal(power(x,2.), 1.21) - assert(power(x,masked) is masked) + self.failUnless(power(x,masked) is masked) x = array([-1.1,-1.1,1.1,1.1,0.]) b = array([0.5,2.,0.5,2.,-1.], mask=[0,0,0,0,1]) y = power(x,b) @@ -2219,7 +2228,7 @@ store = empty(4, dtype=int) chosen = choose([2, 3, 1, 0], choices, out=store) assert_equal(store, array([20, 31, 12, 3])) - assert(store is chosen) + self.failUnless(store is chosen) # Check with some masked indices + out store = empty(4, dtype=int) indices_ = array([2, 3, 1, 0], mask=[1,0,0,1]) @@ -2241,25 +2250,25 @@ # Try the default b = a.reshape((5,2)) assert_equal(b.shape, (5,2)) - assert(b.flags['C']) + self.failUnless(b.flags['C']) # Try w/ arguments as list instead of tuple b = a.reshape(5,2) assert_equal(b.shape, (5,2)) - assert(b.flags['C']) + self.failUnless(b.flags['C']) # Try w/ order b = a.reshape((5,2), order='F') assert_equal(b.shape, (5,2)) - assert(b.flags['F']) + self.failUnless(b.flags['F']) # Try w/ order b = a.reshape(5,2, order='F') assert_equal(b.shape, (5,2)) - assert(b.flags['F']) + self.failUnless(b.flags['F']) # c = np.reshape(a, (2,5)) - assert(isinstance(c, MaskedArray)) + self.failUnless(isinstance(c, MaskedArray)) assert_equal(c.shape, (2,5)) - assert(c[0,0] is masked) - assert(c.flags['C']) + self.failUnless(c[0,0] is masked) + self.failUnless(c.flags['C']) #------------------------------------------------------------------------------ @@ -2371,7 +2380,7 @@ # test = a.view((float,2), np.matrix) assert_equal(test, data) - assert(isinstance(test, np.matrix)) + self.failUnless(isinstance(test, np.matrix)) # def test_getitem(self): ndtype = [('a',float), ('b',float)] @@ -2380,13 +2389,13 @@ [1,0,0,0,0,0,0,0,1,0]), dtype=[('a',bool),('b',bool)]) # No mask - assert(isinstance(a[1], np.void)) + self.failUnless(isinstance(a[1], np.void)) # One element masked - assert(isinstance(a[0], MaskedArray)) + self.failUnless(isinstance(a[0], MaskedArray)) assert_equal_records(a[0]._data, a._data[0]) assert_equal_records(a[0]._mask, a._mask[0]) # All element masked - assert(isinstance(a[-2], MaskedArray)) + self.failUnless(isinstance(a[-2], MaskedArray)) assert_equal_records(a[-2]._data, a._data[-2]) assert_equal_records(a[-2]._mask, a._mask[-2]) Modified: branches/clean_math_config/numpy/ma/tests/test_extras.py =================================================================== --- branches/clean_math_config/numpy/ma/tests/test_extras.py 2008-09-30 02:03:00 UTC (rev 5881) +++ branches/clean_math_config/numpy/ma/tests/test_extras.py 2008-09-30 04:40:13 UTC (rev 5882) @@ -26,7 +26,7 @@ assert_equal(2.0, average(ott, weights=[1., 1., 2., 1.])) result, wts = average(ott, weights=[1.,1.,2.,1.], returned=1) assert_equal(2.0, result) - assert(wts == 4.0) + self.failUnless(wts == 4.0) ott[:] = masked assert_equal(average(ott,axis=0).mask, [True]) ott = array([0.,1.,2.,3.], mask=[1,0,0,0]) @@ -104,7 +104,7 @@ m = [1,0,0,0,0] d = masked_array(b,mask=m) c = mr_[d,0,0,d] - assert(isinstance(c,MaskedArray) or isinstance(c,core.MaskedArray)) + self.failUnless(isinstance(c,MaskedArray) or isinstance(c,core.MaskedArray)) assert_array_equal(c,[1,1,1,1,1,0,0,1,1,1,1,1]) assert_array_equal(c.mask, mr_[m,0,0,m]) @@ -117,12 +117,12 @@ b_1 = masked_array(a_1,mask=m_1) b_2 = masked_array(a_2,mask=m_2) d = mr_['1',b_1,b_2] # append columns - assert(d.shape == (5,10)) + self.failUnless(d.shape == (5,10)) assert_array_equal(d[:,:5],b_1) assert_array_equal(d[:,5:],b_2) assert_array_equal(d.mask, np.r_['1',m_1,m_2]) d = mr_[b_1,b_2] - assert(d.shape == (10,5)) + self.failUnless(d.shape == (10,5)) assert_array_equal(d[:5,:],b_1) assert_array_equal(d[5:,:],b_2) assert_array_equal(d.mask, np.r_[m_1,m_2]) @@ -158,14 +158,14 @@ assert_equal(tmp[-3], slice(0,3,None)) # tmp = notmasked_contiguous(a, 0) - assert(len(tmp[-1]) == 1) - assert(tmp[-2] is None) + self.failUnless(len(tmp[-1]) == 1) + self.failUnless(tmp[-2] is None) assert_equal(tmp[-3],tmp[-1]) - assert(len(tmp[0]) == 2) + self.failUnless(len(tmp[0]) == 2) # tmp = notmasked_contiguous(a, 1) assert_equal(tmp[0][-1], slice(0,3,None)) - assert(tmp[1] is None) + self.failUnless(tmp[1] is None) assert_equal(tmp[2][-1], slice(7,7,None)) assert_equal(tmp[2][-2], slice(0,5,None)) @@ -205,12 +205,12 @@ assert_equal(mask_rowcols(x,0).mask, [[1,1,1],[1,1,1],[0,0,0]] ) assert_equal(mask_rowcols(x,1,).mask, [[1,1,0],[1,1,0],[1,1,0]] ) x = array(x._data, mask=[[1,0,0],[0,1,0],[0,0,1]]) - assert(mask_rowcols(x).all() is masked) - assert(mask_rowcols(x,0).all() is masked) - assert(mask_rowcols(x,1).all() is masked) - assert(mask_rowcols(x).mask.all()) - assert(mask_rowcols(x,0).mask.all()) - assert(mask_rowcols(x,1).mask.all()) + self.failUnless(mask_rowcols(x).all() is masked) + self.failUnless(mask_rowcols(x,0).all() is masked) + self.failUnless(mask_rowcols(x,1).all() is masked) + self.failUnless(mask_rowcols(x).mask.all()) + self.failUnless(mask_rowcols(x,0).mask.all()) + self.failUnless(mask_rowcols(x,1).mask.all()) # def test_dot(self): "Tests dot product" Modified: branches/clean_math_config/numpy/ma/tests/test_mrecords.py =================================================================== --- branches/clean_math_config/numpy/ma/tests/test_mrecords.py 2008-09-30 02:03:00 UTC (rev 5881) +++ branches/clean_math_config/numpy/ma/tests/test_mrecords.py 2008-09-30 04:40:13 UTC (rev 5882) @@ -264,16 +264,16 @@ base = self.base.copy() mbase = base.view(mrecarray) mbase.harden_mask() - assert(mbase._hardmask) + self.failUnless(mbase._hardmask) mbase._mask = nomask assert_equal_records(mbase._mask, base._mask) mbase.soften_mask() - assert(not mbase._hardmask) + self.failUnless(not mbase._hardmask) mbase._mask = nomask # So, the mask of a field is no longer set to nomask... assert_equal_records(mbase._mask, ma.make_mask_none(base.shape,base.dtype)) - assert(ma.make_mask(mbase['b']._mask) is nomask) + self.failUnless(ma.make_mask(mbase['b']._mask) is nomask) assert_equal(mbase['a']._mask,mbase['b']._mask) # def test_pickling(self): @@ -435,7 +435,7 @@ mrectxt = fromtextfile(tmp_fl, delimitor=',',varnames='ABCDEFG') os.remove(tmp_fl) # - assert(isinstance(mrectxt, MaskedRecords)) + self.failUnless(isinstance(mrectxt, MaskedRecords)) assert_equal(mrectxt.F, [1,1,1,1]) assert_equal(mrectxt.E._mask, [1,1,1,1]) assert_equal(mrectxt.C, [1,2,3.e+5,-1e-10]) Modified: branches/clean_math_config/numpy/ma/tests/test_subclassing.py =================================================================== --- branches/clean_math_config/numpy/ma/tests/test_subclassing.py 2008-09-30 02:03:00 UTC (rev 5881) +++ branches/clean_math_config/numpy/ma/tests/test_subclassing.py 2008-09-30 04:40:13 UTC (rev 5882) @@ -76,24 +76,24 @@ m = [0,0,1,0,0] xsub = SubArray(x) xmsub = masked_array(xsub, mask=m) - assert isinstance(xmsub, MaskedArray) + self.failUnless(isinstance(xmsub, MaskedArray)) assert_equal(xmsub._data, xsub) - assert isinstance(xmsub._data, SubArray) + self.failUnless(isinstance(xmsub._data, SubArray)) def test_maskedarray_subclassing(self): "Tests subclassing MaskedArray" x = np.arange(5) mx = mmatrix(x,mask=[0,1,0,0,0]) - assert isinstance(mx._data, np.matrix) + self.failUnless(isinstance(mx._data, np.matrix)) "Tests masked_unary_operation" - assert isinstance(add(mx,mx), mmatrix) - assert isinstance(add(mx,x), mmatrix) + self.failUnless(isinstance(add(mx,mx), mmatrix)) + self.failUnless(isinstance(add(mx,x), mmatrix)) assert_equal(add(mx,x), mx+x) - assert isinstance(add(mx,mx)._data, np.matrix) - assert isinstance(add.outer(mx,mx), mmatrix) + self.failUnless(isinstance(add(mx,mx)._data, np.matrix)) + self.failUnless(isinstance(add.outer(mx,mx), mmatrix)) "Tests masked_binary_operation" - assert isinstance(hypot(mx,mx), mmatrix) - assert isinstance(hypot(mx,x), mmatrix) + self.failUnless(isinstance(hypot(mx,mx), mmatrix)) + self.failUnless(isinstance(hypot(mx,x), mmatrix)) def test_attributepropagation(self): x = array(arange(5), mask=[0]+[1]*4) @@ -101,16 +101,16 @@ ym = msubarray(x) # z = (my+1) - assert isinstance(z,MaskedArray) - assert not isinstance(z, MSubArray) - assert isinstance(z._data, SubArray) + self.failUnless(isinstance(z,MaskedArray)) + self.failUnless(not isinstance(z, MSubArray)) + self.failUnless(isinstance(z._data, SubArray)) assert_equal(z._data.info, {}) # z = (ym+1) - assert isinstance(z, MaskedArray) - assert isinstance(z, MSubArray) - assert isinstance(z._data, SubArray) - assert z._data.info['added'] > 0 + self.failUnless(isinstance(z, MaskedArray)) + self.failUnless(isinstance(z, MSubArray)) + self.failUnless(isinstance(z._data, SubArray)) + self.failUnless(z._data.info['added'] > 0) # ym._set_mask([1,0,0,0,1]) assert_equal(ym._mask, [1,0,0,0,1]) @@ -119,7 +119,7 @@ # xsub = subarray(x, info={'name':'x'}) mxsub = masked_array(xsub) - assert hasattr(mxsub, 'info') + self.failUnless(hasattr(mxsub, 'info')) assert_equal(mxsub.info, xsub.info) def test_subclasspreservation(self): @@ -130,22 +130,22 @@ xsub = MSubArray(x, mask=m, info={'xsub':xinfo}) # mxsub = masked_array(xsub, subok=False) - assert not isinstance(mxsub, MSubArray) - assert isinstance(mxsub, MaskedArray) + self.failUnless(not isinstance(mxsub, MSubArray)) + self.failUnless(isinstance(mxsub, MaskedArray)) assert_equal(mxsub._mask, m) # mxsub = asarray(xsub) - assert not isinstance(mxsub, MSubArray) - assert isinstance(mxsub, MaskedArray) + self.failUnless(not isinstance(mxsub, MSubArray)) + self.failUnless(isinstance(mxsub, MaskedArray)) assert_equal(mxsub._mask, m) # mxsub = masked_array(xsub, subok=True) - assert isinstance(mxsub, MSubArray) + self.failUnless(isinstance(mxsub, MSubArray)) assert_equal(mxsub.info, xsub.info) assert_equal(mxsub._mask, xsub._mask) # mxsub = asanyarray(xsub) - assert isinstance(mxsub, MSubArray) + self.failUnless(isinstance(mxsub, MSubArray)) assert_equal(mxsub.info, xsub.info) assert_equal(mxsub._mask, m) @@ -160,16 +160,16 @@ ym = msubarray(x) # z = (my+1) - assert isinstance(z,MaskedArray) - assert not isinstance(z, MSubArray) - assert isinstance(z._data, SubArray) + self.failUnless(isinstance(z,MaskedArray)) + self.failUnless(not isinstance(z, MSubArray)) + self.failUnless(isinstance(z._data, SubArray)) assert_equal(z._data.info, {}) # z = (ym+1) - assert isinstance(z, MaskedArray) - assert isinstance(z, MSubArray) - assert isinstance(z._data, SubArray) - assert z._data.info['added'] > 0 + self.failUnless(isinstance(z, MaskedArray)) + self.failUnless(isinstance(z, MSubArray)) + self.failUnless(isinstance(z._data, SubArray)) + self.failUnless(z._data.info['added'] > 0) # ym._set_mask([1,0,0,0,1]) assert_equal(ym._mask, [1,0,0,0,1]) Modified: branches/clean_math_config/numpy/ma/testutils.py =================================================================== --- branches/clean_math_config/numpy/ma/testutils.py 2008-09-30 02:03:00 UTC (rev 5881) +++ branches/clean_math_config/numpy/ma/testutils.py 2008-09-30 04:40:13 UTC (rev 5882) @@ -81,10 +81,12 @@ """ # Case #1: dictionary ..... if isinstance(desired, dict): - assert isinstance(actual, dict), repr(type(actual)) + if not isinstance(actual, dict): + raise AssertionError(repr(type(actual))) assert_equal(len(actual),len(desired),err_msg) for k,i in desired.items(): - assert k in actual, repr(k) + if not k in actual: + raise AssertionError("%s not in %s" % (k,actual)) assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg)) return # Case #2: lists ..... @@ -92,7 +94,8 @@ return _assert_equal_on_sequences(actual, desired, err_msg='') if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)): msg = build_err_msg([actual, desired], err_msg,) - assert desired == actual, msg + if not desired == actual: + raise AssertionError(msg) return # Case #4. arrays or equivalent if ((actual is masked) and not (desired is masked)) or \ @@ -122,10 +125,12 @@ """Raises an assertion error if two items are equal. """ if isinstance(desired, dict): - assert isinstance(actual, dict), repr(type(actual)) + if not isinstance(actual, dict): + raise AssertionError(repr(type(actual))) fail_if_equal(len(actual),len(desired),err_msg) for k,i in desired.items(): - assert k in actual, repr(k) + if not k in actual: + raise AssertionError(repr(k)) fail_if_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg)) return if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)): @@ -136,7 +141,8 @@ if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray): return fail_if_array_equal(actual, desired, err_msg) msg = build_err_msg([actual, desired], err_msg) - assert desired != actual, msg + if not desired != actual: + raise AssertionError(msg) assert_not_equal = fail_if_equal @@ -149,7 +155,8 @@ err_msg=err_msg, verbose=verbose) msg = build_err_msg([actual, desired], err_msg=err_msg, verbose=verbose) - assert round(abs(desired - actual),decimal) == 0, msg + if not round(abs(desired - actual),decimal) == 0: + raise AssertionError(msg) assert_close = assert_almost_equal From numpy-svn at scipy.org Tue Sep 30 11:23:47 2008 From: numpy-svn at scipy.org (numpy-svn at scipy.org) Date: Tue, 30 Sep 2008 10:23:47 -0500 (CDT) Subject: [Numpy-svn] r5883 - branches/clean_math_config_chuck/numpy/core/src Message-ID: <20080930152347.CFBE639C249@scipy.org> Author: charris Date: 2008-09-30 10:23:44 -0500 (Tue, 30 Sep 2008) New Revision: 5883 Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src Log: For David to test. Modified: branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src =================================================================== --- branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-30 04:40:13 UTC (rev 5882) +++ branches/clean_math_config_chuck/numpy/core/src/umathmodule.c.src 2008-09-30 15:23:44 UTC (rev 5883) @@ -995,25 +995,16 @@ /**begin repeat1 * #kind = maximum, minimum# - * #OP1 = >=, <=# - * #OP2 = <=, >=# + * #OP = >, <# **/ static void @TYPE at _@kind@(char **args, intp *dimensions, intp *steps, void *func) { - /* Return NaN if either value is NaN */ + /* */ BINARY_LOOP { const @type@ in1 = *(@type@ *)ip1; const @type@ in2 = *(@type@ *)ip2; - if (in1 @OP1@ in2) { - *((@type@ *)op) = in1; - } - else if (in1 @OP2@ in2) { - *((@type@ *)op) = in2; - } - else { - *((@type@ *)op) = NAN; - } + *((@type@ *)op) = in1 @OP@ in2 ? in1 : in2; } } /**end repeat1**/ @@ -1102,7 +1093,7 @@ static void @TYPE at _sign(char **args, intp *dimensions, intp *steps, void *func) { - /* Returns NaN as sign of NaN */ + /* */ UNARY_LOOP { const @type@ in1 = *(@type@ *)ip1; if (in1 > 0) { @@ -1111,13 +1102,9 @@ else if (in1 < 0) { *((@type@ *)op) = -1; } - else if (in1 == 0) { + else { *((@type@ *)op) = 0; } - else { - /* is NaN */ - *((@type@ *)op) = in1; - } } } @@ -1396,14 +1383,22 @@ UNARY_LOOP { const @type@ in1r = ((@type@ *)ip1)[0]; const @type@ in1i = ((@type@ *)ip1)[1]; - if (in1r != 0) { - ((@type@ *)op)[0] = in1r > 0 ? 1 : -1; + if (in1r > 0) { + ((@type@ *)op)[0] = 1; } - else if (in1i != 0) { - ((@type@ *)op)[0] = in1i > 0 ? 1 : -1; + else if (in1r < 0) { + ((@type@ *)op)[0] = -1; } else { - ((@type@ *)op)[0] = 0; + if (in1i > 0) { + ((@type@ *)op)[0] = 1; + } + else if (in1i < 0) { + ((@type@ *)op)[0] = -1; + } + else { + ((@type@ *)op)[0] = 0; + } } ((@type@ *)op)[1] = 0; }